repo_name stringlengths 7 71 | file_path stringlengths 5 118 | context list | import_statement stringlengths 45 12.5k | token_num int64 641 99.4k | cropped_code stringlengths 44 17k | all_code stringlengths 43 754k | next_line stringlengths 2 330 | gold_snippet_index int64 0 68 | created_at stringlengths 25 25 | level stringclasses 9 values |
|---|---|---|---|---|---|---|---|---|---|---|
pytorch-labs/torchfix | torchfix/visitors/vision/pretrained.py | [
{
"identifier": "LintViolation",
"path": "torchfix/common.py",
"snippet": "class LintViolation:\n error_code: str\n message: str\n line: int\n column: int\n node: cst.CSTNode\n replacement: Optional[cst.CSTNode]\n\n def flake8_result(self):\n full_message = f\"{self.error_cod... | from typing import Optional
from libcst.codemod.visitors import ImportItem
from ...common import LintViolation, TorchVisitor
import libcst as cst | 5,544 | ("segmentation.deeplabv3_resnet50", "pretrained"): "DeepLabV3_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.deeplabv3_resnet50", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("segmentation.deeplabv3_resnet101", "pretrained"): "DeepLabV3_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.deeplabv3_resnet101", "pretrained_backbone"): "ResNet101_Weights.IMAGENET1K_V1",
("segmentation.deeplabv3_mobilenet_v3_large", "pretrained"): "DeepLabV3_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.deeplabv3_mobilenet_v3_large", "pretrained_backbone"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
("segmentation.fcn_resnet50", "pretrained"): "FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.fcn_resnet50", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("segmentation.fcn_resnet101", "pretrained"): "FCN_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.fcn_resnet101", "pretrained_backbone"): "ResNet101_Weights.IMAGENET1K_V1",
("detection.ssd300_vgg16", "pretrained"): "SSD300_VGG16_Weights.COCO_V1",
("detection.ssd300_vgg16", "pretrained_backbone"): "VGG16_Weights.IMAGENET1K_FEATURES",
("detection.ssdlite320_mobilenet_v3_large", "pretrained"): "SSDLite320_MobileNet_V3_Large_Weights.COCO_V1",
("detection.ssdlite320_mobilenet_v3_large", "pretrained_backbone"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
}
# fmt: on
# The same model can be imported from torchvision.models directly,
# or from a submodule like torchvision.models.resnet.
MODEL_SUBMODULES = (
"alexnet",
"convnext",
"densenet",
"efficientnet",
"googlenet",
"inception",
"mnasnet",
"mobilenet",
"regnet",
"resnet",
"shufflenetv2",
"squeezenet",
"vgg",
"vision_transformer",
"swin_transformer",
"maxvit",
)
def visit_Call(self, node):
def _new_arg_and_import(
old_arg: cst.Arg, is_backbone: bool
) -> Optional[cst.Arg]:
old_arg_name = "pretrained_backbone" if is_backbone else "pretrained"
if old_arg is None or (model_name, old_arg_name) not in self.MODEL_WEIGHTS:
return None
new_arg_name = "weights_backbone" if is_backbone else "weights"
weights_arg = None
if cst.ensure_type(old_arg.value, cst.Name).value == "True":
weights_str = self.MODEL_WEIGHTS[(model_name, old_arg_name)]
if is_backbone is False and len(model_name.split(".")) > 1:
# Prepend things like 'detection.' to the weights string
weights_str = model_name.split(".")[0] + "." + weights_str
weights_str = "models." + weights_str
weights_arg = cst.ensure_type(
cst.parse_expression(f"f({new_arg_name}={weights_str})"), cst.Call
).args[0]
self.needed_imports.add(
ImportItem(
module_name="torchvision",
obj_name="models",
)
)
elif cst.ensure_type(old_arg.value, cst.Name).value == "False":
weights_arg = cst.ensure_type(
cst.parse_expression(f"f({new_arg_name}=None)"), cst.Call
).args[0]
return weights_arg
qualified_name = self.get_qualified_name_for_call(node)
if qualified_name is None:
return
if qualified_name.startswith("torchvision.models"):
model_name = qualified_name[len("torchvision.models") + 1 :]
for submodule in self.MODEL_SUBMODULES:
if model_name.startswith(submodule + "."):
model_name = model_name[len(submodule) + 1 :]
if (model_name, "pretrained") not in self.MODEL_WEIGHTS:
return
message = None
pretrained_arg = self.get_specific_arg(node, "pretrained", 0)
if pretrained_arg is not None:
message = "Parameter `pretrained` is deprecated, please use `weights` instead."
pretrained_backbone_arg = self.get_specific_arg(
node, "pretrained_backbone", 1
)
if pretrained_backbone_arg is not None:
message = "Parameter `pretrained_backbone` is deprecated, please use `weights_backbone` instead."
replacement_args = list(node.args)
new_pretrained_arg = _new_arg_and_import(pretrained_arg, is_backbone=False)
has_replacement = False
if new_pretrained_arg is not None:
for pos, arg in enumerate(node.args):
if arg is pretrained_arg:
break
replacement_args[pos] = new_pretrained_arg
has_replacement = True
new_pretrained_backbone_arg = _new_arg_and_import(
pretrained_backbone_arg, is_backbone=True
)
if new_pretrained_backbone_arg is not None:
for pos, arg in enumerate(node.args):
if arg is pretrained_backbone_arg:
break
replacement_args[pos] = new_pretrained_backbone_arg
has_replacement = True
replacement = (
node.with_changes(args=replacement_args) if has_replacement else None
)
if message is not None:
position_metadata = self.get_metadata(
cst.metadata.WhitespaceInclusivePositionProvider, node
)
self.violations.append(
|
class TorchVisionDeprecatedPretrainedVisitor(TorchVisitor):
"""
Find and fix deprecated `pretrained` parameters in TorchVision models.
Both `pretrained` and `pretrained_backbone` parameters are supported.
The parameters are updated to the new `weights` and `weights_backbone` parameters
only if the old parameter has explicit literal `True` or `False` value,
otherwise only lint violation is emitted.
"""
ERROR_CODE = "TOR201"
# flake8: noqa: E105
# fmt: off
MODEL_WEIGHTS = {
("mobilenet_v2", "pretrained"): "MobileNet_V2_Weights.IMAGENET1K_V1",
("mobilenet_v3_large", "pretrained"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
("mobilenet_v3_small", "pretrained"): "MobileNet_V3_Small_Weights.IMAGENET1K_V1",
("densenet121", "pretrained"): "DenseNet121_Weights.IMAGENET1K_V1",
("densenet161", "pretrained"): "DenseNet161_Weights.IMAGENET1K_V1",
("densenet169", "pretrained"): "DenseNet169_Weights.IMAGENET1K_V1",
("densenet201", "pretrained"): "DenseNet201_Weights.IMAGENET1K_V1",
("detection.maskrcnn_resnet50_fpn", "pretrained"): "MaskRCNN_ResNet50_FPN_Weights.COCO_V1",
("detection.maskrcnn_resnet50_fpn", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("detection.maskrcnn_resnet50_fpn_v2", "pretrained"): "MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1",
("detection.maskrcnn_resnet50_fpn_v2", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("detection.retinanet_resnet50_fpn", "pretrained"): "RetinaNet_ResNet50_FPN_Weights.COCO_V1",
("detection.retinanet_resnet50_fpn", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("detection.retinanet_resnet50_fpn_v2", "pretrained"): "RetinaNet_ResNet50_FPN_V2_Weights.COCO_V1",
("detection.retinanet_resnet50_fpn_v2", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("optical_flow.raft_large", "pretrained"): "Raft_Large_Weights.C_T_SKHT_V2",
("optical_flow.raft_small", "pretrained"): "Raft_Small_Weights.C_T_V2",
("alexnet", "pretrained"): "AlexNet_Weights.IMAGENET1K_V1",
("convnext_tiny", "pretrained"): "ConvNeXt_Tiny_Weights.IMAGENET1K_V1",
("convnext_small", "pretrained"): "ConvNeXt_Small_Weights.IMAGENET1K_V1",
("convnext_base", "pretrained"): "ConvNeXt_Base_Weights.IMAGENET1K_V1",
("convnext_large", "pretrained"): "ConvNeXt_Large_Weights.IMAGENET1K_V1",
("inception_v3", "pretrained"): "Inception_V3_Weights.IMAGENET1K_V1",
("maxvit_t", "pretrained"): "MaxVit_T_Weights.IMAGENET1K_V1",
("mnasnet0_5", "pretrained"): "MNASNet0_5_Weights.IMAGENET1K_V1",
("mnasnet0_75", "pretrained"): "MNASNet0_75_Weights.IMAGENET1K_V1",
("mnasnet1_0", "pretrained"): "MNASNet1_0_Weights.IMAGENET1K_V1",
("mnasnet1_3", "pretrained"): "MNASNet1_3_Weights.IMAGENET1K_V1",
("detection.fasterrcnn_resnet50_fpn", "pretrained"): "FasterRCNN_ResNet50_FPN_Weights.COCO_V1",
("detection.fasterrcnn_resnet50_fpn", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("detection.fasterrcnn_resnet50_fpn_v2", "pretrained"): "FasterRCNN_ResNet50_FPN_V2_Weights.COCO_V1",
("detection.fasterrcnn_resnet50_fpn_v2", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("detection.fasterrcnn_mobilenet_v3_large_320_fpn", "pretrained"): "FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.COCO_V1",
("detection.fasterrcnn_mobilenet_v3_large_320_fpn", "pretrained_backbone"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
("detection.fasterrcnn_mobilenet_v3_large_fpn", "pretrained"): "FasterRCNN_MobileNet_V3_Large_FPN_Weights.COCO_V1",
("detection.fasterrcnn_mobilenet_v3_large_fpn", "pretrained_backbone"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
("detection.fcos_resnet50_fpn", "pretrained"): "FCOS_ResNet50_FPN_Weights.COCO_V1",
("detection.fcos_resnet50_fpn", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("segmentation.lraspp_mobilenet_v3_large", "pretrained"): "LRASPP_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.lraspp_mobilenet_v3_large", "pretrained_backbone"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
("shufflenet_v2_x0_5", "pretrained"): "ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1",
("shufflenet_v2_x1_0", "pretrained"): "ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1",
("shufflenet_v2_x1_5", "pretrained"): "ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1",
("shufflenet_v2_x2_0", "pretrained"): "ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1",
("squeezenet1_0", "pretrained"): "SqueezeNet1_0_Weights.IMAGENET1K_V1",
("squeezenet1_1", "pretrained"): "SqueezeNet1_1_Weights.IMAGENET1K_V1",
("swin_t", "pretrained"): "Swin_T_Weights.IMAGENET1K_V1",
("swin_s", "pretrained"): "Swin_S_Weights.IMAGENET1K_V1",
("swin_b", "pretrained"): "Swin_B_Weights.IMAGENET1K_V1",
("swin_v2_t", "pretrained"): "Swin_V2_T_Weights.IMAGENET1K_V1",
("swin_v2_s", "pretrained"): "Swin_V2_S_Weights.IMAGENET1K_V1",
("swin_v2_b", "pretrained"): "Swin_V2_B_Weights.IMAGENET1K_V1",
("video.s3d", "pretrained"): "S3D_Weights.KINETICS400_V1",
("video.swin3d_t", "pretrained"): "Swin3D_T_Weights.KINETICS400_V1",
("video.swin3d_s", "pretrained"): "Swin3D_S_Weights.KINETICS400_V1",
("video.swin3d_b", "pretrained"): "Swin3D_B_Weights.KINETICS400_V1",
("vit_b_16", "pretrained"): "ViT_B_16_Weights.IMAGENET1K_V1",
("vit_b_32", "pretrained"): "ViT_B_32_Weights.IMAGENET1K_V1",
("vit_l_16", "pretrained"): "ViT_L_16_Weights.IMAGENET1K_V1",
("vit_l_32", "pretrained"): "ViT_L_32_Weights.IMAGENET1K_V1",
("vit_h_14", "pretrained"): "None",
("vgg11", "pretrained"): "VGG11_Weights.IMAGENET1K_V1",
("vgg11_bn", "pretrained"): "VGG11_BN_Weights.IMAGENET1K_V1",
("vgg13", "pretrained"): "VGG13_Weights.IMAGENET1K_V1",
("vgg13_bn", "pretrained"): "VGG13_BN_Weights.IMAGENET1K_V1",
("vgg16", "pretrained"): "VGG16_Weights.IMAGENET1K_V1",
("vgg16_bn", "pretrained"): "VGG16_BN_Weights.IMAGENET1K_V1",
("vgg19", "pretrained"): "VGG19_Weights.IMAGENET1K_V1",
("vgg19_bn", "pretrained"): "VGG19_BN_Weights.IMAGENET1K_V1",
("video.mvit_v1_b", "pretrained"): "MViT_V1_B_Weights.KINETICS400_V1",
("video.mvit_v2_s", "pretrained"): "MViT_V2_S_Weights.KINETICS400_V1",
("video.r3d_18", "pretrained"): "R3D_18_Weights.KINETICS400_V1",
("video.mc3_18", "pretrained"): "MC3_18_Weights.KINETICS400_V1",
("video.r2plus1d_18", "pretrained"): "R2Plus1D_18_Weights.KINETICS400_V1",
("regnet_y_400mf", "pretrained"): "RegNet_Y_400MF_Weights.IMAGENET1K_V1",
("regnet_y_800mf", "pretrained"): "RegNet_Y_800MF_Weights.IMAGENET1K_V1",
("regnet_y_1_6gf", "pretrained"): "RegNet_Y_1_6GF_Weights.IMAGENET1K_V1",
("regnet_y_3_2gf", "pretrained"): "RegNet_Y_3_2GF_Weights.IMAGENET1K_V1",
("regnet_y_8gf", "pretrained"): "RegNet_Y_8GF_Weights.IMAGENET1K_V1",
("regnet_y_16gf", "pretrained"): "RegNet_Y_16GF_Weights.IMAGENET1K_V1",
("regnet_y_32gf", "pretrained"): "RegNet_Y_32GF_Weights.IMAGENET1K_V1",
("regnet_y_128gf", "pretrained"): "None",
("regnet_x_400mf", "pretrained"): "RegNet_X_400MF_Weights.IMAGENET1K_V1",
("regnet_x_800mf", "pretrained"): "RegNet_X_800MF_Weights.IMAGENET1K_V1",
("regnet_x_1_6gf", "pretrained"): "RegNet_X_1_6GF_Weights.IMAGENET1K_V1",
("regnet_x_3_2gf", "pretrained"): "RegNet_X_3_2GF_Weights.IMAGENET1K_V1",
("regnet_x_8gf", "pretrained"): "RegNet_X_8GF_Weights.IMAGENET1K_V1",
("regnet_x_16gf", "pretrained"): "RegNet_X_16GF_Weights.IMAGENET1K_V1",
("regnet_x_32gf", "pretrained"): "RegNet_X_32GF_Weights.IMAGENET1K_V1",
("resnet18", "pretrained"): "ResNet18_Weights.IMAGENET1K_V1",
("resnet34", "pretrained"): "ResNet34_Weights.IMAGENET1K_V1",
("resnet50", "pretrained"): "ResNet50_Weights.IMAGENET1K_V1",
("resnet101", "pretrained"): "ResNet101_Weights.IMAGENET1K_V1",
("resnet152", "pretrained"): "ResNet152_Weights.IMAGENET1K_V1",
("resnext50_32x4d", "pretrained"): "ResNeXt50_32X4D_Weights.IMAGENET1K_V1",
("resnext101_32x8d", "pretrained"): "ResNeXt101_32X8D_Weights.IMAGENET1K_V1",
("resnext101_64x4d", "pretrained"): "ResNeXt101_64X4D_Weights.IMAGENET1K_V1",
("wide_resnet50_2", "pretrained"): "Wide_ResNet50_2_Weights.IMAGENET1K_V1",
("wide_resnet101_2", "pretrained"): "Wide_ResNet101_2_Weights.IMAGENET1K_V1",
("efficientnet_b0", "pretrained"): "EfficientNet_B0_Weights.IMAGENET1K_V1",
("efficientnet_b1", "pretrained"): "EfficientNet_B1_Weights.IMAGENET1K_V1",
("efficientnet_b2", "pretrained"): "EfficientNet_B2_Weights.IMAGENET1K_V1",
("efficientnet_b3", "pretrained"): "EfficientNet_B3_Weights.IMAGENET1K_V1",
("efficientnet_b4", "pretrained"): "EfficientNet_B4_Weights.IMAGENET1K_V1",
("efficientnet_b5", "pretrained"): "EfficientNet_B5_Weights.IMAGENET1K_V1",
("efficientnet_b6", "pretrained"): "EfficientNet_B6_Weights.IMAGENET1K_V1",
("efficientnet_b7", "pretrained"): "EfficientNet_B7_Weights.IMAGENET1K_V1",
("efficientnet_v2_s", "pretrained"): "EfficientNet_V2_S_Weights.IMAGENET1K_V1",
("efficientnet_v2_m", "pretrained"): "EfficientNet_V2_M_Weights.IMAGENET1K_V1",
("efficientnet_v2_l", "pretrained"): "EfficientNet_V2_L_Weights.IMAGENET1K_V1",
("googlenet", "pretrained"): "GoogLeNet_Weights.IMAGENET1K_V1",
("segmentation.deeplabv3_resnet50", "pretrained"): "DeepLabV3_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.deeplabv3_resnet50", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("segmentation.deeplabv3_resnet101", "pretrained"): "DeepLabV3_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.deeplabv3_resnet101", "pretrained_backbone"): "ResNet101_Weights.IMAGENET1K_V1",
("segmentation.deeplabv3_mobilenet_v3_large", "pretrained"): "DeepLabV3_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.deeplabv3_mobilenet_v3_large", "pretrained_backbone"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
("segmentation.fcn_resnet50", "pretrained"): "FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.fcn_resnet50", "pretrained_backbone"): "ResNet50_Weights.IMAGENET1K_V1",
("segmentation.fcn_resnet101", "pretrained"): "FCN_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1",
("segmentation.fcn_resnet101", "pretrained_backbone"): "ResNet101_Weights.IMAGENET1K_V1",
("detection.ssd300_vgg16", "pretrained"): "SSD300_VGG16_Weights.COCO_V1",
("detection.ssd300_vgg16", "pretrained_backbone"): "VGG16_Weights.IMAGENET1K_FEATURES",
("detection.ssdlite320_mobilenet_v3_large", "pretrained"): "SSDLite320_MobileNet_V3_Large_Weights.COCO_V1",
("detection.ssdlite320_mobilenet_v3_large", "pretrained_backbone"): "MobileNet_V3_Large_Weights.IMAGENET1K_V1",
}
# fmt: on
# The same model can be imported from torchvision.models directly,
# or from a submodule like torchvision.models.resnet.
MODEL_SUBMODULES = (
"alexnet",
"convnext",
"densenet",
"efficientnet",
"googlenet",
"inception",
"mnasnet",
"mobilenet",
"regnet",
"resnet",
"shufflenetv2",
"squeezenet",
"vgg",
"vision_transformer",
"swin_transformer",
"maxvit",
)
def visit_Call(self, node):
def _new_arg_and_import(
old_arg: cst.Arg, is_backbone: bool
) -> Optional[cst.Arg]:
old_arg_name = "pretrained_backbone" if is_backbone else "pretrained"
if old_arg is None or (model_name, old_arg_name) not in self.MODEL_WEIGHTS:
return None
new_arg_name = "weights_backbone" if is_backbone else "weights"
weights_arg = None
if cst.ensure_type(old_arg.value, cst.Name).value == "True":
weights_str = self.MODEL_WEIGHTS[(model_name, old_arg_name)]
if is_backbone is False and len(model_name.split(".")) > 1:
# Prepend things like 'detection.' to the weights string
weights_str = model_name.split(".")[0] + "." + weights_str
weights_str = "models." + weights_str
weights_arg = cst.ensure_type(
cst.parse_expression(f"f({new_arg_name}={weights_str})"), cst.Call
).args[0]
self.needed_imports.add(
ImportItem(
module_name="torchvision",
obj_name="models",
)
)
elif cst.ensure_type(old_arg.value, cst.Name).value == "False":
weights_arg = cst.ensure_type(
cst.parse_expression(f"f({new_arg_name}=None)"), cst.Call
).args[0]
return weights_arg
qualified_name = self.get_qualified_name_for_call(node)
if qualified_name is None:
return
if qualified_name.startswith("torchvision.models"):
model_name = qualified_name[len("torchvision.models") + 1 :]
for submodule in self.MODEL_SUBMODULES:
if model_name.startswith(submodule + "."):
model_name = model_name[len(submodule) + 1 :]
if (model_name, "pretrained") not in self.MODEL_WEIGHTS:
return
message = None
pretrained_arg = self.get_specific_arg(node, "pretrained", 0)
if pretrained_arg is not None:
message = "Parameter `pretrained` is deprecated, please use `weights` instead."
pretrained_backbone_arg = self.get_specific_arg(
node, "pretrained_backbone", 1
)
if pretrained_backbone_arg is not None:
message = "Parameter `pretrained_backbone` is deprecated, please use `weights_backbone` instead."
replacement_args = list(node.args)
new_pretrained_arg = _new_arg_and_import(pretrained_arg, is_backbone=False)
has_replacement = False
if new_pretrained_arg is not None:
for pos, arg in enumerate(node.args):
if arg is pretrained_arg:
break
replacement_args[pos] = new_pretrained_arg
has_replacement = True
new_pretrained_backbone_arg = _new_arg_and_import(
pretrained_backbone_arg, is_backbone=True
)
if new_pretrained_backbone_arg is not None:
for pos, arg in enumerate(node.args):
if arg is pretrained_backbone_arg:
break
replacement_args[pos] = new_pretrained_backbone_arg
has_replacement = True
replacement = (
node.with_changes(args=replacement_args) if has_replacement else None
)
if message is not None:
position_metadata = self.get_metadata(
cst.metadata.WhitespaceInclusivePositionProvider, node
)
self.violations.append( | LintViolation( | 0 | 2023-11-15 01:21:07+00:00 | 8k |
FISHers6/CodeLearn-Agent | codelearn/agents/question_solve.py | [
{
"identifier": "CustomOutputParser",
"path": "codelearn/agents/code_agent.py",
"snippet": "class CustomPromptTemplate(StringPromptTemplate):\nclass CustomOutputParser(AgentOutputParser):\n def format(self, **kwargs) -> str:\n def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:"
... | from typing import Any, List
from langchain.chat_models import ChatOpenAI
from langchain.agents import load_tools, initialize_agent, AgentType
from langchain.schema.embeddings import Embeddings
from langchain.schema.document import Document
from codelearn.agents.code_agent import CustomOutputParser, CustomPromptTemplate, template_with_history
from codelearn.project.project import Project
from langchain.chains import LLMChain
from codelearn.retrieval.code_retriever import CodeRetriever
from codelearn.retrieval.multi_retriever import MultiQueryMultiRetriever
from codelearn.storage.vector import VectorStoreBase
from codelearn.tools.code_search import CodeSearchTool
from codelearn.tools.directory_struct_view import DirectoryStructViewTool
from codelearn.tools.file_content_view import FileContentViewTool
from codelearn.tools.project_struct_view import ProjectStructViewTool
from langchain.chat_models import ChatOpenAI
from langchain.prompts import MessagesPlaceholder
from langchain.tools import BaseTool
from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser
from langchain.memory import ConversationBufferWindowMemory | 3,646 |
def question_solve_agent(
llm: ChatOpenAI,
query: str,
project: Project,
vector_store: VectorStoreBase,
embending: Embeddings,
languages: List[str],
chat_history: Any = {},
max_iterations = 20
):
code_retrival = CodeRetriever(vector_store=vector_store, embending=embending, index_name="code")
multi_retrievel = MultiQueryMultiRetriever.from_llm(retrievers=[code_retrival], llm=llm, project=project, languages=languages)
code_search = CodeSearchTool(
project = project,
multi_retriever = multi_retrievel
)
|
def question_solve_agent(
llm: ChatOpenAI,
query: str,
project: Project,
vector_store: VectorStoreBase,
embending: Embeddings,
languages: List[str],
chat_history: Any = {},
max_iterations = 20
):
code_retrival = CodeRetriever(vector_store=vector_store, embending=embending, index_name="code")
multi_retrievel = MultiQueryMultiRetriever.from_llm(retrievers=[code_retrival], llm=llm, project=project, languages=languages)
code_search = CodeSearchTool(
project = project,
multi_retriever = multi_retrievel
) | directory_struct_view = DirectoryStructViewTool(project = project) | 6 | 2023-11-12 13:13:30+00:00 | 8k |
kirill-vish/Beyond-INet | main.py | [
{
"identifier": "run_imagenetx",
"path": "inference/imagenet_x.py",
"snippet": "@torch.no_grad()\ndef run_imagenetx(data_loader, model, device, model_name):\n model.eval()\n\n total_samples = 0\n max_probs_list = []\n max_indices_list = []\n file_names_list = []\n\n date = datetime.now... | import argparse
import json
import os
import random
import numpy as np
import pandas
import torch
import torch.backends.cudnn as cudnn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import wandb
from collections import defaultdict
from pathlib import Path
from imagenetv2_pytorch import ImageNetV2Dataset
from torchvision import transforms
from inference.imagenet_x import run_imagenetx
from inference.invariance import run_invariance
from inference.pug_imagenet import run_pug_imagenet
from inference.robustness import run_robustness
from utils.misc import (ImageFolderWithPaths, get_world_size,
load_model_transform, resolve_name) | 4,030 | parser.add_argument("--shift_y", type=int, default=0, help="Shift Y")
parser.add_argument("--data_path",
type=str,
default="",
help="dataset path")
parser.add_argument("--pretrained_dir",
type=str,
default="pretrained",
help="pretrained directory")
parser.add_argument(
"--nb_classes",
default=1000,
type=int,
help="number of the classification types",
)
parser.add_argument("--image_size",
default=224,
type=int,
help="image size")
parser.add_argument(
"--output_dir",
default="./outputs",
help="path where to save, empty for no saving",
)
parser.add_argument("--device",
default="cuda",
help="device to use for training / testing")
parser.add_argument("--seed", default=0, type=int)
parser.add_argument("--num_workers", default=10, type=int)
parser.add_argument(
"--pin_mem",
action="store_true",
help=
"Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.",
)
parser.set_defaults(pin_mem=True)
parser.add_argument(
"--num_runs",
default=1,
type=int,
help="number of how many repeated runs of experiment",
)
parser.add_argument("--n_bins",
default=15,
type=int,
help="number of bins in ECE calculation")
parser.add_argument("--run_name", type=str, default="")
parser.add_argument("--dataset", type=str, default="")
parser.add_argument("--debug", action="store_true")
return parser
def main(args):
print("job dir: {}".format(os.path.dirname(os.path.realpath(__file__))))
print("{}".format(args).replace(", ", ",\n"))
device = torch.device(args.device)
seed = args.seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.benchmark = True
model_name = None
transform_val = None
data_loader_val = None
model, transform_val = load_model_transform(args.model,
args.pretrained_dir,
args.image_size)
if transform_val is None:
transform_val = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
print(transform_val)
if args.experiment == "imagenetx" or args.experiment == "pug_imagenet":
dataset_val = ImageFolderWithPaths(root=args.data_path,
transform=transform_val)
else:
if "imagenetv2" in args.data_path:
dataset_val = ImageNetV2Dataset("matched-frequency",
transform=transform_val,
location=args.data_path)
elif "imagenet-r" in args.data_path:
dataset_val = datasets.ImageFolder(os.path.join(args.data_path),
transform=transform_val)
elif "imagenet" in args.data_path:
dataset_val = datasets.ImageFolder(os.path.join(args.data_path),
transform=transform_val)
if args.experiment != "robustness":
data_loader_val = torch.utils.data.DataLoader(
dataset_val,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=True,
shuffle=False,
)
model.to(device)
model.eval()
model_without_ddp = model
n_parameters = sum(p.numel() for p in model.parameters()
if p.requires_grad)
print("Model = %s" % str(model_without_ddp))
print(args.model)
print("number of params (M): %.2f" % (n_parameters / 1.0e6))
|
def get_args_parser():
parser = argparse.ArgumentParser("Beyond ImageNet accuracy")
parser.add_argument(
"--batch_size",
default=512,
type=int,
help="Batch size per GPU (effective batch size is batch_size * # gpus",
)
parser.add_argument("--model",
type=str,
metavar="MODEL",
help="name of model")
parser.add_argument("--experiment",
default="scale",
type=str,
help="Name of model to train")
parser.add_argument("--scale_factor", type=float, help="scale factor")
parser.add_argument("--shift_x", type=int, default=0, help="Shift X")
parser.add_argument("--shift_y", type=int, default=0, help="Shift Y")
parser.add_argument("--data_path",
type=str,
default="",
help="dataset path")
parser.add_argument("--pretrained_dir",
type=str,
default="pretrained",
help="pretrained directory")
parser.add_argument(
"--nb_classes",
default=1000,
type=int,
help="number of the classification types",
)
parser.add_argument("--image_size",
default=224,
type=int,
help="image size")
parser.add_argument(
"--output_dir",
default="./outputs",
help="path where to save, empty for no saving",
)
parser.add_argument("--device",
default="cuda",
help="device to use for training / testing")
parser.add_argument("--seed", default=0, type=int)
parser.add_argument("--num_workers", default=10, type=int)
parser.add_argument(
"--pin_mem",
action="store_true",
help=
"Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.",
)
parser.set_defaults(pin_mem=True)
parser.add_argument(
"--num_runs",
default=1,
type=int,
help="number of how many repeated runs of experiment",
)
parser.add_argument("--n_bins",
default=15,
type=int,
help="number of bins in ECE calculation")
parser.add_argument("--run_name", type=str, default="")
parser.add_argument("--dataset", type=str, default="")
parser.add_argument("--debug", action="store_true")
return parser
def main(args):
print("job dir: {}".format(os.path.dirname(os.path.realpath(__file__))))
print("{}".format(args).replace(", ", ",\n"))
device = torch.device(args.device)
seed = args.seed
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.benchmark = True
model_name = None
transform_val = None
data_loader_val = None
model, transform_val = load_model_transform(args.model,
args.pretrained_dir,
args.image_size)
if transform_val is None:
transform_val = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
print(transform_val)
if args.experiment == "imagenetx" or args.experiment == "pug_imagenet":
dataset_val = ImageFolderWithPaths(root=args.data_path,
transform=transform_val)
else:
if "imagenetv2" in args.data_path:
dataset_val = ImageNetV2Dataset("matched-frequency",
transform=transform_val,
location=args.data_path)
elif "imagenet-r" in args.data_path:
dataset_val = datasets.ImageFolder(os.path.join(args.data_path),
transform=transform_val)
elif "imagenet" in args.data_path:
dataset_val = datasets.ImageFolder(os.path.join(args.data_path),
transform=transform_val)
if args.experiment != "robustness":
data_loader_val = torch.utils.data.DataLoader(
dataset_val,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=True,
shuffle=False,
)
model.to(device)
model.eval()
model_without_ddp = model
n_parameters = sum(p.numel() for p in model.parameters()
if p.requires_grad)
print("Model = %s" % str(model_without_ddp))
print(args.model)
print("number of params (M): %.2f" % (n_parameters / 1.0e6))
| eff_batch_size = args.batch_size * get_world_size() | 5 | 2023-11-15 22:22:06+00:00 | 8k |
shengliu66/ICV | tasks/base.py | [
{
"identifier": "hf_datasets_root",
"path": "anchor.py",
"snippet": ""
},
{
"identifier": "TokenizedForStyleRightPad",
"path": "tasks/loader.py",
"snippet": "class TokenizedForStyleRightPad(Dataset):\n def __init__(self, data, tok: PreTrainedTokenizer, prompt_fn, mode = 'eval', no_pad... | import json
import logging
import random
import re
import torch
import numpy as np
import datasets
from collections import defaultdict
from anchor import hf_datasets_root
from tasks.loader import TokenizedForStyleRightPad
from utils.rng_ctx import RandomContext, EmptyContext
from utils.pca import PCA
from utils.context_manager import modified_forward_context_manager, traced_forward_context_manager | 4,288 | dataset_name, subset, split = self.dataset_part(part)
data = self.do_download(dataset_name, subset, split=split, cache_dir=str(hf_datasets_root))
if part == "sample":
data = data.train_test_split(test_size=0.4)['train']
if part == "result":
data = data.train_test_split(test_size=0.4)['test']
data.to_json(f_path)
logger.info(f"... success, saved at: {f_path}")
@staticmethod
def do_download(dataset_name, subset, split, cache_dir):
raw_data = datasets.load_dataset(dataset_name, subset, split=split, cache_dir=cache_dir)
logger.info("Download success.")
return raw_data
def mk_result_dataset(self, tokenizer, no_padding=False, prefix=''):
return TokenizedForStyleRightPad(self.raw_data_result, tokenizer, self.paralell_style_promptify, no_padding=no_padding, prefix=prefix)
def mk_test_dataset(self, tokenzier):
return self.mk_result_dataset(tokenzier)
def mk_dev_dataset(self, tokenizer):
sample_size = len(self.raw_data_result)
ans_set = set(e["answer_idx"] for e in self.raw_data_sample)
ans_map = defaultdict(list)
for idx, e in enumerate(self.raw_data_sample):
label = e["answer_idx"]
ans_map[label].append(idx)
per_label = sample_size // len(ans_set)
residual = sample_size - per_label * len(ans_set)
selected_ids = []
with self._rng_context:
for label, all_ids in ans_map.items():
selected = random.sample(all_ids, per_label)
selected_ids.extend(selected)
remain_ids = set(range(len(self.raw_data_sample))) - set(selected_ids)
residual_selected = random.sample(remain_ids, residual)
selected_ids.extend(residual_selected)
random.shuffle(selected_ids)
self.raw_data_dev = [self.raw_data_sample[i] for i in selected_ids]
return TokenizedForStyleRightPad(self.raw_data_dev, tokenizer, self.paralell_style_promptify)
def mk_finetune_dataset(self, tokenizer, mode = 'ft'):
selected_exemplar = self._cahced_selected_exemplar
assert (selected_exemplar != None), "No demonstration is selected yet, run stratified_sampling first! \n"
return TokenizedForStyleRightPad(selected_exemplar, tokenizer, self.paralell_style_promptify, mode=mode)
def mk_result_dataset_with_demostration(self, tokenizer, exemplar_str, no_padding=False):
def add_demostration(query, return_reference = False, Instruction = ''):
if return_reference:
with_query, with_query_and_paraphrase, references = self.paralell_style_promptify(query, return_reference=return_reference, Instruction=Instruction)
with_query = with_query.replace(Instruction,"")
with_query_and_paraphrase = with_query_and_paraphrase.replace(Instruction,"")
return f"{exemplar_str}{with_query}", f"{exemplar_str}{with_query_and_paraphrase}", references
else:
with_query, with_query_and_paraphrase = self.paralell_style_promptify(query, return_reference=return_reference, Instruction=Instruction)
with_query = with_query.replace(Instruction,"")
with_query_and_paraphrase = with_query_and_paraphrase.replace(Instruction,"")
return f"{exemplar_str}{with_query}", f"{exemplar_str}{with_query_and_paraphrase}"
return TokenizedForStyleRightPad(self.raw_data_result, tokenizer, add_demostration, no_padding=no_padding)
@staticmethod
def modified_forward(model, inputs, forward_modifiers = ()):
context_manager = modified_forward_context_manager(model, forward_modifiers=forward_modifiers)
input_ids = torch.tensor(inputs['input_ids'])
attention_mask = torch.tensor(inputs['attention_mask'])
with context_manager:
outputs = model(
input_ids=input_ids.unsqueeze(0).cuda(),
attention_mask=attention_mask.unsqueeze(0).cuda(),
)
return outputs
@staticmethod
def traced_forward(model, inputs, forward_modifiers = (), with_submodules=False):
context_manager, forward_trace = traced_forward_context_manager(model, with_submodules=with_submodules)
with context_manager:
outputs = BaseProbInference.modified_forward(
model,
inputs=inputs,
forward_modifiers=forward_modifiers,
)
return outputs, forward_trace
@staticmethod
def get_latentstates(model, inputs):
h_all = []
for example_id in range(len(inputs)):
latents_for_all_styles= []
for style_id in range(len(inputs[example_id])):
_, forward_trace = BaseProbInference.traced_forward(model, inputs[example_id][style_id], with_submodules=False)
task_latents = forward_trace.residual_stream.hidden[:, :, -4:, :].mean(2,keepdim=False) #[:, :, -1, :] # get last token
task_latents = task_latents[:, 1:] # the first one is the embedding layer (num_data, num_layers, hidden_size)
latents_for_all_styles.append(task_latents)
h_all.append(tuple(latents_for_all_styles))
return h_all
@staticmethod
def get_icv(model, inputs, rank=1):
hidden_states = BaseProbInference.get_latentstates(model, inputs)
_, num_layers, hidden_dim = hidden_states[0][0].size()
hidden_states_all = []
num_demonstration = len(hidden_states)
for demonstration_id in range(num_demonstration):
h = hidden_states[demonstration_id][0].flatten() - hidden_states[demonstration_id][1].flatten()
hidden_states_all.append(h)
fit_data = torch.stack(hidden_states_all)
|
logger = logging.getLogger("task")
class BaseProbInference:
def __init__(self, prompt_version):
if prompt_version == "default":
self.prompt_version = self.default_prompt_version()
else:
self.prompt_version = prompt_version
self.raw_data_sample = None
self.raw_data_dev = None
self.can_be_stratified = False
self.num_base_shot = 1
self._rng_context = EmptyContext()
self._cached_prefix = None
self._cached_ex_list = None
self._cahced_selected_exemplar = None
self.shuffled_mapping = None
def default_prompt_version(self):
raise NotImplementedError
def set_seed(self, seed):
self._rng_context = RandomContext(seed=seed)
def dataset_signature(self):
# {
# "result": (dataset_name, subset, split), # which produce the final result
# "sample": (dataset_name, subset, split), # which we sample ICL few-shot examples
# }
raise NotImplementedError
def dataset_part(self, part):
return self.dataset_signature()[part]
def dataset_preprocess(self, raw_data):
raise NotImplementedError
def handcrafted_exemplars(self):
raise NotImplementedError
def exemplar_seperator(self):
raise NotImplementedError
def paralell_style_promptify(self, query):
raise NotImplementedError
def shuffle_exemplars(self):
prefix = self._cached_prefix
ex_list = self._cached_ex_list
ex_list_with_idx = list(enumerate(ex_list))
with self._rng_context:
random.shuffle(ex_list_with_idx)
indices, ex_list = zip(*ex_list_with_idx)
self.shuffled_mapping = indices
return self.build_exemplar_from_examples(prefix, ex_list)
def random_selected_exemplars(self, num_shots, prefix = ""):
with self._rng_context:
num_shots = min(len(self.raw_data_sample), num_shots)
sampled = random.sample(self.raw_data_sample, num_shots)
self._cahced_selected_exemplar = sampled
ex_list = [e["query"] for e in sampled]
self._cached_prefix = prefix
self._cached_ex_list = ex_list
return self.build_exemplar_from_examples(prefix, ex_list)
def stratified_sampling(self, num_k_shots):
num_shots = self.num_base_shot * num_k_shots
if not self.can_be_stratified:
logger.info("Cannot be stratified, fallback to random selection.")
return self.random_selected_exemplars(num_shots)
prefix = ""
ans_set = set(e["answer_idx"] for e in self.raw_data_sample)
ans_map = defaultdict(list)
for idx, e in enumerate(self.raw_data_sample):
label = e["answer_idx"]
ans_map[label].append(idx)
per_label = num_shots // len(ans_set)
residual = num_shots - per_label * len(ans_set)
selected_ids = []
with self._rng_context:
for label, all_ids in ans_map.items():
selected = random.sample(all_ids, per_label)
selected_ids.extend(selected)
remain_ids = set(range(len(self.raw_data_sample))) - set(selected_ids)
residual_selected = random.sample(remain_ids, residual)
selected_ids.extend(residual_selected)
random.shuffle(selected_ids)
selected_exemplar = [self.raw_data_sample[i] for i in selected_ids]
self._cahced_selected_exemplar = selected_exemplar
ex_list = [e["query"] for e in selected_exemplar]
self._cached_prefix = prefix
self._cached_ex_list = ex_list
return self.build_exemplar_from_examples(prefix, ex_list)
def build_exemplar_from_examples(self, prefix, ex_list):
s = prefix
if len(s):
s += self.exemplar_seperator()
for query in ex_list:
_, line = self.paralell_style_promptify(query) # query, <query_with_answer>
s += line + self.exemplar_seperator()
return s
def dataset_file_path(self, part):
dataset_name, subset, split = self.dataset_part(part)
dumped_folder = hf_datasets_root.joinpath("dumped")
if not dumped_folder.exists():
dumped_folder.mkdir(parents=True)
if part == "sample":
split = 'train'
if part == "result":
split = 'test'
file_name = f"{dataset_name}-{subset}-{split}.jsonl"
file_name = re.sub(r"[^\w_. -]", "_", file_name)
return dumped_folder.joinpath(file_name)
def do_load_part(self, part):
f_path = self.dataset_file_path(part)
print(f_path)
if not f_path.exists():
self.not_exist_download(part)
return self.do_load_part(part) # call once more
else:
with f_path.open("r") as f:
raw_data = [json.loads(line) for line in f]
data = self.dataset_preprocess(raw_data)
logger.info(f"Data loaded: {part}.")
return data
def do_load(self):
self.raw_data_sample = self.do_load_part("sample")
self.raw_data_result = self.do_load_part("result")
def not_exist_download(self, part):
f_path = self.dataset_file_path(part)
logger.info(f"{f_path} not exist, download from huggingface datasets hub...")
dataset_name, subset, split = self.dataset_part(part)
data = self.do_download(dataset_name, subset, split=split, cache_dir=str(hf_datasets_root))
if part == "sample":
data = data.train_test_split(test_size=0.4)['train']
if part == "result":
data = data.train_test_split(test_size=0.4)['test']
data.to_json(f_path)
logger.info(f"... success, saved at: {f_path}")
@staticmethod
def do_download(dataset_name, subset, split, cache_dir):
raw_data = datasets.load_dataset(dataset_name, subset, split=split, cache_dir=cache_dir)
logger.info("Download success.")
return raw_data
def mk_result_dataset(self, tokenizer, no_padding=False, prefix=''):
return TokenizedForStyleRightPad(self.raw_data_result, tokenizer, self.paralell_style_promptify, no_padding=no_padding, prefix=prefix)
def mk_test_dataset(self, tokenzier):
return self.mk_result_dataset(tokenzier)
def mk_dev_dataset(self, tokenizer):
sample_size = len(self.raw_data_result)
ans_set = set(e["answer_idx"] for e in self.raw_data_sample)
ans_map = defaultdict(list)
for idx, e in enumerate(self.raw_data_sample):
label = e["answer_idx"]
ans_map[label].append(idx)
per_label = sample_size // len(ans_set)
residual = sample_size - per_label * len(ans_set)
selected_ids = []
with self._rng_context:
for label, all_ids in ans_map.items():
selected = random.sample(all_ids, per_label)
selected_ids.extend(selected)
remain_ids = set(range(len(self.raw_data_sample))) - set(selected_ids)
residual_selected = random.sample(remain_ids, residual)
selected_ids.extend(residual_selected)
random.shuffle(selected_ids)
self.raw_data_dev = [self.raw_data_sample[i] for i in selected_ids]
return TokenizedForStyleRightPad(self.raw_data_dev, tokenizer, self.paralell_style_promptify)
def mk_finetune_dataset(self, tokenizer, mode = 'ft'):
selected_exemplar = self._cahced_selected_exemplar
assert (selected_exemplar != None), "No demonstration is selected yet, run stratified_sampling first! \n"
return TokenizedForStyleRightPad(selected_exemplar, tokenizer, self.paralell_style_promptify, mode=mode)
def mk_result_dataset_with_demostration(self, tokenizer, exemplar_str, no_padding=False):
def add_demostration(query, return_reference = False, Instruction = ''):
if return_reference:
with_query, with_query_and_paraphrase, references = self.paralell_style_promptify(query, return_reference=return_reference, Instruction=Instruction)
with_query = with_query.replace(Instruction,"")
with_query_and_paraphrase = with_query_and_paraphrase.replace(Instruction,"")
return f"{exemplar_str}{with_query}", f"{exemplar_str}{with_query_and_paraphrase}", references
else:
with_query, with_query_and_paraphrase = self.paralell_style_promptify(query, return_reference=return_reference, Instruction=Instruction)
with_query = with_query.replace(Instruction,"")
with_query_and_paraphrase = with_query_and_paraphrase.replace(Instruction,"")
return f"{exemplar_str}{with_query}", f"{exemplar_str}{with_query_and_paraphrase}"
return TokenizedForStyleRightPad(self.raw_data_result, tokenizer, add_demostration, no_padding=no_padding)
@staticmethod
def modified_forward(model, inputs, forward_modifiers = ()):
context_manager = modified_forward_context_manager(model, forward_modifiers=forward_modifiers)
input_ids = torch.tensor(inputs['input_ids'])
attention_mask = torch.tensor(inputs['attention_mask'])
with context_manager:
outputs = model(
input_ids=input_ids.unsqueeze(0).cuda(),
attention_mask=attention_mask.unsqueeze(0).cuda(),
)
return outputs
@staticmethod
def traced_forward(model, inputs, forward_modifiers = (), with_submodules=False):
context_manager, forward_trace = traced_forward_context_manager(model, with_submodules=with_submodules)
with context_manager:
outputs = BaseProbInference.modified_forward(
model,
inputs=inputs,
forward_modifiers=forward_modifiers,
)
return outputs, forward_trace
@staticmethod
def get_latentstates(model, inputs):
h_all = []
for example_id in range(len(inputs)):
latents_for_all_styles= []
for style_id in range(len(inputs[example_id])):
_, forward_trace = BaseProbInference.traced_forward(model, inputs[example_id][style_id], with_submodules=False)
task_latents = forward_trace.residual_stream.hidden[:, :, -4:, :].mean(2,keepdim=False) #[:, :, -1, :] # get last token
task_latents = task_latents[:, 1:] # the first one is the embedding layer (num_data, num_layers, hidden_size)
latents_for_all_styles.append(task_latents)
h_all.append(tuple(latents_for_all_styles))
return h_all
@staticmethod
def get_icv(model, inputs, rank=1):
hidden_states = BaseProbInference.get_latentstates(model, inputs)
_, num_layers, hidden_dim = hidden_states[0][0].size()
hidden_states_all = []
num_demonstration = len(hidden_states)
for demonstration_id in range(num_demonstration):
h = hidden_states[demonstration_id][0].flatten() - hidden_states[demonstration_id][1].flatten()
hidden_states_all.append(h)
fit_data = torch.stack(hidden_states_all) | pca = PCA(n_components=rank).to(fit_data.device).fit(fit_data.float()) | 4 | 2023-11-11 18:20:45+00:00 | 8k |
Fraunhofer-SCAI/corr_shap | corr_shap/sampling/sampling_factory.py | [
{
"identifier": "SamplingStrategy",
"path": "corr_shap/sampling/SamplingStrategy.py",
"snippet": "class SamplingStrategy:\n def __init__(self, explainer, **kwargs):\n \"\"\" Construct all necessary attributes for the SamplingStrategy object.\"\"\"\n self.data = explainer.data.data\n ... | from .SamplingStrategy import SamplingStrategy
from .GaussStrategy import GaussStrategy
from .CopulaStrategy import CopulaStrategy
from .EmpiricalStrategy import EmpiricalStrategy
from .GaussEmpiricalStrategy import GaussEmpiricalStrategy
from .CopulaEmpiricalStrategy import CopulaEmpiricalStrategy | 5,026 |
def get_sampling_strategy(type, explainer, kwargs):
"""Assign the sampling strategy method to the explainer based on the given type. """
sampling_strategies = {"default": SamplingStrategy, "gauss": GaussStrategy, "copula": CopulaStrategy,
"empirical": EmpiricalStrategy, "gauss+empirical": GaussEmpiricalStrategy,
|
def get_sampling_strategy(type, explainer, kwargs):
"""Assign the sampling strategy method to the explainer based on the given type. """
sampling_strategies = {"default": SamplingStrategy, "gauss": GaussStrategy, "copula": CopulaStrategy,
"empirical": EmpiricalStrategy, "gauss+empirical": GaussEmpiricalStrategy, | "copula+empirical": CopulaEmpiricalStrategy} | 5 | 2023-11-14 08:56:18+00:00 | 8k |
RapidAI/TableStructureRec | wired_table_rec/table_line_rec.py | [
{
"identifier": "OrtInferSession",
"path": "wired_table_rec/utils.py",
"snippet": "class OrtInferSession:\n def __init__(self, model_path: Union[str, Path], num_threads: int = -1):\n self.verify_exist(model_path)\n\n self.num_threads = num_threads\n self._init_sess_opt()\n\n ... | from typing import Any, Dict, Optional
from .utils import OrtInferSession
from .utils_table_line_rec import (
bbox_decode,
bbox_post_process,
gbox_decode,
gbox_post_process,
get_affine_transform,
group_bbox_by_gbox,
nms,
)
from .utils_table_recover import merge_adjacent_polys, sorted_boxes
import cv2
import numpy as np | 4,480 | # -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: liekkaskono@163.com
class TableLineRecognition:
def __init__(self, model_path: str = None):
self.K = 1000
self.MK = 4000
self.mean = np.array([0.408, 0.447, 0.470], dtype=np.float32).reshape(1, 1, 3)
self.std = np.array([0.289, 0.274, 0.278], dtype=np.float32).reshape(1, 1, 3)
self.inp_height = 1024
self.inp_width = 1024
self.session = OrtInferSession(model_path)
def __call__(self, img: np.ndarray) -> Optional[np.ndarray]:
img_info = self.preprocess(img)
pred = self.infer(img_info)
polygons = self.postprocess(pred)
if polygons.size == 0:
return None
polygons = polygons.reshape(polygons.shape[0], 4, 2)
| # -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: liekkaskono@163.com
class TableLineRecognition:
def __init__(self, model_path: str = None):
self.K = 1000
self.MK = 4000
self.mean = np.array([0.408, 0.447, 0.470], dtype=np.float32).reshape(1, 1, 3)
self.std = np.array([0.289, 0.274, 0.278], dtype=np.float32).reshape(1, 1, 3)
self.inp_height = 1024
self.inp_width = 1024
self.session = OrtInferSession(model_path)
def __call__(self, img: np.ndarray) -> Optional[np.ndarray]:
img_info = self.preprocess(img)
pred = self.infer(img_info)
polygons = self.postprocess(pred)
if polygons.size == 0:
return None
polygons = polygons.reshape(polygons.shape[0], 4, 2) | polygons = sorted_boxes(polygons) | 9 | 2023-11-11 08:37:11+00:00 | 8k |
davep/tinboard | tinboard/app.py | [
{
"identifier": "Main",
"path": "tinboard/screens/main.py",
"snippet": "class Main(Screen[None]):\n \"\"\"The main application screen.\"\"\"\n\n CONTEXT_HELP = \"\"\"\n ## Application keys and commands\n\n The following keys and commands are available throughout the application:\n\n | Key... | import os
from textual.app import App
from textual.binding import Binding
from .screens import Main, TokenInput
from .data import load_configuration, save_configuration, token_file, ExitStates | 5,627 | """The main application class."""
##############################################################################
# Backward compatibility.
from __future__ import annotations
##############################################################################
# Python imports.
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class Tinboard(App[ExitStates]):
"""The application."""
BINDINGS = [
Binding("ctrl+backslash", "gndn"),
Binding("ctrl+p", "command_palette", priority=True),
]
def __init__(self) -> None:
"""Initialise the application."""
super().__init__()
self.dark = load_configuration().dark_mode
def token_bounce(self, token: str | None) -> None:
"""Handle the result of asking the user for their API token.
Args:
token: The resulting token.
"""
if token:
token_file().write_text(token, encoding="utf-8")
| """The main application class."""
##############################################################################
# Backward compatibility.
from __future__ import annotations
##############################################################################
# Python imports.
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class Tinboard(App[ExitStates]):
"""The application."""
BINDINGS = [
Binding("ctrl+backslash", "gndn"),
Binding("ctrl+p", "command_palette", priority=True),
]
def __init__(self) -> None:
"""Initialise the application."""
super().__init__()
self.dark = load_configuration().dark_mode
def token_bounce(self, token: str | None) -> None:
"""Handle the result of asking the user for their API token.
Args:
token: The resulting token.
"""
if token:
token_file().write_text(token, encoding="utf-8") | self.push_screen(Main(token)) | 0 | 2023-11-13 08:19:41+00:00 | 8k |
wurenkai/MHA-UNet | train_cou.py | [
{
"identifier": "MHA_UNet",
"path": "models/model.py",
"snippet": "class MHA_UNet(nn.Module):\n\n def __init__(self, num_classes=1, input_channels=3, pretrained=None,use_checkpoint=False, c_list=[16, 32, 64, 128, 256],\n split_att='fc', bridge=True):\n super().__init__()\n ... | import torch
import os
import sys
import warnings
from torch import nn
from torch.cuda.amp import autocast, GradScaler
from torch.utils.data import DataLoader
from loader import *
from models.model import MHA_UNet
from dataset.npy_datasets import NPY_datasets
from engine import *
from utils import *
from configs.config_setting import setting_config
| 5,185 |
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # "0, 1, 2, 3"
warnings.filterwarnings("ignore")
def main(config):
print('#----------Creating logger----------#')
sys.path.append(config.work_dir + '/')
log_dir = os.path.join(config.work_dir, 'log')
checkpoint_dir = os.path.join(config.work_dir, 'checkpoints')
resume_model = os.path.join(checkpoint_dir, 'latest.pth')
outputs = os.path.join(config.work_dir, 'outputs')
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
if not os.path.exists(outputs):
os.makedirs(outputs)
global logger
logger = get_logger('train', log_dir)
log_config_info(config, logger)
print('#----------GPU init----------#')
set_seed(config.seed)
gpu_ids = [0] # [0, 1, 2, 3]
torch.cuda.empty_cache()
print('#----------Preparing dataset----------#')
train_dataset = isic_loader(path_Data=config.data_path, train=True)
train_loader = DataLoader(train_dataset,
batch_size=config.batch_size,
shuffle=True,
pin_memory=True,
num_workers=config.num_workers)
val_dataset = isic_loader(path_Data=config.data_path, train=False)
val_loader = DataLoader(val_dataset,
batch_size=1,
shuffle=False,
pin_memory=True,
num_workers=config.num_workers,
drop_last=True)
test_dataset = isic_loader(path_Data=config.data_path, train=False, Test=True)
test_loader = DataLoader(test_dataset,
batch_size=1,
shuffle=False,
pin_memory=True,
num_workers=config.num_workers,
drop_last=True)
print('#----------Prepareing Models----------#')
#model_cfg = config.model_config
|
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # "0, 1, 2, 3"
warnings.filterwarnings("ignore")
def main(config):
print('#----------Creating logger----------#')
sys.path.append(config.work_dir + '/')
log_dir = os.path.join(config.work_dir, 'log')
checkpoint_dir = os.path.join(config.work_dir, 'checkpoints')
resume_model = os.path.join(checkpoint_dir, 'latest.pth')
outputs = os.path.join(config.work_dir, 'outputs')
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
if not os.path.exists(outputs):
os.makedirs(outputs)
global logger
logger = get_logger('train', log_dir)
log_config_info(config, logger)
print('#----------GPU init----------#')
set_seed(config.seed)
gpu_ids = [0] # [0, 1, 2, 3]
torch.cuda.empty_cache()
print('#----------Preparing dataset----------#')
train_dataset = isic_loader(path_Data=config.data_path, train=True)
train_loader = DataLoader(train_dataset,
batch_size=config.batch_size,
shuffle=True,
pin_memory=True,
num_workers=config.num_workers)
val_dataset = isic_loader(path_Data=config.data_path, train=False)
val_loader = DataLoader(val_dataset,
batch_size=1,
shuffle=False,
pin_memory=True,
num_workers=config.num_workers,
drop_last=True)
test_dataset = isic_loader(path_Data=config.data_path, train=False, Test=True)
test_loader = DataLoader(test_dataset,
batch_size=1,
shuffle=False,
pin_memory=True,
num_workers=config.num_workers,
drop_last=True)
print('#----------Prepareing Models----------#')
#model_cfg = config.model_config
| model = MHA_UNet()
| 0 | 2023-11-13 06:59:52+00:00 | 8k |
buptlihang/CVLM | examples/example_chat.py | [
{
"identifier": "IMAGE_TOKEN_INDEX",
"path": "model/utils.py",
"snippet": "IMAGE_TOKEN_INDEX = -200"
},
{
"identifier": "DEFAULT_IMAGE_TOKEN",
"path": "model/utils.py",
"snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\""
},
{
"identifier": "DEFAULT_IM_START_TOKEN",
"path": "model/... | import argparse
import torch
import requests
from PIL import Image
from io import BytesIO
from transformers import TextStreamer, AutoTokenizer
from model.utils import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from model.utils import process_images, tokenizer_image_token, KeywordsStoppingCriteria
from model.utils import Conversation, SeparatorStyle
from model.utils import load_image, load_pretrained_model, build_conversation
from model import CvlmForCausalLM | 5,602 |
def main(args):
# Model
tokenizer, model, image_processor, context_len = load_pretrained_model(
args.model_path, args.load_8bit, args.load_4bit, device=args.device)
conv = build_conversation()
image = load_image(args.image_file)
# Similar operation in model_worker.py
|
def main(args):
# Model
tokenizer, model, image_processor, context_len = load_pretrained_model(
args.model_path, args.load_8bit, args.load_4bit, device=args.device)
conv = build_conversation()
image = load_image(args.image_file)
# Similar operation in model_worker.py | image_tensor = process_images([image], image_processor, args) | 4 | 2023-11-10 03:52:46+00:00 | 8k |
vvvm23/TchAIkovsky | model/model.py | [
{
"identifier": "MultiheadAttention",
"path": "model/attention.py",
"snippet": "class MultiheadAttention(Module):\n r\"\"\"\n Computes\n\n $$\\text{MultiheadAttention}(Q, K, V)\n = \\sum_i \\text{Attention}\\left(QW^Q_i, KW^K_i, VW^V_i\\right)W^O_i$$\n\n where:\n\n - The inputs are\n... | from typing import List, Optional
from jax.random import PRNGKey
from .attention import MultiheadAttention
from .utils import make_attention_mask, make_causal_mask
import equinox as eqx
import jax
import jax.numpy as jnp | 4,580 | norm2: eqx.Module
dtype: jnp.dtype = eqx.field(static=True)
def __init__(
self,
key: PRNGKey,
dim: int,
num_heads: int,
mult: int = 4,
head_dim: Optional[int] = None,
dropout: float = 0.0,
dtype: jnp.dtype = jnp.float32,
):
self.dtype = dtype
attn_key, fc_key = jax.random.split(key)
if head_dim is None:
assert dim % num_heads == 0
head_dim = dim // num_heads
self.attn = MultiheadAttention(
num_heads=num_heads,
query_size=head_dim * num_heads,
output_size=dim,
use_output_bias=True,
dropout_p=dropout,
key=attn_key,
dtype=self.dtype,
)
self.norm1 = eqx.nn.LayerNorm(dim)
self.fc = eqx.nn.MLP(
dim,
dim,
width_size=dim * mult,
depth=1,
activation=jax.nn.silu,
key=fc_key,
)
self.norm2 = eqx.nn.LayerNorm(dim)
def __call__(self, x, mask, key=None):
x = x.astype(self.dtype)
attn_norm = jax.vmap(self.norm1)(x)
attn_output = self.attn(attn_norm, attn_norm, attn_norm, mask, key=key, inference=key is None)
fc_output = jax.vmap(self.fc)(jax.vmap(self.norm2)(x))
return x + attn_output + fc_output
class Decoder(eqx.Module):
layers: List[eqx.Module]
def __init__(
self,
key: PRNGKey,
dim: int,
num_heads: int,
num_layers: int,
head_dim: Optional[int] = None,
dropout: float = 0.0,
dtype: jnp.dtype = jnp.float32,
):
keys = jax.random.split(key, num_layers)
self.layers = [DecoderLayer(k, dim, num_heads, head_dim=head_dim, dropout=dropout, dtype=dtype) for k in keys]
def __call__(self, x, mask, key=None):
for layer in self.layers:
key, subkey = jax.random.split(key) if (key is not None) else (None, None)
x = layer(x, mask, subkey)
return x
class TchAIkovskyModel(eqx.Module):
id_embeddings: eqx.Module
pos_embeddings: eqx.Module
decoder: eqx.Module
norm_out: eqx.Module
out_head: eqx.Module
dtype: jnp.dtype = eqx.field(static=True)
output_dtype: jnp.dtype = eqx.field(static=True)
def __init__(
self,
dim: int,
num_heads: int,
num_layers: int,
vocab_size: int,
max_positions: int,
head_dim: Optional[int] = None,
dropout: float = 0.0,
key: PRNGKey = None,
dtype: jnp.dtype = jnp.float32,
output_dtype: jnp.dtype = jnp.float32,
):
self.dtype = dtype
self.output_dtype = output_dtype
id_embeddings_key, pos_embeddings_key, decoder_key, out_key = jax.random.split(key, 4)
self.id_embeddings = eqx.nn.Embedding(vocab_size, dim, key=id_embeddings_key)
self.pos_embeddings = eqx.nn.Embedding(max_positions, dim, key=pos_embeddings_key)
self.decoder = Decoder(
decoder_key,
dim,
num_heads,
num_layers,
head_dim=head_dim,
dropout=dropout,
dtype=dtype,
)
self.norm_out = eqx.nn.LayerNorm(dim)
self.out_head = eqx.nn.Linear(dim, vocab_size, use_bias=True, key=out_key)
def __call__(self, input_ids, position_ids, mask, key=None):
|
class DecoderLayer(eqx.Module):
attn: eqx.Module
fc: eqx.Module
norm1: eqx.Module
norm2: eqx.Module
dtype: jnp.dtype = eqx.field(static=True)
def __init__(
self,
key: PRNGKey,
dim: int,
num_heads: int,
mult: int = 4,
head_dim: Optional[int] = None,
dropout: float = 0.0,
dtype: jnp.dtype = jnp.float32,
):
self.dtype = dtype
attn_key, fc_key = jax.random.split(key)
if head_dim is None:
assert dim % num_heads == 0
head_dim = dim // num_heads
self.attn = MultiheadAttention(
num_heads=num_heads,
query_size=head_dim * num_heads,
output_size=dim,
use_output_bias=True,
dropout_p=dropout,
key=attn_key,
dtype=self.dtype,
)
self.norm1 = eqx.nn.LayerNorm(dim)
self.fc = eqx.nn.MLP(
dim,
dim,
width_size=dim * mult,
depth=1,
activation=jax.nn.silu,
key=fc_key,
)
self.norm2 = eqx.nn.LayerNorm(dim)
def __call__(self, x, mask, key=None):
x = x.astype(self.dtype)
attn_norm = jax.vmap(self.norm1)(x)
attn_output = self.attn(attn_norm, attn_norm, attn_norm, mask, key=key, inference=key is None)
fc_output = jax.vmap(self.fc)(jax.vmap(self.norm2)(x))
return x + attn_output + fc_output
class Decoder(eqx.Module):
layers: List[eqx.Module]
def __init__(
self,
key: PRNGKey,
dim: int,
num_heads: int,
num_layers: int,
head_dim: Optional[int] = None,
dropout: float = 0.0,
dtype: jnp.dtype = jnp.float32,
):
keys = jax.random.split(key, num_layers)
self.layers = [DecoderLayer(k, dim, num_heads, head_dim=head_dim, dropout=dropout, dtype=dtype) for k in keys]
def __call__(self, x, mask, key=None):
for layer in self.layers:
key, subkey = jax.random.split(key) if (key is not None) else (None, None)
x = layer(x, mask, subkey)
return x
class TchAIkovskyModel(eqx.Module):
id_embeddings: eqx.Module
pos_embeddings: eqx.Module
decoder: eqx.Module
norm_out: eqx.Module
out_head: eqx.Module
dtype: jnp.dtype = eqx.field(static=True)
output_dtype: jnp.dtype = eqx.field(static=True)
def __init__(
self,
dim: int,
num_heads: int,
num_layers: int,
vocab_size: int,
max_positions: int,
head_dim: Optional[int] = None,
dropout: float = 0.0,
key: PRNGKey = None,
dtype: jnp.dtype = jnp.float32,
output_dtype: jnp.dtype = jnp.float32,
):
self.dtype = dtype
self.output_dtype = output_dtype
id_embeddings_key, pos_embeddings_key, decoder_key, out_key = jax.random.split(key, 4)
self.id_embeddings = eqx.nn.Embedding(vocab_size, dim, key=id_embeddings_key)
self.pos_embeddings = eqx.nn.Embedding(max_positions, dim, key=pos_embeddings_key)
self.decoder = Decoder(
decoder_key,
dim,
num_heads,
num_layers,
head_dim=head_dim,
dropout=dropout,
dtype=dtype,
)
self.norm_out = eqx.nn.LayerNorm(dim)
self.out_head = eqx.nn.Linear(dim, vocab_size, use_bias=True, key=out_key)
def __call__(self, input_ids, position_ids, mask, key=None): | causal_mask = make_causal_mask(input_ids)[0] | 2 | 2023-11-13 07:31:30+00:00 | 8k |
LiquidFun/aoc_tiles | aoc_tiles/drawer.py | [
{
"identifier": "color_similarity",
"path": "aoc_tiles/colors.py",
"snippet": "def color_similarity(color_a, color_b, threshold):\n return abs(luminance(color_a) - luminance(color_b)) < threshold"
},
{
"identifier": "darker_color",
"path": "aoc_tiles/colors.py",
"snippet": "def darker... | import math
from functools import partial
from pathlib import Path
from typing import List, Tuple, Union, Dict
from PIL import ImageColor, Image
from PIL.ImageDraw import ImageDraw
from aoc_tiles.colors import color_similarity, darker_color, extension_to_colors
from aoc_tiles.config import Config
from aoc_tiles.fonts import main_font, secondary_font
from aoc_tiles.leaderboard import DayScores | 3,710 |
def format_time(time: str) -> str:
"""Formats time as mm:ss if the time is below 1 hour, otherwise it returns >1h to a max of >24h
>>> format_time("00:58:32")
'58:32'
>>> format_time(">1h")
' >1h'
"""
time = time.replace(">", ">")
if ">" in time:
formatted = time
else:
h, m, s = time.split(":")
formatted = f">{h}h" if int(h) >= 1 else f"{m:02}:{s:02}"
return f"{formatted:>5}"
class TileDrawer:
def __init__(self, config: Config):
self.config = config
def draw_tile(
self, day: str, languages: List[str], day_scores: Union[DayScores, None], path: Path, stars: int
):
"""Saves a graphic for a given day and year. Returns the path to it."""
image = self.get_alternating_background(languages, stars == 2)
drawer = ImageDraw(image)
text_kwargs = {"fill": self.config.text_color}
# Get all colors of the day, check if any one is similar to TEXT_COLOR
# If yes, add outline
for language in languages:
color = ImageColor.getrgb(extension_to_colors()[language])
if color_similarity(color, self.config.text_color, self.config.contrast_improvement_threshold):
if "outline" in self.config.contrast_improvement_type:
text_kwargs["stroke_width"] = 1
text_kwargs["stroke_fill"] = self.config.outline_color
if "dark" in self.config.contrast_improvement_type:
text_kwargs["fill"] = self.config.not_completed_color
break
draw_text = lambda *args, **kwargs: drawer.text(*args, **kwargs, **text_kwargs)
draw_line = partial(drawer.line, fill=text_kwargs["fill"], width=2)
# === Left side ===
draw_text((3, -5), "Day", align="left", font=main_font(20))
draw_text((1, -10), str(day), align="center", font=main_font(75))
# Calculate font size based on number of characters, because it might overflow
lang_as_str = " ".join(languages)
lang_font_size = max(6, int(18 - max(0, len(lang_as_str) - 8) * 1.3))
draw_text((0, 74), lang_as_str, align="left", font=secondary_font(lang_font_size))
# === Right side (P1 & P2) ===
for part in (1, 2):
y = 50 if part == 2 else 0
time = getattr(day_scores, f"time{part}", None)
rank = getattr(day_scores, f"rank{part}", None)
color_override = self.config.top100_color if rank and int(rank) <= 100 else self.config.text_color
text_kwargs["fill"] = color_override
if stars >= part:
draw_text((104, -5 + y), f"P{part} ", align="left", font=main_font(25))
if self.config.what_to_show_on_right_side == "checkmark" or day_scores is None:
draw_line((160, 35 + y, 150, 25 + y))
draw_line((160, 35 + y, 180, 15 + y))
elif self.config.what_to_show_on_right_side == "time_and_rank":
draw_text((105, 25 + y), "time", align="right", font=secondary_font(10))
draw_text((105, 35 + y), "rank", align="right", font=secondary_font(10))
draw_text((143, 3 + y), format_time(time), align="right", font=secondary_font(18))
draw_text((133, 23 + y), f"{rank:>6}", align="right", font=secondary_font(18))
elif self.config.what_to_show_on_right_side == "loc":
raise NotImplementedError("loc is not implemented yet")
else:
# Draw cross
draw_line((140, 15 + y, 160, 35 + y))
draw_line((140, 35 + y, 160, 15 + y))
if day_scores is None and not languages:
draw_line((15, 85, 85, 85))
# === Divider lines ===
draw_line((100, 5, 100, 95), width=1)
draw_line((105, 50, 195, 50), width=1)
image.save(path)
def get_alternating_background(self, languages, both_parts_completed=True, *, stripe_width=20):
colors = [ImageColor.getrgb(extension_to_colors()[language]) for language in languages]
if len(colors) == 1:
|
def format_time(time: str) -> str:
"""Formats time as mm:ss if the time is below 1 hour, otherwise it returns >1h to a max of >24h
>>> format_time("00:58:32")
'58:32'
>>> format_time(">1h")
' >1h'
"""
time = time.replace(">", ">")
if ">" in time:
formatted = time
else:
h, m, s = time.split(":")
formatted = f">{h}h" if int(h) >= 1 else f"{m:02}:{s:02}"
return f"{formatted:>5}"
class TileDrawer:
def __init__(self, config: Config):
self.config = config
def draw_tile(
self, day: str, languages: List[str], day_scores: Union[DayScores, None], path: Path, stars: int
):
"""Saves a graphic for a given day and year. Returns the path to it."""
image = self.get_alternating_background(languages, stars == 2)
drawer = ImageDraw(image)
text_kwargs = {"fill": self.config.text_color}
# Get all colors of the day, check if any one is similar to TEXT_COLOR
# If yes, add outline
for language in languages:
color = ImageColor.getrgb(extension_to_colors()[language])
if color_similarity(color, self.config.text_color, self.config.contrast_improvement_threshold):
if "outline" in self.config.contrast_improvement_type:
text_kwargs["stroke_width"] = 1
text_kwargs["stroke_fill"] = self.config.outline_color
if "dark" in self.config.contrast_improvement_type:
text_kwargs["fill"] = self.config.not_completed_color
break
draw_text = lambda *args, **kwargs: drawer.text(*args, **kwargs, **text_kwargs)
draw_line = partial(drawer.line, fill=text_kwargs["fill"], width=2)
# === Left side ===
draw_text((3, -5), "Day", align="left", font=main_font(20))
draw_text((1, -10), str(day), align="center", font=main_font(75))
# Calculate font size based on number of characters, because it might overflow
lang_as_str = " ".join(languages)
lang_font_size = max(6, int(18 - max(0, len(lang_as_str) - 8) * 1.3))
draw_text((0, 74), lang_as_str, align="left", font=secondary_font(lang_font_size))
# === Right side (P1 & P2) ===
for part in (1, 2):
y = 50 if part == 2 else 0
time = getattr(day_scores, f"time{part}", None)
rank = getattr(day_scores, f"rank{part}", None)
color_override = self.config.top100_color if rank and int(rank) <= 100 else self.config.text_color
text_kwargs["fill"] = color_override
if stars >= part:
draw_text((104, -5 + y), f"P{part} ", align="left", font=main_font(25))
if self.config.what_to_show_on_right_side == "checkmark" or day_scores is None:
draw_line((160, 35 + y, 150, 25 + y))
draw_line((160, 35 + y, 180, 15 + y))
elif self.config.what_to_show_on_right_side == "time_and_rank":
draw_text((105, 25 + y), "time", align="right", font=secondary_font(10))
draw_text((105, 35 + y), "rank", align="right", font=secondary_font(10))
draw_text((143, 3 + y), format_time(time), align="right", font=secondary_font(18))
draw_text((133, 23 + y), f"{rank:>6}", align="right", font=secondary_font(18))
elif self.config.what_to_show_on_right_side == "loc":
raise NotImplementedError("loc is not implemented yet")
else:
# Draw cross
draw_line((140, 15 + y, 160, 35 + y))
draw_line((140, 35 + y, 160, 15 + y))
if day_scores is None and not languages:
draw_line((15, 85, 85, 85))
# === Divider lines ===
draw_line((100, 5, 100, 95), width=1)
draw_line((105, 50, 195, 50), width=1)
image.save(path)
def get_alternating_background(self, languages, both_parts_completed=True, *, stripe_width=20):
colors = [ImageColor.getrgb(extension_to_colors()[language]) for language in languages]
if len(colors) == 1: | colors.append(darker_color(colors[0])) | 1 | 2023-11-14 21:41:12+00:00 | 8k |
etri-crossmodal/gbswt5 | gbswt5/modeling_gbst5.py | [
{
"identifier": "GBSWT5Config",
"path": "gbswt5/configuration_gbst5.py",
"snippet": "class GBSWT5Config(PretrainedConfig):\n \"\"\" Based on models.t5. configuration_t5. T5Config in hf Transformers. \"\"\"\n model_type = \"gbswt5\"\n keys_to_ignore_at_inference = [\"past_key_values\"]\n attr... | import copy
import torch
from typing import Optional, Union, Tuple
from torch import nn
from transformers import add_start_docstrings
from transformers.utils import logging
from transformers.modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPastAndCrossAttentions,
Seq2SeqLMOutput,
Seq2SeqModelOutput,
)
from transformers.models.t5.modeling_t5 import (
T5LayerNorm, T5Block, T5Stack,
T5Model, T5PreTrainedModel, T5ForConditionalGeneration, T5EncoderModel,
T5DenseActDense, T5DenseGatedActDense, T5Attention,
T5_START_DOCSTRING
)
from .configuration_gbst5 import GBSWT5Config
from .gbst import GBSWT | 4,348 | """
hf transformers-compatible GBST + T5 Model implementation.
several methods are copying from huggingface/transformers/models/t5/modeling_t5.py
as Implementation Standards for compatibility. (version 4.28.1)
hf transformers' modeling_t5.py file is distributed under Apache 2.0 License.
Copyright (C) 2023, ETRI LIRS, Jong-hun Shin.
"""
logger = logging.get_logger(__name__)
class GBSWT5PreTrainedModel(T5PreTrainedModel):
config_class = GBSWT5Config
base_model_prefix = "GBSWT5"
is_parallelizable = True
supports_gradient_checkpointing = True
_no_split_modules = ["T5Block"]
_keep_in_fp32_modules = ["wo"]
def _init_weights(self, module):
"""Initialize the weights. 대부분은 T5PreTrainedModel을 따른다. """
factor = self.config.initializer_factor # Used for testing weights initialization
if isinstance(module, T5LayerNorm):
module.weight.data.fill_(factor * 1.0)
elif isinstance(
module,
( GBSWT5Model, GBSWT5ForConditionalGeneration, GBSWT5EncoderModel,),
):
# Mesh TensorFlow embeddings initialization
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
if hasattr(module, "qa_outputs"):
module.qa_outputs.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
module.qa_outputs.bias.data.zero_()
elif isinstance(module, T5DenseActDense):
# Mesh TensorFlow FF initialization
# See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
# and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi, "bias") and module.wi.bias is not None:
module.wi.bias.data.zero_()
module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
module.wo.bias.data.zero_()
elif isinstance(module, T5DenseGatedActDense):
module.wi_0.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
module.wi_0.bias.data.zero_()
module.wi_1.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
module.wi_1.bias.data.zero_()
module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
module.wo.bias.data.zero_()
elif isinstance(module, T5Attention):
# Mesh TensorFlow attention initialization to avoid scaling before softmax
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
d_model = self.config.d_model
key_value_proj_dim = self.config.d_kv
n_heads = self.config.num_heads
module.q.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
module.k.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
module.v.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
if module.has_relative_attention_bias:
module.relative_attention_bias.weight.data.normal_(mean=0.0, std=factor * ((d_model) ** -0.5))
| """
hf transformers-compatible GBST + T5 Model implementation.
several methods are copying from huggingface/transformers/models/t5/modeling_t5.py
as Implementation Standards for compatibility. (version 4.28.1)
hf transformers' modeling_t5.py file is distributed under Apache 2.0 License.
Copyright (C) 2023, ETRI LIRS, Jong-hun Shin.
"""
logger = logging.get_logger(__name__)
class GBSWT5PreTrainedModel(T5PreTrainedModel):
config_class = GBSWT5Config
base_model_prefix = "GBSWT5"
is_parallelizable = True
supports_gradient_checkpointing = True
_no_split_modules = ["T5Block"]
_keep_in_fp32_modules = ["wo"]
def _init_weights(self, module):
"""Initialize the weights. 대부분은 T5PreTrainedModel을 따른다. """
factor = self.config.initializer_factor # Used for testing weights initialization
if isinstance(module, T5LayerNorm):
module.weight.data.fill_(factor * 1.0)
elif isinstance(
module,
( GBSWT5Model, GBSWT5ForConditionalGeneration, GBSWT5EncoderModel,),
):
# Mesh TensorFlow embeddings initialization
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
if hasattr(module, "qa_outputs"):
module.qa_outputs.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
module.qa_outputs.bias.data.zero_()
elif isinstance(module, T5DenseActDense):
# Mesh TensorFlow FF initialization
# See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
# and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi, "bias") and module.wi.bias is not None:
module.wi.bias.data.zero_()
module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
module.wo.bias.data.zero_()
elif isinstance(module, T5DenseGatedActDense):
module.wi_0.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
module.wi_0.bias.data.zero_()
module.wi_1.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
module.wi_1.bias.data.zero_()
module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
module.wo.bias.data.zero_()
elif isinstance(module, T5Attention):
# Mesh TensorFlow attention initialization to avoid scaling before softmax
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
d_model = self.config.d_model
key_value_proj_dim = self.config.d_kv
n_heads = self.config.num_heads
module.q.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
module.k.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
module.v.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
if module.has_relative_attention_bias:
module.relative_attention_bias.weight.data.normal_(mean=0.0, std=factor * ((d_model) ** -0.5)) | elif isinstance(module, GBSWT): | 1 | 2023-11-17 02:04:46+00:00 | 8k |
dazhangyu123/ACMIL | wsi_core/WholeSlideImage.py | [
{
"identifier": "savePatchIter_bag_hdf5",
"path": "wsi_core/wsi_utils.py",
"snippet": "def savePatchIter_bag_hdf5(patch):\n x, y, cont_idx, patch_level, downsample, downsampled_level_dim, level_dim, img_patch, name, save_path= tuple(patch.values())\n img_patch = np.array(img_patch)[np.newaxis,...]... | import math
import os
import time
import xml.etree.ElementTree as ET
import multiprocessing as mp
import cv2
import matplotlib.pyplot as plt
import numpy as np
import openslide
import pdb
import h5py
import math
import itertools
import pickle
from xml.dom import minidom
from PIL import Image
from wsi_core.wsi_utils import savePatchIter_bag_hdf5, initialize_hdf5_bag, coord_generator, save_hdf5, sample_indices, screen_coords, isBlackPatch, isWhitePatch, to_percentiles
from wsi_core.util_classes import isInContourV1, isInContourV2, isInContourV3_Easy, isInContourV3_Hard, Contour_Checking_fn
from utils.file_utils import load_pkl, save_pkl
from skimage.color import rgb2hed, hed2rgb
from wsi_core.KfbSlide import kfbslide | 5,798 | # img_h_gray = 255-cv2.medianBlur(cv2.cvtColor(img_h, cv2.COLOR_BGR2GRAY),mthresh)
# # _, img_otsu = cv2.threshold(img_h_gray, sthresh, sthresh_up, cv2.THRESH_BINARY)
# otsu_thresh, img_otsu = cv2.threshold(img_h_gray, 0, sthresh_up, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
# adjust_thresh = max(sthresh,otsu_thresh-20)
# _, img_otsu = cv2.threshold(img_h_gray, adjust_thresh, sthresh_up, cv2.THRESH_BINARY)
# img_d = hed2rgb(np.stack((img_hed[:, :, 2], img_hed[:, :, 2], img_hed[:, :, 2]), axis=-1))
# filter this?
# Morphological closing
if close > 0:
kernel = np.ones((close, close), np.uint8)
img_otsu = cv2.morphologyEx(img_otsu, cv2.MORPH_CLOSE, kernel)
scale = self.level_downsamples[seg_level]
scaled_ref_patch_area = int(ref_patch_size**2 / (scale[0] * scale[1]))
print('scaled_ref_patch_area',scaled_ref_patch_area)
print('ref_patch_size',ref_patch_size)
print('scale',scale,'seg_level',seg_level)
filter_params = filter_params.copy()
filter_params['a_t'] = filter_params['a_t'] * scaled_ref_patch_area
filter_params['a_h'] = filter_params['a_h'] * scaled_ref_patch_area
# Find and filter contours
contours, hierarchy = cv2.findContours(img_otsu, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) # Find contours
hierarchy = np.squeeze(hierarchy, axis=(0,))[:, 2:]
# pdb.set_trace()
if filter_params: foreground_contours, hole_contours = _filter_contours(contours, hierarchy, filter_params) # Necessary for filtering out artifacts
self.contours_tissue = self.scaleContourDim(foreground_contours, scale)
self.holes_tissue = self.scaleHolesDim(hole_contours, scale)
#exclude_ids = [0,7,9]
if len(keep_ids) > 0:
contour_ids = set(keep_ids) - set(exclude_ids)
else:
contour_ids = set(np.arange(len(self.contours_tissue))) - set(exclude_ids)
self.contours_tissue = [self.contours_tissue[i] for i in contour_ids]
self.holes_tissue = [self.holes_tissue[i] for i in contour_ids]
def visWSI(self, vis_level=0, color = (0,255,0), hole_color = (0,0,255), annot_color=(255,0,0),
line_thickness=250, max_size=None, top_left=None, bot_right=None, custom_downsample=1, view_slide_only=False,
number_contours=False, seg_display=True, annot_display=True):
downsample = self.level_downsamples[vis_level]
scale = [1/downsample[0], 1/downsample[1]]
# pdb.set_trace()
if top_left is not None and bot_right is not None:
top_left = tuple(top_left)
bot_right = tuple(bot_right)
w, h = tuple((np.array(bot_right) * scale).astype(int) - (np.array(top_left) * scale).astype(int))
region_size = (w, h)
else:
top_left = (0,0)
region_size = self.level_dim[vis_level]
img = self.wsi.read_region(top_left, vis_level, region_size)
try:
img = np.array(img.convert("RGB"))
except:
pass
# view_slide_only= True
if not view_slide_only:
offset = tuple(-(np.array(top_left) * scale).astype(int))
line_thickness = int(line_thickness * math.sqrt(scale[0] * scale[1]))
if self.contours_tissue is not None and seg_display:
if not number_contours:
cv2.drawContours(img, self.scaleContourDim(self.contours_tissue, scale),
-1, color, line_thickness, lineType=cv2.LINE_8, offset=offset)
else: # add numbering to each contour
for idx, cont in enumerate(self.contours_tissue):
contour = np.array(self.scaleContourDim(cont, scale))
M = cv2.moments(contour)
cX = int(M["m10"] / (M["m00"] + 1e-9))
cY = int(M["m01"] / (M["m00"] + 1e-9))
# draw the contour and put text next to center
cv2.drawContours(img, [contour], -1, color, line_thickness, lineType=cv2.LINE_8, offset=offset)
cv2.putText(img, "{}".format(idx), (cX, cY),
cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 10)
for holes in self.holes_tissue:
cv2.drawContours(img, self.scaleContourDim(holes, scale),
-1, hole_color, line_thickness, lineType=cv2.LINE_8)
if self.contours_tumor is not None and annot_display:
cv2.drawContours(img, self.scaleContourDim(self.contours_tumor, scale),
-1, annot_color, line_thickness, lineType=cv2.LINE_8, offset=offset)
img = Image.fromarray(img)
w, h = img.size
if custom_downsample > 1:
img = img.resize((int(w/custom_downsample), int(h/custom_downsample)))
if max_size is not None and (w > max_size or h > max_size):
resizeFactor = max_size/w if w > h else max_size/h
img = img.resize((int(w*resizeFactor), int(h*resizeFactor)))
return img
def createPatches_bag_hdf5(self, save_path, patch_level=0, patch_size=256, step_size=256, save_coord=True, **kwargs):
contours = self.contours_tissue
contour_holes = self.holes_tissue
print("Creating patches for: ", self.name, "...",)
elapsed = time.time()
for idx, cont in enumerate(contours):
patch_gen = self._getPatchGenerator(cont, idx, patch_level, save_path, patch_size, step_size, **kwargs)
if self.hdf5_file is None:
try:
first_patch = next(patch_gen)
# empty contour, continue
except StopIteration:
continue
|
Image.MAX_IMAGE_PIXELS = 933120000
class WholeSlideImage(object):
def __init__(self, path):
"""
Args:
path (str): fullpath to WSI file
"""
# self.name = ".".join(path.split("/")[-1].split('.')[:-1])
self.name = os.path.splitext(os.path.basename(path))[0]
# pdb.set_trace()
try:
self.wsi = openslide.open_slide(path)
except:
self.wsi = kfbslide.open_kfbslide(path)
# self.wsi = openSlide(path)
# pdb.set_trace()
self.level_downsamples = self._assertLevelDownsamples()
self.level_dim = self.wsi.level_dimensions
self.contours_tissue = None
self.contours_tumor = None
self.hdf5_file = None
def getOpenSlide(self):
return self.wsi
def initXML(self, xml_path):
def _createContour(coord_list):
return np.array([[[int(float(coord.attributes['X'].value)),
int(float(coord.attributes['Y'].value))]] for coord in coord_list], dtype = 'int32')
xmldoc = minidom.parse(xml_path)
annotations = [anno.getElementsByTagName('Coordinate') for anno in xmldoc.getElementsByTagName('Annotation')]
self.contours_tumor = [_createContour(coord_list) for coord_list in annotations]
self.contours_tumor = sorted(self.contours_tumor, key=cv2.contourArea, reverse=True)
def initTxt(self,annot_path):
def _create_contours_from_dict(annot):
all_cnts = []
for idx, annot_group in enumerate(annot):
contour_group = annot_group['coordinates']
if annot_group['type'] == 'Polygon':
for idx, contour in enumerate(contour_group):
contour = np.array(contour).astype(np.int32).reshape(-1,1,2)
all_cnts.append(contour)
else:
for idx, sgmt_group in enumerate(contour_group):
contour = []
for sgmt in sgmt_group:
contour.extend(sgmt)
contour = np.array(contour).astype(np.int32).reshape(-1,1,2)
all_cnts.append(contour)
return all_cnts
with open(annot_path, "r") as f:
annot = f.read()
annot = eval(annot)
self.contours_tumor = _create_contours_from_dict(annot)
self.contours_tumor = sorted(self.contours_tumor, key=cv2.contourArea, reverse=True)
def initSegmentation(self, mask_file):
# load segmentation results from pickle file
asset_dict = load_pkl(mask_file)
self.holes_tissue = asset_dict['holes']
self.contours_tissue = asset_dict['tissue']
def saveSegmentation(self, mask_file):
# save segmentation results using pickle
asset_dict = {'holes': self.holes_tissue, 'tissue': self.contours_tissue}
save_pkl(mask_file, asset_dict)
def segmentTissue(self, seg_level=0, sthresh=20, sthresh_up = 255, mthresh=7, close = 0, use_otsu=False,
filter_params={'a_t':100}, ref_patch_size=512, exclude_ids=[], keep_ids=[]):
"""
Segment the tissue via HSV -> Median thresholding -> Binary threshold
"""
def _filter_contours(contours, hierarchy, filter_params):
"""
Filter contours by: area.
"""
filtered = []
# find indices of foreground contours (parent == -1)
hierarchy_1 = np.flatnonzero(hierarchy[:,1] == -1)
all_holes = []
# loop through foreground contour indices
for cont_idx in hierarchy_1:
# actual contour
# pdb.set_trace()
cont = contours[cont_idx]
# indices of holes contained in this contour (children of parent contour)
holes = np.flatnonzero(hierarchy[:, 1] == cont_idx)
# take contour area (includes holes)
a = cv2.contourArea(cont)
# calculate the contour area of each hole
hole_areas = [cv2.contourArea(contours[hole_idx]) for hole_idx in holes]
# actual area of foreground contour region
a = a - np.array(hole_areas).sum()
if a == 0: continue
# print(tuple((filter_params['a_t'],)),tuple((a,)))
if tuple((filter_params['a_t'],)) < tuple((a,)):
filtered.append(cont_idx)
all_holes.append(holes)
foreground_contours = [contours[cont_idx] for cont_idx in filtered]
hole_contours = []
for hole_ids in all_holes:
unfiltered_holes = [contours[idx] for idx in hole_ids ]
unfilered_holes = sorted(unfiltered_holes, key=cv2.contourArea, reverse=True)
# take max_n_holes largest holes by area
unfilered_holes = unfilered_holes[:filter_params['max_n_holes']]
filtered_holes = []
# filter these holes
for hole in unfilered_holes:
if cv2.contourArea(hole) > filter_params['a_h']:
filtered_holes.append(hole)
hole_contours.append(filtered_holes)
return foreground_contours, hole_contours
# pdb.set_trace()
try:
img = np.array(self.wsi.read_region((0,0), seg_level, self.level_dim[seg_level]))
except:
print('failed read region')
img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) # Convert to HSV space
img_med = cv2.medianBlur(img_hsv[:,:,1], mthresh) # Apply median blurring
# Thresholding
# if use_otsu:
if False:
otsu_thresh, img_otsu = cv2.threshold(img_med, 0, sthresh_up, cv2.THRESH_OTSU+cv2.THRESH_BINARY)
# adjust_thresh = max(sthresh,otsu_thresh-20)
adjust_thresh = otsu_thresh
_, img_otsu = cv2.threshold(img_med, adjust_thresh, sthresh_up, cv2.THRESH_BINARY)
print('otsu_threshold:',otsu_thresh,'adjust_thresh:',adjust_thresh)
else:
print('not otsu')
_, img_otsu = cv2.threshold(img_med, sthresh, sthresh_up, cv2.THRESH_BINARY)
# pdb.set_trace()
## hed operas
# img_hed = rgb2hed(cv2.cvtColor(img, cv2.COLOR_RGBA2RGB))
# # img_e = hed2rgb(np.stack((img_hed[:, :, 1], img_hed[:, :, 1], img_hed[:, :, 1]), axis=-1))
# img_h = hed2rgb(np.stack((img_hed[:, :, 0], np.zeros_like(img_hed[:, :, 0]), np.zeros_like(img_hed[:, :, 0])), axis=-1))
# img_h = (img_h*255).astype(np.uint8)
# img_h_gray = 255-cv2.medianBlur(cv2.cvtColor(img_h, cv2.COLOR_BGR2GRAY),mthresh)
# # _, img_otsu = cv2.threshold(img_h_gray, sthresh, sthresh_up, cv2.THRESH_BINARY)
# otsu_thresh, img_otsu = cv2.threshold(img_h_gray, 0, sthresh_up, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
# adjust_thresh = max(sthresh,otsu_thresh-20)
# _, img_otsu = cv2.threshold(img_h_gray, adjust_thresh, sthresh_up, cv2.THRESH_BINARY)
# img_d = hed2rgb(np.stack((img_hed[:, :, 2], img_hed[:, :, 2], img_hed[:, :, 2]), axis=-1))
# filter this?
# Morphological closing
if close > 0:
kernel = np.ones((close, close), np.uint8)
img_otsu = cv2.morphologyEx(img_otsu, cv2.MORPH_CLOSE, kernel)
scale = self.level_downsamples[seg_level]
scaled_ref_patch_area = int(ref_patch_size**2 / (scale[0] * scale[1]))
print('scaled_ref_patch_area',scaled_ref_patch_area)
print('ref_patch_size',ref_patch_size)
print('scale',scale,'seg_level',seg_level)
filter_params = filter_params.copy()
filter_params['a_t'] = filter_params['a_t'] * scaled_ref_patch_area
filter_params['a_h'] = filter_params['a_h'] * scaled_ref_patch_area
# Find and filter contours
contours, hierarchy = cv2.findContours(img_otsu, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) # Find contours
hierarchy = np.squeeze(hierarchy, axis=(0,))[:, 2:]
# pdb.set_trace()
if filter_params: foreground_contours, hole_contours = _filter_contours(contours, hierarchy, filter_params) # Necessary for filtering out artifacts
self.contours_tissue = self.scaleContourDim(foreground_contours, scale)
self.holes_tissue = self.scaleHolesDim(hole_contours, scale)
#exclude_ids = [0,7,9]
if len(keep_ids) > 0:
contour_ids = set(keep_ids) - set(exclude_ids)
else:
contour_ids = set(np.arange(len(self.contours_tissue))) - set(exclude_ids)
self.contours_tissue = [self.contours_tissue[i] for i in contour_ids]
self.holes_tissue = [self.holes_tissue[i] for i in contour_ids]
def visWSI(self, vis_level=0, color = (0,255,0), hole_color = (0,0,255), annot_color=(255,0,0),
line_thickness=250, max_size=None, top_left=None, bot_right=None, custom_downsample=1, view_slide_only=False,
number_contours=False, seg_display=True, annot_display=True):
downsample = self.level_downsamples[vis_level]
scale = [1/downsample[0], 1/downsample[1]]
# pdb.set_trace()
if top_left is not None and bot_right is not None:
top_left = tuple(top_left)
bot_right = tuple(bot_right)
w, h = tuple((np.array(bot_right) * scale).astype(int) - (np.array(top_left) * scale).astype(int))
region_size = (w, h)
else:
top_left = (0,0)
region_size = self.level_dim[vis_level]
img = self.wsi.read_region(top_left, vis_level, region_size)
try:
img = np.array(img.convert("RGB"))
except:
pass
# view_slide_only= True
if not view_slide_only:
offset = tuple(-(np.array(top_left) * scale).astype(int))
line_thickness = int(line_thickness * math.sqrt(scale[0] * scale[1]))
if self.contours_tissue is not None and seg_display:
if not number_contours:
cv2.drawContours(img, self.scaleContourDim(self.contours_tissue, scale),
-1, color, line_thickness, lineType=cv2.LINE_8, offset=offset)
else: # add numbering to each contour
for idx, cont in enumerate(self.contours_tissue):
contour = np.array(self.scaleContourDim(cont, scale))
M = cv2.moments(contour)
cX = int(M["m10"] / (M["m00"] + 1e-9))
cY = int(M["m01"] / (M["m00"] + 1e-9))
# draw the contour and put text next to center
cv2.drawContours(img, [contour], -1, color, line_thickness, lineType=cv2.LINE_8, offset=offset)
cv2.putText(img, "{}".format(idx), (cX, cY),
cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 10)
for holes in self.holes_tissue:
cv2.drawContours(img, self.scaleContourDim(holes, scale),
-1, hole_color, line_thickness, lineType=cv2.LINE_8)
if self.contours_tumor is not None and annot_display:
cv2.drawContours(img, self.scaleContourDim(self.contours_tumor, scale),
-1, annot_color, line_thickness, lineType=cv2.LINE_8, offset=offset)
img = Image.fromarray(img)
w, h = img.size
if custom_downsample > 1:
img = img.resize((int(w/custom_downsample), int(h/custom_downsample)))
if max_size is not None and (w > max_size or h > max_size):
resizeFactor = max_size/w if w > h else max_size/h
img = img.resize((int(w*resizeFactor), int(h*resizeFactor)))
return img
def createPatches_bag_hdf5(self, save_path, patch_level=0, patch_size=256, step_size=256, save_coord=True, **kwargs):
contours = self.contours_tissue
contour_holes = self.holes_tissue
print("Creating patches for: ", self.name, "...",)
elapsed = time.time()
for idx, cont in enumerate(contours):
patch_gen = self._getPatchGenerator(cont, idx, patch_level, save_path, patch_size, step_size, **kwargs)
if self.hdf5_file is None:
try:
first_patch = next(patch_gen)
# empty contour, continue
except StopIteration:
continue
| file_path = initialize_hdf5_bag(first_patch, save_coord=save_coord) | 1 | 2023-11-12 14:07:34+00:00 | 8k |
juftin/hatch-pip-compile | tests/conftest.py | [
{
"identifier": "PipInstaller",
"path": "hatch_pip_compile/installer.py",
"snippet": "class PipInstaller(PluginInstaller):\n \"\"\"\n Plugin Installer for `pip`\n \"\"\"\n\n def install_dependencies(self) -> None:\n \"\"\"\n Install the dependencies with `pip`\n \"\"\"\n... | import os
import pathlib
import shutil
import pytest
import tomlkit
from dataclasses import dataclass, field
from subprocess import CompletedProcess
from typing import Dict, Generator, Type
from unittest.mock import patch
from hatch.cli.application import Application
from hatch.config.constants import AppEnvVars, ConfigEnvVars, PublishEnvVars
from hatch.project.core import Project
from hatch.utils.fs import Path, temp_directory
from hatch.utils.platform import Platform
from hatch_pip_compile.installer import PipInstaller, PipSyncInstaller, PluginInstaller
from hatch_pip_compile.plugin import PipCompileEnvironment | 4,554 | """
Shared fixtures for tests.
"""
@pytest.fixture
def mock_check_command() -> Generator[patch, None, None]:
"""
Disable the `plugin_check_command` for testing
"""
with patch("hatch_pip_compile.plugin.PipCompileEnvironment.plugin_check_command") as mock:
mock.return_value = CompletedProcess(args=[], returncode=0, stdout=b"", stderr=b"")
yield mock
@pytest.fixture
def platform() -> Platform:
"""
Platform
"""
return Platform()
@pytest.fixture
def isolation(platform: Platform) -> Generator[Path, None, None]:
"""
Isolated hatch environment for testing.
"""
with temp_directory() as temp_dir:
data_dir = pathlib.Path(__file__).parent / "data"
shutil.copytree(data_dir, temp_dir, dirs_exist_ok=True)
data_dir = temp_dir / "data"
data_dir.mkdir()
cache_dir = temp_dir / "cache"
cache_dir.mkdir()
default_env_vars = {
AppEnvVars.NO_COLOR: "1",
ConfigEnvVars.DATA: str(data_dir),
ConfigEnvVars.CACHE: str(cache_dir),
PublishEnvVars.REPO: "dev",
"HATCH_SELF_TESTING": "true",
"PYAPP_COMMAND_NAME": os.urandom(4).hex(),
"GIT_AUTHOR_NAME": "Foo Bar",
"GIT_AUTHOR_EMAIL": "foo@bar.baz",
"COLUMNS": "80",
"LINES": "24",
}
if platform.windows: # pragma: no cover
default_env_vars["COMSPEC"] = "cmd.exe"
else:
default_env_vars["SHELL"] = "sh"
with temp_dir.as_cwd(default_env_vars):
os.environ.pop(AppEnvVars.ENV_ACTIVE, None)
os.environ.pop(AppEnvVars.FORCE_COLOR, None)
yield temp_dir
@dataclass
class PipCompileFixture:
"""
Testing Fixture Data Container
"""
__test__ = False
isolation: pathlib.Path
toml_doc: tomlkit.TOMLDocument
pyproject: pathlib.Path
project: Project
platform: Platform
isolated_data_dir: pathlib.Path
application: Application = field(init=False)
| """
Shared fixtures for tests.
"""
@pytest.fixture
def mock_check_command() -> Generator[patch, None, None]:
"""
Disable the `plugin_check_command` for testing
"""
with patch("hatch_pip_compile.plugin.PipCompileEnvironment.plugin_check_command") as mock:
mock.return_value = CompletedProcess(args=[], returncode=0, stdout=b"", stderr=b"")
yield mock
@pytest.fixture
def platform() -> Platform:
"""
Platform
"""
return Platform()
@pytest.fixture
def isolation(platform: Platform) -> Generator[Path, None, None]:
"""
Isolated hatch environment for testing.
"""
with temp_directory() as temp_dir:
data_dir = pathlib.Path(__file__).parent / "data"
shutil.copytree(data_dir, temp_dir, dirs_exist_ok=True)
data_dir = temp_dir / "data"
data_dir.mkdir()
cache_dir = temp_dir / "cache"
cache_dir.mkdir()
default_env_vars = {
AppEnvVars.NO_COLOR: "1",
ConfigEnvVars.DATA: str(data_dir),
ConfigEnvVars.CACHE: str(cache_dir),
PublishEnvVars.REPO: "dev",
"HATCH_SELF_TESTING": "true",
"PYAPP_COMMAND_NAME": os.urandom(4).hex(),
"GIT_AUTHOR_NAME": "Foo Bar",
"GIT_AUTHOR_EMAIL": "foo@bar.baz",
"COLUMNS": "80",
"LINES": "24",
}
if platform.windows: # pragma: no cover
default_env_vars["COMSPEC"] = "cmd.exe"
else:
default_env_vars["SHELL"] = "sh"
with temp_dir.as_cwd(default_env_vars):
os.environ.pop(AppEnvVars.ENV_ACTIVE, None)
os.environ.pop(AppEnvVars.FORCE_COLOR, None)
yield temp_dir
@dataclass
class PipCompileFixture:
"""
Testing Fixture Data Container
"""
__test__ = False
isolation: pathlib.Path
toml_doc: tomlkit.TOMLDocument
pyproject: pathlib.Path
project: Project
platform: Platform
isolated_data_dir: pathlib.Path
application: Application = field(init=False) | default_environment: PipCompileEnvironment = field(init=False) | 3 | 2023-11-10 00:34:00+00:00 | 8k |
zhang-tao-whu/DVIS_Plus | mask2former/modeling/pixel_decoder/fpn.py | [
{
"identifier": "PositionEmbeddingSine",
"path": "mask2former/modeling/transformer_decoder/position_encoding.py",
"snippet": "class PositionEmbeddingSine(nn.Module):\n \"\"\"\n This is a more standard version of the position embedding, very similar to the one\n used by the Attention is all you ... | import logging
import numpy as np
import fvcore.nn.weight_init as weight_init
import torch
from typing import Callable, Dict, List, Optional, Tuple, Union
from torch import nn
from torch.nn import functional as F
from torch.nn.init import xavier_uniform_, constant_, uniform_, normal_
from torch.cuda.amp import autocast
from detectron2.config import configurable
from detectron2.layers import Conv2d, DeformConv, ShapeSpec, get_norm
from detectron2.modeling import SEM_SEG_HEADS_REGISTRY
from ..transformer_decoder.position_encoding import PositionEmbeddingSine
from ..transformer_decoder.transformer import TransformerEncoder, TransformerEncoderLayer, _get_clones, _get_activation_fn | 3,838 | ret["mask_dim"] = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM
ret["norm"] = cfg.MODEL.SEM_SEG_HEAD.NORM
return ret
def forward_features(self, features):
multi_scale_features = []
num_cur_levels = 0
# Reverse feature maps into top-down order (from low to high resolution)
for idx, f in enumerate(self.in_features[::-1]):
x = features[f]
lateral_conv = self.lateral_convs[idx]
output_conv = self.output_convs[idx]
if lateral_conv is None:
y = output_conv(x)
else:
cur_fpn = lateral_conv(x)
# Following FPN implementation, we use nearest upsampling here
y = cur_fpn + F.interpolate(y, size=cur_fpn.shape[-2:], mode="nearest")
y = output_conv(y)
if num_cur_levels < self.maskformer_num_feature_levels:
multi_scale_features.append(y)
num_cur_levels += 1
return self.mask_features(y), None, multi_scale_features
def forward(self, features, targets=None):
logger = logging.getLogger(__name__)
logger.warning("Calling forward() may cause unpredicted behavior of PixelDecoder module.")
return self.forward_features(features)
class TransformerEncoderOnly(nn.Module):
def __init__(
self,
d_model=512,
nhead=8,
num_encoder_layers=6,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
):
super().__init__()
encoder_layer = TransformerEncoderLayer(
d_model, nhead, dim_feedforward, dropout, activation, normalize_before
)
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
self._reset_parameters()
self.d_model = d_model
self.nhead = nhead
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def forward(self, src, mask, pos_embed):
# flatten NxCxHxW to HWxNxC
bs, c, h, w = src.shape
src = src.flatten(2).permute(2, 0, 1)
pos_embed = pos_embed.flatten(2).permute(2, 0, 1)
if mask is not None:
mask = mask.flatten(1)
memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed)
return memory.permute(1, 2, 0).view(bs, c, h, w)
# This is a modified FPN decoder with extra Transformer encoder that processes the lowest-resolution feature map.
@SEM_SEG_HEADS_REGISTRY.register()
class TransformerEncoderPixelDecoder(BasePixelDecoder):
@configurable
def __init__(
self,
input_shape: Dict[str, ShapeSpec],
*,
transformer_dropout: float,
transformer_nheads: int,
transformer_dim_feedforward: int,
transformer_enc_layers: int,
transformer_pre_norm: bool,
conv_dim: int,
mask_dim: int,
norm: Optional[Union[str, Callable]] = None,
):
"""
NOTE: this interface is experimental.
Args:
input_shape: shapes (channels and stride) of the input features
transformer_dropout: dropout probability in transformer
transformer_nheads: number of heads in transformer
transformer_dim_feedforward: dimension of feedforward network
transformer_enc_layers: number of transformer encoder layers
transformer_pre_norm: whether to use pre-layernorm or not
conv_dims: number of output channels for the intermediate conv layers.
mask_dim: number of output channels for the final conv layer.
norm (str or callable): normalization for all conv layers
"""
super().__init__(input_shape, conv_dim=conv_dim, mask_dim=mask_dim, norm=norm)
input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
self.in_features = [k for k, v in input_shape] # starting from "res2" to "res5"
feature_strides = [v.stride for k, v in input_shape]
feature_channels = [v.channels for k, v in input_shape]
in_channels = feature_channels[len(self.in_features) - 1]
self.input_proj = Conv2d(in_channels, conv_dim, kernel_size=1)
weight_init.c2_xavier_fill(self.input_proj)
self.transformer = TransformerEncoderOnly(
d_model=conv_dim,
dropout=transformer_dropout,
nhead=transformer_nheads,
dim_feedforward=transformer_dim_feedforward,
num_encoder_layers=transformer_enc_layers,
normalize_before=transformer_pre_norm,
)
N_steps = conv_dim // 2
| # Copyright (c) Facebook, Inc. and its affiliates.
def build_pixel_decoder(cfg, input_shape):
"""
Build a pixel decoder from `cfg.MODEL.MASK_FORMER.PIXEL_DECODER_NAME`.
"""
name = cfg.MODEL.SEM_SEG_HEAD.PIXEL_DECODER_NAME
model = SEM_SEG_HEADS_REGISTRY.get(name)(cfg, input_shape)
forward_features = getattr(model, "forward_features", None)
if not callable(forward_features):
raise ValueError(
"Only SEM_SEG_HEADS with forward_features method can be used as pixel decoder. "
f"Please implement forward_features for {name} to only return mask features."
)
return model
# This is a modified FPN decoder.
@SEM_SEG_HEADS_REGISTRY.register()
class BasePixelDecoder(nn.Module):
@configurable
def __init__(
self,
input_shape: Dict[str, ShapeSpec],
*,
conv_dim: int,
mask_dim: int,
norm: Optional[Union[str, Callable]] = None,
):
"""
NOTE: this interface is experimental.
Args:
input_shape: shapes (channels and stride) of the input features
conv_dims: number of output channels for the intermediate conv layers.
mask_dim: number of output channels for the final conv layer.
norm (str or callable): normalization for all conv layers
"""
super().__init__()
input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
self.in_features = [k for k, v in input_shape] # starting from "res2" to "res5"
feature_channels = [v.channels for k, v in input_shape]
lateral_convs = []
output_convs = []
use_bias = norm == ""
for idx, in_channels in enumerate(feature_channels):
if idx == len(self.in_features) - 1:
output_norm = get_norm(norm, conv_dim)
output_conv = Conv2d(
in_channels,
conv_dim,
kernel_size=3,
stride=1,
padding=1,
bias=use_bias,
norm=output_norm,
activation=F.relu,
)
weight_init.c2_xavier_fill(output_conv)
self.add_module("layer_{}".format(idx + 1), output_conv)
lateral_convs.append(None)
output_convs.append(output_conv)
else:
lateral_norm = get_norm(norm, conv_dim)
output_norm = get_norm(norm, conv_dim)
lateral_conv = Conv2d(
in_channels, conv_dim, kernel_size=1, bias=use_bias, norm=lateral_norm
)
output_conv = Conv2d(
conv_dim,
conv_dim,
kernel_size=3,
stride=1,
padding=1,
bias=use_bias,
norm=output_norm,
activation=F.relu,
)
weight_init.c2_xavier_fill(lateral_conv)
weight_init.c2_xavier_fill(output_conv)
self.add_module("adapter_{}".format(idx + 1), lateral_conv)
self.add_module("layer_{}".format(idx + 1), output_conv)
lateral_convs.append(lateral_conv)
output_convs.append(output_conv)
# Place convs into top-down order (from low to high resolution)
# to make the top-down computation in forward clearer.
self.lateral_convs = lateral_convs[::-1]
self.output_convs = output_convs[::-1]
self.mask_dim = mask_dim
self.mask_features = Conv2d(
conv_dim,
mask_dim,
kernel_size=3,
stride=1,
padding=1,
)
weight_init.c2_xavier_fill(self.mask_features)
self.maskformer_num_feature_levels = 3 # always use 3 scales
@classmethod
def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]):
ret = {}
ret["input_shape"] = {
k: v for k, v in input_shape.items() if k in cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
}
ret["conv_dim"] = cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM
ret["mask_dim"] = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM
ret["norm"] = cfg.MODEL.SEM_SEG_HEAD.NORM
return ret
def forward_features(self, features):
multi_scale_features = []
num_cur_levels = 0
# Reverse feature maps into top-down order (from low to high resolution)
for idx, f in enumerate(self.in_features[::-1]):
x = features[f]
lateral_conv = self.lateral_convs[idx]
output_conv = self.output_convs[idx]
if lateral_conv is None:
y = output_conv(x)
else:
cur_fpn = lateral_conv(x)
# Following FPN implementation, we use nearest upsampling here
y = cur_fpn + F.interpolate(y, size=cur_fpn.shape[-2:], mode="nearest")
y = output_conv(y)
if num_cur_levels < self.maskformer_num_feature_levels:
multi_scale_features.append(y)
num_cur_levels += 1
return self.mask_features(y), None, multi_scale_features
def forward(self, features, targets=None):
logger = logging.getLogger(__name__)
logger.warning("Calling forward() may cause unpredicted behavior of PixelDecoder module.")
return self.forward_features(features)
class TransformerEncoderOnly(nn.Module):
def __init__(
self,
d_model=512,
nhead=8,
num_encoder_layers=6,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
):
super().__init__()
encoder_layer = TransformerEncoderLayer(
d_model, nhead, dim_feedforward, dropout, activation, normalize_before
)
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
self._reset_parameters()
self.d_model = d_model
self.nhead = nhead
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
def forward(self, src, mask, pos_embed):
# flatten NxCxHxW to HWxNxC
bs, c, h, w = src.shape
src = src.flatten(2).permute(2, 0, 1)
pos_embed = pos_embed.flatten(2).permute(2, 0, 1)
if mask is not None:
mask = mask.flatten(1)
memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed)
return memory.permute(1, 2, 0).view(bs, c, h, w)
# This is a modified FPN decoder with extra Transformer encoder that processes the lowest-resolution feature map.
@SEM_SEG_HEADS_REGISTRY.register()
class TransformerEncoderPixelDecoder(BasePixelDecoder):
@configurable
def __init__(
self,
input_shape: Dict[str, ShapeSpec],
*,
transformer_dropout: float,
transformer_nheads: int,
transformer_dim_feedforward: int,
transformer_enc_layers: int,
transformer_pre_norm: bool,
conv_dim: int,
mask_dim: int,
norm: Optional[Union[str, Callable]] = None,
):
"""
NOTE: this interface is experimental.
Args:
input_shape: shapes (channels and stride) of the input features
transformer_dropout: dropout probability in transformer
transformer_nheads: number of heads in transformer
transformer_dim_feedforward: dimension of feedforward network
transformer_enc_layers: number of transformer encoder layers
transformer_pre_norm: whether to use pre-layernorm or not
conv_dims: number of output channels for the intermediate conv layers.
mask_dim: number of output channels for the final conv layer.
norm (str or callable): normalization for all conv layers
"""
super().__init__(input_shape, conv_dim=conv_dim, mask_dim=mask_dim, norm=norm)
input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
self.in_features = [k for k, v in input_shape] # starting from "res2" to "res5"
feature_strides = [v.stride for k, v in input_shape]
feature_channels = [v.channels for k, v in input_shape]
in_channels = feature_channels[len(self.in_features) - 1]
self.input_proj = Conv2d(in_channels, conv_dim, kernel_size=1)
weight_init.c2_xavier_fill(self.input_proj)
self.transformer = TransformerEncoderOnly(
d_model=conv_dim,
dropout=transformer_dropout,
nhead=transformer_nheads,
dim_feedforward=transformer_dim_feedforward,
num_encoder_layers=transformer_enc_layers,
normalize_before=transformer_pre_norm,
)
N_steps = conv_dim // 2 | self.pe_layer = PositionEmbeddingSine(N_steps, normalize=True) | 0 | 2023-11-14 10:55:11+00:00 | 8k |
52phm/pylmkit | pylmkit/core/base.py | [
{
"identifier": "read_yaml",
"path": "pylmkit/utils/data_utils.py",
"snippet": "def read_yaml(filepath):\n try:\n with open(filepath, encoding=\"utf-8\") as fp:\n result = yaml.load(fp, Loader=SafeLoader)\n except Exception as e:\n raise Exception(e)\n return result"
... | from abc import ABC
from pathlib import Path
from tqdm import tqdm
from pydantic import Field, BaseModel
from pylmkit.utils.data_utils import read_yaml, read_json, write_yaml, write_json
from pylmkit.utils.data_utils import message_as_string, document_as_dict, dict_as_document
from typing import Any, List, Optional, Type, Union, Sequence, Literal
from pylmkit.perception.directory import BaseLoader
from pylmkit.utils.data_utils import text_as_document
from pylmkit.perception.directory import RecursiveCharacterTextSplitter
from functools import partial
from pylmkit.core.html import init_css, init_footer, init_logo
from pylmkit.core.html import _zh, _en
import time
import pandas as pd
import streamlit as st | 3,904 | self.page_icon = self.lang.get('_page_icon', None)
if self.footer_describe is None:
self.footer_describe = self.lang.get('_footer_describe', '')
if self.sidebar_title is None:
self.sidebar_title = self.lang.get('_sidebar_title', '')
if self.sidebar_describe is None:
self.sidebar_describe = self.lang.get('_sidebar_describe', '')
if self.logo1 is None:
self.logo1 = self.lang.get('_logo1', '')
if self.logo2 is None:
self.logo2 = self.lang.get('_logo2', '')
if self.greetings is None:
self.greetings = self.lang.get('_greetings', '')
if self.placeholder is None:
self.placeholder = self.lang.get('_placeholder', '')
if self.refer_name is None:
self.refer_name = self.lang.get('_refer_name', 'refer')
self.base_page()
if "messages" not in st.session_state:
st.session_state["messages"] = [{"role": "assistant", "content": self.greetings}]
self.input_kwargs = {}
st.session_state["output_kwargs"] = {}
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
# refer setting
refer = msg.get("refer", False)
if refer:
with st.expander(label=self.refer_name, expanded=False):
st.markdown(refer, unsafe_allow_html=True)
def _input(self, content, role="user", avatar="😄"):
st.chat_message(role, avatar=avatar).write(content, unsafe_allow_html=True)
msg = {"role": role, "content": content}
st.session_state.messages.append(msg)
def _output(self, content, refer=None, role="assistant"):
# st.chat_message(role).write(content, unsafe_allow_html=True)
with st.chat_message(role):
content_placeholder = st.empty()
full_content = ""
for chunk in content:
full_content += chunk + ""
time.sleep(0.01)
content_placeholder.markdown(full_content + "▌")
content_placeholder.markdown(full_content)
if refer: # refer setting
with st.expander(label=self.refer_name, expanded=False):
st.markdown(refer, unsafe_allow_html=True)
msg = {"role": role, "content": content, "refer": refer}
st.session_state.messages.append(msg)
def output_parse(self, output_param, output_result):
refer = None
if len(output_param) == 0:
response = None
elif len(output_param) == 1:
response = output_result
st.session_state["output_kwargs"][output_param[0]['name']] = response
else:
response = output_result[0]
for i, arg in enumerate(output_param):
st.session_state["output_kwargs"][arg['name']] = output_result[i]
if arg['type'] == 'chat':
response = output_result[i]
if arg['type'] == 'refer':
refer = output_result[i]
return response, refer
def run(self, obj, input_param: list, output_param: list):
chat_variable = ""
obj = self.wrapper(obj)
for arg in input_param:
if arg['type'] != 'chat':
self.input_kwargs[arg['name']] = generate_input_widget(mode='sidebar', **arg)
else:
chat_variable = arg['name']
if chat_variable:
if prompt := st.chat_input(placeholder=self.placeholder):
self.input_kwargs[chat_variable] = prompt
self._input(content=prompt)
with st.spinner('PyLMKit: Generating, please wait...'): # 正在生成,请稍候...
result = obj(**self.input_kwargs)
response, refer = self.output_parse(output_param, result)
self._output(content=response, refer=refer)
else:
with st.spinner('PyLMKit: Generating, please wait...'): # 正在生成,请稍候...
result = obj(**self.input_kwargs)
response, refer = self.output_parse(output_param, result)
# self._output(content=response, refer=refer)
with st.expander(label="output", expanded=True):
st.json(st.session_state["output_kwargs"], expanded=True)
def wrapper(self, fun):
return partial(fun)
def param(self, label, type, value, mode='sidebar'):
input_kwargs = {
"label": label,
"type": type,
"value": value
}
key = f"{label}-{type}-{str(value)}"
if key not in st.session_state.keys():
st.session_state[key] = ""
renew_value = generate_input_widget(
mode=mode,
**input_kwargs
)
return renew_value
def base_page(self):
st.set_page_config(
page_title=self.title,
layout=self.layout,
page_icon=self.page_icon,
)
st.markdown(init_css, unsafe_allow_html=True)
if self.footer_describe:
|
class BaseMemory(object):
human_prefix: str = "Human"
ai_prefix: str = "AI"
system_prefix: str = "System"
def __init__(self, init_memory=None, streamlit_web=False):
self.memory_messages = []
self.streamlit_web = streamlit_web
if self.streamlit_web: # streamlit rerun page, so need cache
if "memory" not in st.session_state:
st.session_state["memory"] = self.memory_messages
if isinstance(init_memory, list):
self.memory_messages = init_memory
if self.streamlit_web:
st.session_state['memory'] = self.memory_messages
if self.streamlit_web: # streamlit rerun page, so need cache
self.memory_messages = st.session_state['memory']
def add(self, role, content, refer=''):
""" role,human ai system
"""
if role in ['user', 'User', 'USER', 'human', 'Human', 'HUMAN']:
role = self.human_prefix
elif role in ['ai', 'Ai', 'AI', 'assistant']:
role = self.ai_prefix
elif role in ['sys', 'system', 'System', 'SYS', 'SYSTEM']:
role = self.system_prefix
else:
raise Exception(f"The role `{role}` does not exist")
self.memory_messages.append(
{"role": role, "content": content, "refer": refer, "date": time.strftime('%Y-%m-%d %H:%M:%S')})
if self.streamlit_web: # streamlit rerun page, so need cache
st.session_state['memory'] = self.memory_messages
def to_csv(self, filepath, index=False, **kwargs):
data = self.memory_messages
pd.DataFrame(data).to_csv(filepath, index=index, **kwargs)
def clear(self):
self.memory_messages = []
if self.streamlit_web: # streamlit rerun page, so need cache
st.session_state['memory'] = self.memory_messages
def _get(self, mode='message'):
if mode == 'message':
return self.memory_messages
elif mode == 'string':
return message_as_string(self.memory_messages)
else:
raise Exception(f"There is no such `{mode}` mode. Support modes: message, string")
class BaseKnowledgeBase(object):
def __init__(self, init_documents=None):
self.documents = []
self.splitter_documents = []
if isinstance(init_documents, list):
self.documents = init_documents
@classmethod
def load(cls, filepath, is_return=True, return_mode="doc", extend=True):
if filepath.endswith('.json'):
data = read_json(filepath)
elif filepath.endswith('.yaml') or filepath.endswith('yml'):
data = read_yaml(filepath) # data=[{},{}]
else:
raise Exception(f"The file type is not supported")
data_dict_as_document = dict_as_document(data)
result = cls()._base(documents=data_dict_as_document, return_mode=return_mode, is_return=is_return,
extend=extend)
if is_return:
return result
@classmethod
def add(cls, texts, metadatas=None, is_return=True, return_mode="doc", extend=True, types="Document"):
data_dict_as_document = text_as_document(texts=texts, metadatas=metadatas, types=types)
result = cls()._base(documents=data_dict_as_document, return_mode=return_mode, is_return=is_return,
extend=extend)
if is_return:
return result
def split(self, splitter=None, chunk_size=500, chunk_overlap=100, return_mode='doc', **kwargs):
if splitter is None:
splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap, **kwargs)
else:
splitter = splitter
self.splitter_documents = splitter.split_documents(self.documents)
if return_mode == 'doc':
return self.splitter_documents
else:
return document_as_dict(self.splitter_documents)
def to_csv_loader(self, filepath, index=False, **kwargs):
data = document_as_dict(self.documents)
pd.DataFrame(data).to_csv(filepath, index=index, **kwargs)
def to_csv_splitter(self,
filepath,
splitter=None,
chunk_size=500,
chunk_overlap=100,
index=False,
splitter_kwargs={},
csv_kwargs={}
):
if not self.splitter_documents:
self.splitter_documents = self.split(splitter=splitter, chunk_size=chunk_size,
chunk_overlap=chunk_overlap, **splitter_kwargs)
data = document_as_dict(self.splitter_documents)
pd.DataFrame(data).to_csv(filepath, index=index, **csv_kwargs)
def clear(self, mode='doc'):
if mode == 'doc':
self.documents = []
else:
self.splitter_documents = []
def _base(self, documents, is_return=True, return_mode='doc', extend=True):
if extend:
self.documents.extend(documents) # # dict -> Document
if is_return:
if return_mode == 'doc':
return self.documents
else:
return document_as_dict(self.documents)
else:
# self.documents = documents # when extend is False, just reset documents
if is_return:
if return_mode == 'doc':
return documents
else:
return document_as_dict(documents)
# def load_multi_memory(path: str, suffixes=None, show_progress: bool = True):
# data = []
# if suffixes is None:
# suffixes = [".yaml", '.json']
# if show_progress:
# for suffixe in tqdm(suffixes):
# for filepath in tqdm(list(Path(path).rglob(f"*{suffixe}"))):
# try:
# data += load_memory(filepath)
# except Exception as e:
# raise e
# else:
# for suffixe in suffixes:
# for filepath in list(Path(path).rglob(f"*{suffixe}")):
# try:
# data += load_memory(filepath)
# except Exception as e:
# raise e
# return data
def input_widget(input1, input2, type, value):
if type == "int":
return st.number_input(format='%d', step=1, **input1)
if type == "float":
return st.number_input(format='%f', **input1)
elif type in ['list', 'List', 'select']:
return st.selectbox(options=value, **input2)
elif type == "bool":
if value in [True, 'True', 'true']:
options = [True, False]
else:
options = [False, True]
return st.radio(options=options, horizontal=True, **input2)
elif type == "file":
uploaded_file = st.file_uploader(**input2)
if uploaded_file is not None:
res = str(Path().cwd() / uploaded_file.name)
with open(res, "wb") as f:
f.write(uploaded_file.getbuffer())
else:
res = None
return res
elif type in ['multiselect']:
return st.multiselect(options=value, **input2)
else:
return st.text_input(**input1)
def generate_input_widget(mode="main", **kwargs): # 在前端生成输入框
"""
mode, default "main" ,other "sidebar"
"""
label = kwargs.get('label', "")
value = kwargs.get('value', None)
name = kwargs.get('name', None)
_input1 = {"label": label, "value": value, "key": f"{name}-{label}"}
_input2 = {"label": label, "key": f"{name}-{label}"}
_type = kwargs.get('type', None) # int float bool string chat file
if mode == 'main':
return input_widget(
input1=_input1,
input2=_input2,
type=_type,
value=value
)
else:
with st.sidebar:
return input_widget(
input1=_input1,
input2=_input2,
type=_type,
value=value
)
class BaseWebUI(object):
def __init__(self,
title=None,
page_icon=None,
layout="centered",
language='en',
sidebar_title=None,
sidebar_describe=None,
footer_describe=None,
logo1=None,
logo2=None,
greetings=None,
placeholder=None,
refer_name=None,
):
self.title = title
self.layout = layout
self.page_icon = page_icon
self.footer_describe = footer_describe
self.sidebar_title = sidebar_title
self.sidebar_describe = sidebar_describe
self.logo1 = logo1
self.logo2 = logo2
self.greetings = greetings
self.placeholder = placeholder
self.refer_name = refer_name
if language in ['zh', '中国', 'china']:
self.lang = _zh
else:
self.lang = _en
if self.title is None:
self.title = self.lang.get('_title', '')
if self.page_icon is None:
self.page_icon = self.lang.get('_page_icon', None)
if self.footer_describe is None:
self.footer_describe = self.lang.get('_footer_describe', '')
if self.sidebar_title is None:
self.sidebar_title = self.lang.get('_sidebar_title', '')
if self.sidebar_describe is None:
self.sidebar_describe = self.lang.get('_sidebar_describe', '')
if self.logo1 is None:
self.logo1 = self.lang.get('_logo1', '')
if self.logo2 is None:
self.logo2 = self.lang.get('_logo2', '')
if self.greetings is None:
self.greetings = self.lang.get('_greetings', '')
if self.placeholder is None:
self.placeholder = self.lang.get('_placeholder', '')
if self.refer_name is None:
self.refer_name = self.lang.get('_refer_name', 'refer')
self.base_page()
if "messages" not in st.session_state:
st.session_state["messages"] = [{"role": "assistant", "content": self.greetings}]
self.input_kwargs = {}
st.session_state["output_kwargs"] = {}
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
# refer setting
refer = msg.get("refer", False)
if refer:
with st.expander(label=self.refer_name, expanded=False):
st.markdown(refer, unsafe_allow_html=True)
def _input(self, content, role="user", avatar="😄"):
st.chat_message(role, avatar=avatar).write(content, unsafe_allow_html=True)
msg = {"role": role, "content": content}
st.session_state.messages.append(msg)
def _output(self, content, refer=None, role="assistant"):
# st.chat_message(role).write(content, unsafe_allow_html=True)
with st.chat_message(role):
content_placeholder = st.empty()
full_content = ""
for chunk in content:
full_content += chunk + ""
time.sleep(0.01)
content_placeholder.markdown(full_content + "▌")
content_placeholder.markdown(full_content)
if refer: # refer setting
with st.expander(label=self.refer_name, expanded=False):
st.markdown(refer, unsafe_allow_html=True)
msg = {"role": role, "content": content, "refer": refer}
st.session_state.messages.append(msg)
def output_parse(self, output_param, output_result):
refer = None
if len(output_param) == 0:
response = None
elif len(output_param) == 1:
response = output_result
st.session_state["output_kwargs"][output_param[0]['name']] = response
else:
response = output_result[0]
for i, arg in enumerate(output_param):
st.session_state["output_kwargs"][arg['name']] = output_result[i]
if arg['type'] == 'chat':
response = output_result[i]
if arg['type'] == 'refer':
refer = output_result[i]
return response, refer
def run(self, obj, input_param: list, output_param: list):
chat_variable = ""
obj = self.wrapper(obj)
for arg in input_param:
if arg['type'] != 'chat':
self.input_kwargs[arg['name']] = generate_input_widget(mode='sidebar', **arg)
else:
chat_variable = arg['name']
if chat_variable:
if prompt := st.chat_input(placeholder=self.placeholder):
self.input_kwargs[chat_variable] = prompt
self._input(content=prompt)
with st.spinner('PyLMKit: Generating, please wait...'): # 正在生成,请稍候...
result = obj(**self.input_kwargs)
response, refer = self.output_parse(output_param, result)
self._output(content=response, refer=refer)
else:
with st.spinner('PyLMKit: Generating, please wait...'): # 正在生成,请稍候...
result = obj(**self.input_kwargs)
response, refer = self.output_parse(output_param, result)
# self._output(content=response, refer=refer)
with st.expander(label="output", expanded=True):
st.json(st.session_state["output_kwargs"], expanded=True)
def wrapper(self, fun):
return partial(fun)
def param(self, label, type, value, mode='sidebar'):
input_kwargs = {
"label": label,
"type": type,
"value": value
}
key = f"{label}-{type}-{str(value)}"
if key not in st.session_state.keys():
st.session_state[key] = ""
renew_value = generate_input_widget(
mode=mode,
**input_kwargs
)
return renew_value
def base_page(self):
st.set_page_config(
page_title=self.title,
layout=self.layout,
page_icon=self.page_icon,
)
st.markdown(init_css, unsafe_allow_html=True)
if self.footer_describe: | st.sidebar.markdown(init_footer.format(self.footer_describe), unsafe_allow_html=True) | 10 | 2023-11-18 10:31:58+00:00 | 8k |
ej0cl6/TextEE | TextEE/models/UniST/EDtrainer.py | [
{
"identifier": "BasicTrainer",
"path": "TextEE/models/trainer.py",
"snippet": "class BasicTrainer(object):\n def __init__(self, config, type_set=None):\n self.config = config\n self.type_set = type_set\n \n @classmethod\n def add_extra_info_fn(cls, instances, raw_data, con... | import os, sys, logging, tqdm, pprint
import torch
import numpy as np
import ipdb
from collections import namedtuple
from transformers import RobertaTokenizer, AutoTokenizer, get_linear_schedule_with_warmup
from torch.utils.data import DataLoader
from torch.optim import AdamW
from ..trainer import BasicTrainer
from .EDmodel import UniSTModel, SpanModel
from scorer import compute_ED_scores, print_scores | 5,341 |
logger = logging.getLogger(__name__)
EDBatch_fields = ['batch_doc_id', 'batch_wnd_id', 'batch_tokens', 'batch_pieces', 'batch_token_lens', 'batch_token_num', 'batch_text', 'batch_triggers', 'batch_spans']
EDBatch = namedtuple('EDBatch', field_names=EDBatch_fields, defaults=[None] * len(EDBatch_fields))
def ED_collate_fn(batch):
return EDBatch(
batch_doc_id=[instance["doc_id"] for instance in batch],
batch_wnd_id=[instance["wnd_id"] for instance in batch],
batch_tokens=[instance["tokens"] for instance in batch],
batch_pieces=[instance["pieces"] for instance in batch],
batch_token_lens=[instance["token_lens"] for instance in batch],
batch_token_num=[instance["token_num"] for instance in batch],
batch_text=[instance["text"] for instance in batch],
batch_triggers=[instance["triggers"] for instance in batch],
batch_spans=[instance["spans"] for instance in batch],
)
|
logger = logging.getLogger(__name__)
EDBatch_fields = ['batch_doc_id', 'batch_wnd_id', 'batch_tokens', 'batch_pieces', 'batch_token_lens', 'batch_token_num', 'batch_text', 'batch_triggers', 'batch_spans']
EDBatch = namedtuple('EDBatch', field_names=EDBatch_fields, defaults=[None] * len(EDBatch_fields))
def ED_collate_fn(batch):
return EDBatch(
batch_doc_id=[instance["doc_id"] for instance in batch],
batch_wnd_id=[instance["wnd_id"] for instance in batch],
batch_tokens=[instance["tokens"] for instance in batch],
batch_pieces=[instance["pieces"] for instance in batch],
batch_token_lens=[instance["token_lens"] for instance in batch],
batch_token_num=[instance["token_num"] for instance in batch],
batch_text=[instance["text"] for instance in batch],
batch_triggers=[instance["triggers"] for instance in batch],
batch_spans=[instance["spans"] for instance in batch],
)
| class UniSTEDTrainer(BasicTrainer): | 0 | 2023-11-15 21:32:56+00:00 | 8k |
isce-framework/snaphu-py | src/snaphu/_unwrap.py | [
{
"identifier": "run_snaphu",
"path": "src/snaphu/_snaphu.py",
"snippet": "def run_snaphu(config_file: str | os.PathLike[str]) -> None:\n \"\"\"\n Run SNAPHU with the specified config file.\n\n Parameters\n ----------\n config_file : path-like\n The file path of a text file storing... | import io
import os
import textwrap
import numpy as np
from dataclasses import dataclass
from pathlib import Path
from tempfile import mkstemp
from typing import cast, overload
from ._snaphu import run_snaphu
from ._util import BlockIterator, scratch_directory
from .io import InputDataset, OutputDataset | 4,853 | belonging to any component are assigned a label of zero.
Parameters
----------
igram : snaphu.io.InputDataset
The input interferogram. A 2-D complex-valued array. Not a Number (NaN) values
in the array will be replaced with zeros.
corr : snaphu.io.InputDataset
The sample coherence magnitude. Must be a floating-point array with the same
dimensions as the input interferogram. Valid coherence values are in the range
[0, 1]. NaN values in the array will be replaced with zeros.
nlooks : float
The equivalent number of independent looks used to form the sample coherence. An
estimate of the number of statistically independent samples averaged in the
multilooked data, taking into account spatial correlation due to
oversampling/filtering (see `Notes`_).
cost : {'defo', 'smooth'}, optional
Statistical cost mode. Defaults to 'smooth'.
init : {'mst', 'mcf'}, optional
Algorithm used for initialization of unwrapped phase gradients.
Supported algorithms include Minimum Spanning Tree ('mst') and Minimum
Cost Flow ('mcf'). Defaults to 'mcf'.
mask : snaphu.io.InputDataset or None, optional
Binary mask of valid pixels. Zeros in this raster indicate interferogram
pixels that should be masked out. If provided, it must have the same dimensions
as the input interferogram and boolean or 8-bit integer datatype. Defaults to
None.
ntiles : (int, int), optional
Number of tiles along the row/column directions. If `ntiles` is (1, 1), then the
interferogram will be unwrapped as a single tile. Increasing the number of tiles
may improve runtime and reduce peak memory utilization, but may also introduce
tile boundary artifacts in the unwrapped result. Defaults to (1, 1).
tile_overlap : int or (int, int), optional
Overlap, in pixels, between neighboring tiles. Increasing overlap may help to
avoid phase discontinuities between tiles. If `tile_overlap` is a scalar
integer, the number of overlapping rows and columns will be the same. Defaults
to 0.
nproc : int, optional
Maximum number of child processes to spawn for parallel tile unwrapping. If
`nproc` is less than 1, use all available processors. Defaults to 1.
scratchdir : path-like or None, optional
Scratch directory where intermediate processing artifacts are written.
If the specified directory does not exist, it will be created. If None,
a temporary directory will be created as though by
``tempfile.TemporaryDirectory()``. Defaults to None.
delete_scratch : bool, optional
If True, the scratch directory will be automatically removed from the file
system when the function exits. Otherwise, the scratch directory will be
preserved. Defaults to True.
unw : snaphu.io.OutputDataset or None, optional
An optional output dataset to store the unwrapped phase, in radians. If
provided, it must have the same dimensions as the input interferogram and
floating-point datatype. If None, an output array will be allocated internally.
Defaults to None.
conncomp : snaphu.io.OutputDataset or None, optional
An optional output dataset to store the connected component labels. If provided,
it must have the same dimensions as the input interferogram and any integer
datatype. If None, an output array will be allocated internally. Defaults to
None.
Returns
-------
unw : snaphu.io.OutputDataset
The output unwrapped phase, in radians.
conncomp : snaphu.io.OutputDataset
The output connected component labels.
Notes
-----
An estimate of the equivalent number of independent looks may be obtained by
.. math:: n_e = k_r k_a \frac{d_r d_a}{\rho_r \rho_a}
where :math:`k_r` and :math:`k_a` are the number of looks in range and azimuth,
:math:`d_r` and :math:`d_a` are the (single-look) sample spacing in range and
azimuth, and :math:`\rho_r` and :math:`\rho_a are the range and azimuth resolution.
References
----------
.. [1] C. W. Chen and H. A. Zebker, "Two-dimensional phase unwrapping with use of
statistical models for cost functions in nonlinear optimization," Journal of the
Optical Society of America A, vol. 18, pp. 338-351 (2001).
.. [2] C. W. Chen and H. A. Zebker, "Phase unwrapping for large SAR interferograms:
Statistical segmentation and generalized network models," IEEE Transactions on
Geoscience and Remote Sensing, vol. 40, pp. 1709-1719 (2002).
"""
# If the `unw` and/or `conncomp` output datasets were not provided, allocate arrays
# to store these outputs.
if unw is None:
unw = np.zeros(shape=igram.shape, dtype=np.float32)
if conncomp is None:
conncomp = np.zeros(shape=igram.shape, dtype=np.uint32)
# Ensure that input & output datasets have valid dimensions and datatypes.
check_shapes(igram, corr, unw, conncomp, mask)
check_dtypes(igram, corr, unw, conncomp, mask)
if nlooks < 1.0:
errmsg = f"nlooks must be >= 1, instead got {nlooks}"
raise ValueError(errmsg)
if cost == "topo":
errmsg = "'topo' cost mode is not currently supported"
raise NotImplementedError(errmsg)
cost_modes = {"defo", "smooth"}
if cost not in cost_modes:
errmsg = f"cost mode must be in {cost_modes}, instead got {cost!r}"
raise ValueError(errmsg)
init_methods = {"mst", "mcf"}
if init not in init_methods:
errmsg = f"init method must be in {init_methods}, instead got {init!r}"
raise ValueError(errmsg)
# Validate inputs related to tiling and coerce them to the expected types.
ntiles, tile_overlap, nproc = normalize_and_validate_tiling_params(
ntiles=ntiles, tile_overlap=tile_overlap, nproc=nproc
)
| from __future__ import annotations
__all__ = [
"unwrap",
]
@dataclass(frozen=True)
class TilingParams:
"""
SNAPHU configuration parameters affecting scene tiling and parallel processing.
Parameters
----------
ntilerow, ntilecol : int, optional
Number of tiles along the row/column directions. If `ntilerow` and `ntilecol`
are both 1 (the default), the interferogram will be unwrapped as a single tile.
rowovrlp, colovrlp : int, optional
Overlap, in number of rows/columns, between neighboring tiles. Defaults to 0.
nproc : int, optional
Maximum number of child processes to spawn for parallel tile unwrapping.
Defaults to 1.
"""
ntilerow: int = 1
ntilecol: int = 1
rowovrlp: int = 0
colovrlp: int = 0
nproc: int = 1
def to_string(self) -> str:
"""
Write SNAPHU tiling parameters to a string.
Creates a multi-line string in SNAPHU configuration file format.
Returns
-------
str
The output string.
"""
return textwrap.dedent(f"""\
NTILEROW {self.ntilerow}
NTILECOL {self.ntilecol}
ROWOVRLP {self.rowovrlp}
COLOVRLP {self.colovrlp}
NPROC {self.nproc}
""")
@dataclass(frozen=True)
class SnaphuConfig:
"""
SNAPHU configuration parameters.
Parameters
----------
infile : path-like
The input interferogram file path.
corrfile : path-like
The input coherence file path.
outfile : path-like
The output unwrapped phase file path.
conncompfile : path-like
The output connected component labels file path.
linelength : int
The line length, in samples, of the input interferogram data array.
ncorrlooks : float
The equivalent number of independent looks used to form the coherence data.
statcostmode : str
The statistical cost mode.
initmethod : str
The algorithm used for initializing the network solver routine.
bytemaskfile : path-like or None, optional
An optional file path of a byte mask file. If None, no mask is applied. Defaults
to None.
tiling_params : TilingParams or None, optional
Optional additional configuration parameters affecting scene tiling and parallel
processing. Defaults to None.
"""
infile: str | os.PathLike[str]
corrfile: str | os.PathLike[str]
outfile: str | os.PathLike[str]
conncompfile: str | os.PathLike[str]
linelength: int
ncorrlooks: float
statcostmode: str
initmethod: str
bytemaskfile: str | os.PathLike[str] | None = None
tiling_params: TilingParams | None = None
def to_string(self) -> str:
"""
Write SNAPHU configuration parameters to a string.
Creates a multi-line string in SNAPHU configuration file format.
Returns
-------
str
The output string.
"""
config = textwrap.dedent(f"""\
INFILE {os.fspath(self.infile)}
INFILEFORMAT COMPLEX_DATA
CORRFILE {os.fspath(self.corrfile)}
CORRFILEFORMAT FLOAT_DATA
OUTFILE {os.fspath(self.outfile)}
OUTFILEFORMAT FLOAT_DATA
CONNCOMPFILE {os.fspath(self.conncompfile)}
CONNCOMPOUTTYPE UINT
LINELENGTH {self.linelength}
NCORRLOOKS {self.ncorrlooks}
STATCOSTMODE {self.statcostmode.upper()}
INITMETHOD {self.initmethod.upper()}
""")
if self.bytemaskfile is not None:
config += f"BYTEMASKFILE {os.fspath(self.bytemaskfile)}\n"
if self.tiling_params is not None:
config += self.tiling_params.to_string()
return config
def _to_file_textio(self, file_: io.TextIOBase, /) -> None:
# Write config params to file.
s = self.to_string()
count = file_.write(s)
# Check that the full text was successfully written to the file.
if count != len(s):
errmsg = "failed to write config params to file"
raise RuntimeError(errmsg)
def _to_file_pathlike(self, file_: str | os.PathLike[str], /) -> None:
# Create the file's parent directory(ies) if they didn't already exist.
p = Path(file_)
p.parent.mkdir(parents=True, exist_ok=True)
# Write config params to file.
s = self.to_string()
p.write_text(s)
def to_file(self, file_: str | os.PathLike[str] | io.TextIOBase, /) -> None:
"""
Write SNAPHU configuration parameters to a file.
The resulting file is suitable for passing to the SNAPHU executable as a
configuration file.
Parameters
----------
file_ : path-like or file-like
The output file. May be an open text file or a file path. If the file
and any of its parent directories do not exist, they will be created. If the
path to an existing file is specified, the file will be overwritten.
"""
if isinstance(file_, io.TextIOBase):
self._to_file_textio(file_)
elif isinstance(file_, (str, os.PathLike)):
self._to_file_pathlike(file_)
else:
errmsg = (
"to_file argument must be a path-like or file-like object, instead got"
f" type={type(file_)}"
)
raise TypeError(errmsg)
def check_shapes(
igram: InputDataset,
corr: InputDataset,
unw: OutputDataset,
conncomp: OutputDataset,
mask: InputDataset | None = None,
) -> None:
"""
Check that the arguments are 2-D arrays with matching shapes.
Parameters
----------
igram : snaphu.io.InputDataset
The input interferogram. Must be a 2-D array.
corr : snaphu.io.InputDataset
The input coherence. Must be a 2-D array with the same shape as `igram`.
unw : snaphu.io.OutputDataset
The output unwrapped phase. Must be a 2-D array with the same shape as `igram`.
conncomp : snaphu.io.OutputDataset
The output connected component labels. Must be a 2-D array with the same shape
as `igram`.
mask : snaphu.io.InputDataset or None, optional
An optional binary mask of valid samples. If not None, it must be a 2-D array
with the same shape as `igram`. Defaults to None.
Raises
------
ValueError
If any array is not 2-D or has a different shape than the others.
"""
if igram.ndim != 2:
errmsg = f"igram must be 2-D, instead got ndim={igram.ndim}"
raise ValueError(errmsg)
def raise_shape_mismatch_error(
name: str,
arr: InputDataset | OutputDataset,
) -> None:
errmsg = (
f"shape mismatch: {name} and igram must have the same shape, instead got"
f" {name}.shape={arr.shape} and {igram.shape=}"
)
raise ValueError(errmsg)
if corr.shape != igram.shape:
raise_shape_mismatch_error("corr", corr)
if unw.shape != igram.shape:
raise_shape_mismatch_error("unw", unw)
if conncomp.shape != igram.shape:
raise_shape_mismatch_error("conncomp", conncomp)
if (mask is not None) and (mask.shape != igram.shape):
raise_shape_mismatch_error("mask", mask)
def check_dtypes(
igram: InputDataset,
corr: InputDataset,
unw: OutputDataset,
conncomp: OutputDataset,
mask: InputDataset | None = None,
) -> None:
"""
Check that the arguments have valid datatypes.
Parameters
----------
igram : snaphu.io.InputDataset
The input interferogram. Must be a complex-valued array.
corr : snaphu.io.InputDataset
The input coherence. Must be a real-valued array.
unw : snaphu.io.OutputDataset
The output unwrapped phase. Must be a real-valued array.
conncomp : snaphu.io.OutputDataset
The output connected component labels. Must be an integer-valued array.
mask : snaphu.io.InputDataset or None, optional
An optional binary mask of valid samples. If not None, it must be a boolean or
8-bit integer array.
Raises
------
TypeError
If any array has an unexpected datatype.
"""
if not np.issubdtype(igram.dtype, np.complexfloating):
errmsg = (
f"igram must be a complex-valued array, instead got dtype={igram.dtype}"
)
raise TypeError(errmsg)
if not np.issubdtype(corr.dtype, np.floating):
errmsg = f"corr must be a real-valued array, instead got dtype={corr.dtype}"
raise TypeError(errmsg)
if not np.issubdtype(unw.dtype, np.floating):
errmsg = f"unw must be a real-valued array, instead got dtype={unw.dtype}"
raise TypeError(errmsg)
if not np.issubdtype(conncomp.dtype, np.integer):
errmsg = (
"conncomp must be an integer-valued array, instead got"
f" dtype={conncomp.dtype}"
)
raise TypeError(errmsg)
if (
(mask is not None)
and (mask.dtype != np.bool_)
and (mask.dtype != np.uint8)
and (mask.dtype != np.int8)
):
errmsg = (
"mask must be a boolean or 8-bit integer array (or None), instead got"
f" dtype={mask.dtype}"
)
raise TypeError(errmsg)
def normalize_and_validate_tiling_params(
ntiles: tuple[int, int],
tile_overlap: int | tuple[int, int],
nproc: int,
) -> tuple[tuple[int, int], tuple[int, int], int]:
"""
Normalize and validate inputs related to tiling and multiprocessing.
Parameters
----------
ntiles : (int, int)
Number of tiles along the row/column directions.
tile_overlap : int or (int, int)
Overlap, in pixels, between neighboring tiles.
nproc : int
Maximum number of child processes to spawn for parallel tile unwrapping.
Returns
-------
ntiles : (int, int)
`ntiles` normalized to a pair of positive integers.
tile_overlap : (int, int)
`tile_overlap` normalized to a pair of nonnegative integers.
nproc : int
`nproc` as a positive integer.
"""
# Normalize `ntiles` to a tuple and ensure its contents are two positive-valued
# integers.
ntiles = tuple(ntiles) # type: ignore[assignment]
if len(ntiles) != 2:
errmsg = f"ntiles must be a pair of ints, instead got {ntiles=}"
raise ValueError(errmsg)
if not all(n >= 1 for n in ntiles):
errmsg = f"ntiles may not contain negative or zero values, got {ntiles=}"
raise ValueError(errmsg)
# If `tile_overlap` is iterable, ensure it's a tuple. Otherwise, assume it's a
# single integer.
try:
tile_overlap = tuple(tile_overlap) # type: ignore[arg-type,assignment]
except TypeError:
tile_overlap = (tile_overlap, tile_overlap) # type: ignore[assignment]
# Convince static type checkers that `tile_overlap` is now a pair of ints.
tile_overlap = cast(tuple[int, int], tile_overlap)
# Ensure the contents of `tile_overlap` are two nonnegative integers.
if len(tile_overlap) != 2:
errmsg = (
f"tile_overlap must be an int or pair of ints, instead got {tile_overlap=}"
)
raise ValueError(errmsg)
if not all(n >= 0 for n in tile_overlap):
errmsg = f"tile_overlap may not contain negative values, got {tile_overlap=}"
raise ValueError(errmsg)
# If `nproc` is less than 1, use all available processors. Fall back to serial
# execution if the number of available processors cannot be determined.
if nproc < 1:
nproc = os.cpu_count() or 1
return ntiles, tile_overlap, nproc
def copy_blockwise(
src: InputDataset,
dst: OutputDataset,
chunks: tuple[int, int] = (1024, 1024),
*,
nan_to_zero: bool = False,
) -> None:
"""
Copy the contents of `src` to `dst` block-by-block.
Parameters
----------
src : snaphu.io.InputDataset
Source dataset.
dst : snaphu.io.OutputDataset
Destination dataset.
chunks : (int, int), optional
Block dimensions. Defaults to (1024, 1024).
nan_to_zero : bool, optional
If True, replace Not a Number (NaN) values in the array with zeros in the
output. Defaults to False.
"""
shape = src.shape
if dst.shape != shape:
errmsg = (
"shape mismatch: src and dst must have the same shape, instead got"
f" {src.shape=} and {dst.shape=}"
)
raise ValueError(errmsg)
for block in BlockIterator(shape, chunks):
if nan_to_zero:
nan_mask = np.isnan(src[block])
dst[block] = np.where(nan_mask, 0.0, src[block])
else:
dst[block] = src[block]
@overload
def unwrap(
igram: InputDataset,
corr: InputDataset,
nlooks: float,
cost: str = "smooth",
init: str = "mcf",
*,
mask: InputDataset | None = None,
ntiles: tuple[int, int] = (1, 1),
tile_overlap: int | tuple[int, int] = 0,
nproc: int = 1,
scratchdir: str | os.PathLike[str] | None = None,
delete_scratch: bool = True,
unw: OutputDataset,
conncomp: OutputDataset,
) -> tuple[OutputDataset, OutputDataset]: ... # pragma: no cover
# If `unw` and `conncomp` aren't specified, return the outputs as two NumPy arrays.
@overload
def unwrap(
igram: InputDataset,
corr: InputDataset,
nlooks: float,
cost: str = "smooth",
init: str = "mcf",
*,
mask: InputDataset | None = None,
ntiles: tuple[int, int] = (1, 1),
tile_overlap: int | tuple[int, int] = 0,
nproc: int = 1,
scratchdir: str | os.PathLike[str] | None = None,
delete_scratch: bool = True,
) -> tuple[np.ndarray, np.ndarray]: ... # pragma: no cover
def unwrap( # type: ignore[no-untyped-def]
igram,
corr,
nlooks,
cost="smooth",
init="mcf",
*,
mask=None,
ntiles=(1, 1),
tile_overlap=0,
nproc=1,
scratchdir=None,
delete_scratch=True,
unw=None,
conncomp=None,
):
r"""
Unwrap an interferogram using SNAPHU.
Performs 2-D phase unwrapping using the Statistical-Cost, Network-Flow Algorithm for
Phase Unwrapping (SNAPHU)\ [1]_. The algorithm produces a Maximum a Posteriori (MAP)
estimate of the unwrapped phase field by (approximately) solving a nonlinear network
flow optimization problem.
The outputs include the unwrapped phase and a corresponding array of connected
component labels. Each connected component is a region of pixels in the solution
that is believed to have been unwrapped in an internally self-consistent manner\
[2]_. Each distinct region is assigned a unique positive integer label. Pixels not
belonging to any component are assigned a label of zero.
Parameters
----------
igram : snaphu.io.InputDataset
The input interferogram. A 2-D complex-valued array. Not a Number (NaN) values
in the array will be replaced with zeros.
corr : snaphu.io.InputDataset
The sample coherence magnitude. Must be a floating-point array with the same
dimensions as the input interferogram. Valid coherence values are in the range
[0, 1]. NaN values in the array will be replaced with zeros.
nlooks : float
The equivalent number of independent looks used to form the sample coherence. An
estimate of the number of statistically independent samples averaged in the
multilooked data, taking into account spatial correlation due to
oversampling/filtering (see `Notes`_).
cost : {'defo', 'smooth'}, optional
Statistical cost mode. Defaults to 'smooth'.
init : {'mst', 'mcf'}, optional
Algorithm used for initialization of unwrapped phase gradients.
Supported algorithms include Minimum Spanning Tree ('mst') and Minimum
Cost Flow ('mcf'). Defaults to 'mcf'.
mask : snaphu.io.InputDataset or None, optional
Binary mask of valid pixels. Zeros in this raster indicate interferogram
pixels that should be masked out. If provided, it must have the same dimensions
as the input interferogram and boolean or 8-bit integer datatype. Defaults to
None.
ntiles : (int, int), optional
Number of tiles along the row/column directions. If `ntiles` is (1, 1), then the
interferogram will be unwrapped as a single tile. Increasing the number of tiles
may improve runtime and reduce peak memory utilization, but may also introduce
tile boundary artifacts in the unwrapped result. Defaults to (1, 1).
tile_overlap : int or (int, int), optional
Overlap, in pixels, between neighboring tiles. Increasing overlap may help to
avoid phase discontinuities between tiles. If `tile_overlap` is a scalar
integer, the number of overlapping rows and columns will be the same. Defaults
to 0.
nproc : int, optional
Maximum number of child processes to spawn for parallel tile unwrapping. If
`nproc` is less than 1, use all available processors. Defaults to 1.
scratchdir : path-like or None, optional
Scratch directory where intermediate processing artifacts are written.
If the specified directory does not exist, it will be created. If None,
a temporary directory will be created as though by
``tempfile.TemporaryDirectory()``. Defaults to None.
delete_scratch : bool, optional
If True, the scratch directory will be automatically removed from the file
system when the function exits. Otherwise, the scratch directory will be
preserved. Defaults to True.
unw : snaphu.io.OutputDataset or None, optional
An optional output dataset to store the unwrapped phase, in radians. If
provided, it must have the same dimensions as the input interferogram and
floating-point datatype. If None, an output array will be allocated internally.
Defaults to None.
conncomp : snaphu.io.OutputDataset or None, optional
An optional output dataset to store the connected component labels. If provided,
it must have the same dimensions as the input interferogram and any integer
datatype. If None, an output array will be allocated internally. Defaults to
None.
Returns
-------
unw : snaphu.io.OutputDataset
The output unwrapped phase, in radians.
conncomp : snaphu.io.OutputDataset
The output connected component labels.
Notes
-----
An estimate of the equivalent number of independent looks may be obtained by
.. math:: n_e = k_r k_a \frac{d_r d_a}{\rho_r \rho_a}
where :math:`k_r` and :math:`k_a` are the number of looks in range and azimuth,
:math:`d_r` and :math:`d_a` are the (single-look) sample spacing in range and
azimuth, and :math:`\rho_r` and :math:`\rho_a are the range and azimuth resolution.
References
----------
.. [1] C. W. Chen and H. A. Zebker, "Two-dimensional phase unwrapping with use of
statistical models for cost functions in nonlinear optimization," Journal of the
Optical Society of America A, vol. 18, pp. 338-351 (2001).
.. [2] C. W. Chen and H. A. Zebker, "Phase unwrapping for large SAR interferograms:
Statistical segmentation and generalized network models," IEEE Transactions on
Geoscience and Remote Sensing, vol. 40, pp. 1709-1719 (2002).
"""
# If the `unw` and/or `conncomp` output datasets were not provided, allocate arrays
# to store these outputs.
if unw is None:
unw = np.zeros(shape=igram.shape, dtype=np.float32)
if conncomp is None:
conncomp = np.zeros(shape=igram.shape, dtype=np.uint32)
# Ensure that input & output datasets have valid dimensions and datatypes.
check_shapes(igram, corr, unw, conncomp, mask)
check_dtypes(igram, corr, unw, conncomp, mask)
if nlooks < 1.0:
errmsg = f"nlooks must be >= 1, instead got {nlooks}"
raise ValueError(errmsg)
if cost == "topo":
errmsg = "'topo' cost mode is not currently supported"
raise NotImplementedError(errmsg)
cost_modes = {"defo", "smooth"}
if cost not in cost_modes:
errmsg = f"cost mode must be in {cost_modes}, instead got {cost!r}"
raise ValueError(errmsg)
init_methods = {"mst", "mcf"}
if init not in init_methods:
errmsg = f"init method must be in {init_methods}, instead got {init!r}"
raise ValueError(errmsg)
# Validate inputs related to tiling and coerce them to the expected types.
ntiles, tile_overlap, nproc = normalize_and_validate_tiling_params(
ntiles=ntiles, tile_overlap=tile_overlap, nproc=nproc
)
| with scratch_directory(scratchdir, delete=delete_scratch) as dir_: | 2 | 2023-11-16 21:48:58+00:00 | 8k |
fofr/cog-sdxl-multi-controlnet-lora | predict.py | [
{
"identifier": "WeightsDownloader",
"path": "weights_downloader.py",
"snippet": "class WeightsDownloader:\n @staticmethod\n def download_if_not_exists(url, dest):\n if not os.path.exists(dest):\n WeightsDownloader.download(url, dest)\n\n @staticmethod\n def download(url, d... | import os
import time
import numpy as np
import torch
from typing import List, Optional
from cog import BasePredictor, Input, Path
from diffusers import (
DDIMScheduler,
DiffusionPipeline,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
HeunDiscreteScheduler,
PNDMScheduler,
StableDiffusionXLImg2ImgPipeline,
StableDiffusionXLInpaintPipeline,
StableDiffusionXLControlNetPipeline,
StableDiffusionXLControlNetInpaintPipeline,
StableDiffusionXLControlNetImg2ImgPipeline,
)
from diffusers.pipelines.stable_diffusion.safety_checker import (
StableDiffusionSafetyChecker,
)
from transformers import CLIPImageProcessor
from weights_downloader import WeightsDownloader
from weights_manager import WeightsManager
from controlnet import ControlNet
from sizing_strategy import SizingStrategy | 3,716 | SAFETY_URL = "https://weights.replicate.delivery/default/sdxl/safety-1.0.tar"
class KarrasDPM:
def from_config(config):
return DPMSolverMultistepScheduler.from_config(config, use_karras_sigmas=True)
SCHEDULERS = {
"DDIM": DDIMScheduler,
"DPMSolverMultistep": DPMSolverMultistepScheduler,
"HeunDiscrete": HeunDiscreteScheduler,
"KarrasDPM": KarrasDPM,
"K_EULER_ANCESTRAL": EulerAncestralDiscreteScheduler,
"K_EULER": EulerDiscreteScheduler,
"PNDM": PNDMScheduler,
}
class Predictor(BasePredictor):
def load_trained_weights(self, weights, pipe):
self.weights_manager.load_trained_weights(weights, pipe)
def build_controlnet_pipeline(self, pipeline_class, controlnet_models):
pipe = pipeline_class.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
controlnet=self.controlnet.get_models(controlnet_models),
)
pipe.to("cuda")
return pipe
def setup(self, weights: Optional[Path] = None):
"""Load the model into memory to make running multiple predictions efficient"""
start = time.time()
self.sizing_strategy = SizingStrategy()
self.weights_manager = WeightsManager(self)
self.tuned_model = False
self.tuned_weights = None
if str(weights) == "weights":
weights = None
print("Loading safety checker...")
WeightsDownloader.download_if_not_exists(SAFETY_URL, SAFETY_CACHE)
self.safety_checker = StableDiffusionSafetyChecker.from_pretrained(
SAFETY_CACHE, torch_dtype=torch.float16
).to("cuda")
self.feature_extractor = CLIPImageProcessor.from_pretrained(FEATURE_EXTRACTOR)
WeightsDownloader.download_if_not_exists(SDXL_URL, SDXL_MODEL_CACHE)
print("Loading sdxl txt2img pipeline...")
self.txt2img_pipe = DiffusionPipeline.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
)
self.is_lora = False
if weights or os.path.exists("./trained-model"):
self.load_trained_weights(weights, self.txt2img_pipe)
self.txt2img_pipe.to("cuda")
print("Loading SDXL img2img pipeline...")
self.img2img_pipe = StableDiffusionXLImg2ImgPipeline(
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
)
self.img2img_pipe.to("cuda")
print("Loading SDXL inpaint pipeline...")
self.inpaint_pipe = StableDiffusionXLInpaintPipeline(
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
)
self.inpaint_pipe.to("cuda")
print("Loading SDXL refiner pipeline...")
# FIXME(ja): should the vae/text_encoder_2 be loaded from SDXL always?
# - in the case of fine-tuned SDXL should we still?
# FIXME(ja): if the answer to above is use VAE/Text_Encoder_2 from fine-tune
# what does this imply about lora + refiner? does the refiner need to know about
WeightsDownloader.download_if_not_exists(REFINER_URL, REFINER_MODEL_CACHE)
print("Loading refiner pipeline...")
self.refiner = DiffusionPipeline.from_pretrained(
REFINER_MODEL_CACHE,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
vae=self.txt2img_pipe.vae,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
)
self.refiner.to("cuda")
|
SDXL_MODEL_CACHE = "./sdxl-cache"
REFINER_MODEL_CACHE = "./refiner-cache"
SAFETY_CACHE = "./safety-cache"
FEATURE_EXTRACTOR = "./feature-extractor"
SDXL_URL = "https://weights.replicate.delivery/default/sdxl/sdxl-vae-upcast-fix.tar"
REFINER_URL = (
"https://weights.replicate.delivery/default/sdxl/refiner-no-vae-no-encoder-1.0.tar"
)
SAFETY_URL = "https://weights.replicate.delivery/default/sdxl/safety-1.0.tar"
class KarrasDPM:
def from_config(config):
return DPMSolverMultistepScheduler.from_config(config, use_karras_sigmas=True)
SCHEDULERS = {
"DDIM": DDIMScheduler,
"DPMSolverMultistep": DPMSolverMultistepScheduler,
"HeunDiscrete": HeunDiscreteScheduler,
"KarrasDPM": KarrasDPM,
"K_EULER_ANCESTRAL": EulerAncestralDiscreteScheduler,
"K_EULER": EulerDiscreteScheduler,
"PNDM": PNDMScheduler,
}
class Predictor(BasePredictor):
def load_trained_weights(self, weights, pipe):
self.weights_manager.load_trained_weights(weights, pipe)
def build_controlnet_pipeline(self, pipeline_class, controlnet_models):
pipe = pipeline_class.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
controlnet=self.controlnet.get_models(controlnet_models),
)
pipe.to("cuda")
return pipe
def setup(self, weights: Optional[Path] = None):
"""Load the model into memory to make running multiple predictions efficient"""
start = time.time()
self.sizing_strategy = SizingStrategy()
self.weights_manager = WeightsManager(self)
self.tuned_model = False
self.tuned_weights = None
if str(weights) == "weights":
weights = None
print("Loading safety checker...")
WeightsDownloader.download_if_not_exists(SAFETY_URL, SAFETY_CACHE)
self.safety_checker = StableDiffusionSafetyChecker.from_pretrained(
SAFETY_CACHE, torch_dtype=torch.float16
).to("cuda")
self.feature_extractor = CLIPImageProcessor.from_pretrained(FEATURE_EXTRACTOR)
WeightsDownloader.download_if_not_exists(SDXL_URL, SDXL_MODEL_CACHE)
print("Loading sdxl txt2img pipeline...")
self.txt2img_pipe = DiffusionPipeline.from_pretrained(
SDXL_MODEL_CACHE,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
)
self.is_lora = False
if weights or os.path.exists("./trained-model"):
self.load_trained_weights(weights, self.txt2img_pipe)
self.txt2img_pipe.to("cuda")
print("Loading SDXL img2img pipeline...")
self.img2img_pipe = StableDiffusionXLImg2ImgPipeline(
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
)
self.img2img_pipe.to("cuda")
print("Loading SDXL inpaint pipeline...")
self.inpaint_pipe = StableDiffusionXLInpaintPipeline(
vae=self.txt2img_pipe.vae,
text_encoder=self.txt2img_pipe.text_encoder,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
tokenizer=self.txt2img_pipe.tokenizer,
tokenizer_2=self.txt2img_pipe.tokenizer_2,
unet=self.txt2img_pipe.unet,
scheduler=self.txt2img_pipe.scheduler,
)
self.inpaint_pipe.to("cuda")
print("Loading SDXL refiner pipeline...")
# FIXME(ja): should the vae/text_encoder_2 be loaded from SDXL always?
# - in the case of fine-tuned SDXL should we still?
# FIXME(ja): if the answer to above is use VAE/Text_Encoder_2 from fine-tune
# what does this imply about lora + refiner? does the refiner need to know about
WeightsDownloader.download_if_not_exists(REFINER_URL, REFINER_MODEL_CACHE)
print("Loading refiner pipeline...")
self.refiner = DiffusionPipeline.from_pretrained(
REFINER_MODEL_CACHE,
text_encoder_2=self.txt2img_pipe.text_encoder_2,
vae=self.txt2img_pipe.vae,
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16",
)
self.refiner.to("cuda")
| self.controlnet = ControlNet(self) | 2 | 2023-11-13 13:04:41+00:00 | 8k |
ahayler/s4c | datasets/kitti_360/kitti_360_dataset.py | [
{
"identifier": "KITTI360Bbox3D",
"path": "datasets/kitti_360/annotation.py",
"snippet": "class KITTI360Bbox3D(KITTI360Object):\n # Constructor\n def __init__(self):\n KITTI360Object.__init__(self)\n # the polygon as list of points\n self.vertices = []\n self.faces = ... | import os
import time
import xml.etree.ElementTree as ET
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import yaml
import omegaconf
from collections import Counter, defaultdict
from pathlib import Path
from typing import Optional
from scipy.spatial.transform import Rotation
from torch.utils.data import Dataset
from torchvision.transforms import ColorJitter
from datasets.kitti_360.annotation import KITTI360Bbox3D
from utils.augmentation import get_color_aug_fn
from datasets.kitti_360.labels import labels | 5,122 | T_02_to_pose[:3, :] = np.reshape(cam_to_pose_data["image_02"], (3, 4))
T_03_to_pose[:3, :] = np.reshape(cam_to_pose_data["image_03"], (3, 4))
T_00_to_velo[:3, :] = np.reshape(cam_to_velo_data, (3, 4))
# Compute cam to pose transforms for rectified perspective cameras
T_rect_00_to_pose = T_00_to_pose @ np.linalg.inv(R_rect_00)
T_rect_01_to_pose = T_01_to_pose @ np.linalg.inv(R_rect_01)
# Compute cam to pose transform for fisheye cameras
T_02_to_pose = T_02_to_pose @ R_02
T_03_to_pose = T_03_to_pose @ R_03
# Compute velo to cameras and velo to pose transforms
T_velo_to_rect_00 = R_rect_00 @ np.linalg.inv(T_00_to_velo)
T_velo_to_pose = T_rect_00_to_pose @ T_velo_to_rect_00
T_velo_to_rect_01 = np.linalg.inv(T_rect_01_to_pose) @ T_velo_to_pose
# Calibration matrix is the same for both perspective cameras
K = P_rect_00[:3, :3]
# Normalize calibration
f_x = K[0, 0] / im_size_rect[1]
f_y = K[1, 1] / im_size_rect[0]
c_x = K[0, 2] / im_size_rect[1]
c_y = K[1, 2] / im_size_rect[0]
# Change to image coordinates [-1, 1]
K[0, 0] = f_x * 2.
K[1, 1] = f_y * 2.
K[0, 2] = c_x * 2. - 1
K[1, 2] = c_y * 2. - 1
# Convert fisheye calibration to [-1, 1] image dimensions
fisheye_02_data["projection_parameters"]["gamma1"] = (fisheye_02_data["projection_parameters"]["gamma1"] / im_size_fish[1]) * 2.
fisheye_02_data["projection_parameters"]["gamma2"] = (fisheye_02_data["projection_parameters"]["gamma2"] / im_size_fish[0]) * 2.
fisheye_02_data["projection_parameters"]["u0"] = (fisheye_02_data["projection_parameters"]["u0"] / im_size_fish[1]) * 2. - 1.
fisheye_02_data["projection_parameters"]["v0"] = (fisheye_02_data["projection_parameters"]["v0"] / im_size_fish[0]) * 2. - 1.
fisheye_03_data["projection_parameters"]["gamma1"] = (fisheye_03_data["projection_parameters"]["gamma1"] / im_size_fish[1]) * 2.
fisheye_03_data["projection_parameters"]["gamma2"] = (fisheye_03_data["projection_parameters"]["gamma2"] / im_size_fish[0]) * 2.
fisheye_03_data["projection_parameters"]["u0"] = (fisheye_03_data["projection_parameters"]["u0"] / im_size_fish[1]) * 2. - 1.
fisheye_03_data["projection_parameters"]["v0"] = (fisheye_03_data["projection_parameters"]["v0"] / im_size_fish[0]) * 2. - 1.
# Use same camera calibration as perspective cameras for resampling
# K_fisheye = np.eye(3, dtype=np.float32)
# K_fisheye[0, 0] = 2
# K_fisheye[1, 1] = 2
K_fisheye = K
calibs = {
"K_perspective": K,
"K_fisheye": K_fisheye,
"T_cam_to_pose": {
"00": T_rect_00_to_pose,
"01": T_rect_01_to_pose,
"02": T_02_to_pose,
"03": T_03_to_pose,
},
"T_velo_to_cam": {
"00": T_velo_to_rect_00,
"01": T_velo_to_rect_01,
},
"T_velo_to_pose": T_velo_to_pose,
"fisheye": {
"calib_02": fisheye_02_data,
"calib_03": fisheye_03_data,
"R_02": R_02[:3, :3],
"R_03": R_03[:3, :3]
},
"im_size": im_size_rect
}
return calibs
@staticmethod
def _get_resamplers(calibs, K_target, target_image_size):
resampler_02 = FisheyeToPinholeSampler(K_target, target_image_size, calibs["fisheye"]["calib_02"], calibs["fisheye"]["R_02"])
resampler_03 = FisheyeToPinholeSampler(K_target, target_image_size, calibs["fisheye"]["calib_03"], calibs["fisheye"]["R_03"])
return resampler_02, resampler_03
@staticmethod
def _load_poses(pose_path, sequences):
ids = {}
poses = {}
for seq in sequences:
pose_file = Path(pose_path) / seq / f"poses.txt"
try:
pose_data = np.loadtxt(pose_file)
except FileNotFoundError:
print(f'Ground truth poses are not avaialble for sequence {seq}.')
ids_seq = pose_data[:, 0].astype(int)
poses_seq = pose_data[:, 1:].astype(np.float32).reshape((-1, 3, 4))
poses_seq = np.concatenate((poses_seq, np.zeros_like(poses_seq[:, :1, :])), axis=1)
poses_seq[:, 3, 3] = 1
ids[seq] = ids_seq
poses[seq] = poses_seq
return ids, poses
@staticmethod
def _load_3d_bboxes(bbox_path, sequences):
bboxes = {}
for seq in sequences:
with open(Path(bbox_path) / f"{seq}.xml", "rb") as f:
tree = ET.parse(f)
root = tree.getroot()
objects = defaultdict(list)
num_bbox = 0
for child in root:
if child.find('transform') is None:
continue
|
name2label = {label.name: label for label in labels}
id2ProposedId = {label.id: label.trainId for label in labels}
PropsedId2TrainId = dict(enumerate(list(set(id2ProposedId.values()))))
PropsedId2TrainId = {v : k for k, v in PropsedId2TrainId.items()}
id2TrainId = {k : PropsedId2TrainId[v] for k, v in id2ProposedId.items()}
class FisheyeToPinholeSampler:
def __init__(self, K_target, target_image_size, calibs, rotation=None):
self._compute_transform(K_target, target_image_size, calibs, rotation)
def _compute_transform(self, K_target, target_image_size, calibs, rotation=None):
x = torch.linspace(-1, 1, target_image_size[1]).view(1, -1).expand(target_image_size)
y = torch.linspace(-1, 1, target_image_size[0]).view(-1, 1).expand(target_image_size)
z = torch.ones_like(x)
xyz = torch.stack((x, y, z), dim=-1).view(-1, 3)
# Unproject
xyz = (torch.inverse(torch.tensor(K_target)) @ xyz.T).T
if rotation is not None:
xyz = (torch.tensor(rotation) @ xyz.T).T
# Backproject into fisheye
xyz = xyz / torch.norm(xyz, dim=-1, keepdim=True)
x = xyz[:, 0]
y = xyz[:, 1]
z = xyz[:, 2]
xi_src = calibs["mirror_parameters"]["xi"]
x = x / (z + xi_src)
y = y / (z + xi_src)
k1 = calibs["distortion_parameters"]["k1"]
k2 = calibs["distortion_parameters"]["k2"]
r = x*x + y*y
factor = (1 + k1 * r + k2 * r * r)
x = x * factor
y = y * factor
gamma0 = calibs["projection_parameters"]["gamma1"]
gamma1 = calibs["projection_parameters"]["gamma2"]
u0 = calibs["projection_parameters"]["u0"]
v0 = calibs["projection_parameters"]["v0"]
x = x * gamma0 + u0
y = y * gamma1 + v0
xy = torch.stack((x, y), dim=-1).view(1, *target_image_size, 2)
self.sample_pts = xy
def resample(self, img):
img = img.unsqueeze(0)
resampled_img = F.grid_sample(img, self.sample_pts, align_corners=True).squeeze(0)
return resampled_img
class Kitti360Dataset(Dataset):
def __init__(self,
data_path: str,
pose_path: str,
split_path: Optional[str],
target_image_size=(192, 640),
return_stereo=False,
return_depth=False,
return_fisheye=True,
return_3d_bboxes=False,
return_segmentation=False,
segmentation_mode=None,
data_segmentation_path=None,
frame_count=2,
keyframe_offset=0,
dilation=1,
fisheye_rotation=0,
fisheye_offset=0,
eigen_depth=True,
color_aug=False,
is_preprocessed=False,
load_kitti_360_segmentation_gt=False,
constrain_to_datapoints=False,
additional_random_front_offset=False
):
self.data_path = data_path
self.data_segmentation_path = data_segmentation_path
self.pose_path = pose_path
self.split_path = split_path
self.target_image_size = target_image_size
self.return_stereo = return_stereo
self.return_fisheye = return_fisheye
self.return_depth = return_depth
self.return_3d_bboxes = return_3d_bboxes
self.return_segmentation = return_segmentation
self.segmentation_mode = segmentation_mode
self.frame_count = frame_count
self.dilation = dilation
self.fisheye_rotation = fisheye_rotation
self.fisheye_offset = fisheye_offset
self.keyframe_offset = keyframe_offset
self.eigen_depth = eigen_depth
self.color_aug = color_aug
self.is_preprocessed = is_preprocessed
self.load_kitti_360_segmentation_gt = load_kitti_360_segmentation_gt
self.constrain_to_datapoints = constrain_to_datapoints
if isinstance(self.fisheye_rotation, float) or isinstance(self.fisheye_rotation, int):
self.fisheye_rotation = (0, self.fisheye_rotation)
self.fisheye_rotation = tuple(self.fisheye_rotation)
# Support random fisheye offset
if type(self.fisheye_offset) == int:
self.random_fisheye_offset = False
self.fisheye_offset = (self.fisheye_offset, )
elif type(self.fisheye_offset) in [tuple, list, omegaconf.listconfig.ListConfig]:
self.random_fisheye_offset = True
self.fisheye_offset = tuple(sorted(self.fisheye_offset))
else:
raise ValueError(f"Invalid datatype for fisheye offset: {type(self.fisheye_offset)}")
if additional_random_front_offset and not self.random_fisheye_offset:
raise ValueError("Random Fisheye Offset needs to be active for additional random front offset!")
else:
self.additional_random_front_offset = additional_random_front_offset
self._sequences = self._get_sequences(self.data_path)
self._calibs = self._load_calibs(self.data_path, self.fisheye_rotation)
self._resampler_02, self._resampler_03 = self._get_resamplers(self._calibs, self._calibs["K_fisheye"], self.target_image_size)
self._img_ids, self._poses = self._load_poses(self.pose_path, self._sequences)
self._left_offset = ((self.frame_count - 1) // 2 + self.keyframe_offset) * self.dilation
self._perspective_folder = "data_rect" if not self.is_preprocessed else f"data_{self.target_image_size[0]}x{self.target_image_size[1]}"
self._segmentation_perspective_folder = "data_192x640"
self._segmentation_fisheye_folder = "data_192x640_0x-15"
self._fisheye_folder = "data_rgb" if not self.is_preprocessed else f"data_{self.target_image_size[0]}x{self.target_image_size[1]}_{self.fisheye_rotation[0]}x{self.fisheye_rotation[1]}"
if self.split_path is not None:
self._datapoints = self._load_split(self.split_path, self._img_ids)
elif self.return_segmentation:
self._datapoints = self._semantics_split(self._sequences, self.data_path, self._img_ids)
else:
self._datapoints = self._full_split(self._sequences, self._img_ids, self.check_file_integrity)
if self.return_3d_bboxes:
self._3d_bboxes = self._load_3d_bboxes(Path(data_path) / "data_3d_bboxes" / "train_full", self._sequences)
if self.segmentation_mode == 'KITTI-360' or self.load_kitti_360_segmentation_gt:
# Segmentations are only provided for the left camera
self._datapoints = [dp for dp in self._datapoints if not dp[2]]
# make sure we can load all segmentation masks
self._datapoints = [dp for dp in self._datapoints if self.check_segmentation(dp)]
if self.constrain_to_datapoints:
print("Using maximum datapoint as last image of sequence.")
seq_max_id = {seq: max([0] + [d[1] for d in self._datapoints if d[0] == seq]) for seq in self._sequences}
for seq in self._sequences:
self._poses[seq] = self._poses[seq][:seq_max_id[seq]+1]
self._img_ids[seq] = self._img_ids[seq][:seq_max_id[seq]+1]
self._skip = 0
self.length = len(self._datapoints)
def check_segmentation(self, dp):
"""Checks for a datapoint dp if we can load all the segmentation masks for all image_ids."""
sequence, id, is_right = dp
seq_len = self._img_ids[sequence].shape[0]
ids = [id] + [max(min(i, seq_len - 1), 0) for i in
range(id - self._left_offset, id - self._left_offset + self.frame_count * self.dilation,
self.dilation) if i != id]
img_ids = [self.get_img_id_from_id(sequence, id) for id in ids]
for img_id in img_ids:
_p = os.path.join(self.data_path, "data_2d_semantics", "train", sequence, "image_00", "semantic",
f"{img_id:010d}.png")
if not os.path.isfile(_p):
return False
return True
def check_file_integrity(self, seq, id):
dp = Path(self.data_path)
image_00 = dp / "data_2d_raw" / seq / "image_00" / self._perspective_folder
image_01 = dp / "data_2d_raw" / seq / "image_01" / self._perspective_folder
image_02 = dp / "data_2d_raw" / seq / "image_02" / self._fisheye_folder
image_03 = dp / "data_2d_raw" / seq / "image_03" / self._fisheye_folder
fisheye_offset = self.fisheye_offset[-1]
seq_len = self._img_ids[seq].shape[0]
ids = [id] + [max(min(i, seq_len - 1), 0) for i in range(id - self._left_offset, id - self._left_offset + self.frame_count * self.dilation, self.dilation) if i != id]
ids_fish = [max(min(id + fisheye_offset, seq_len - 1), 0)] + [max(min(i, seq_len - 1), 0) for i in range(id + fisheye_offset - self._left_offset, id + fisheye_offset - self._left_offset + self.frame_count * self.dilation, self.dilation) if i != id + fisheye_offset]
img_ids = [self.get_img_id_from_id(seq, id) for id in ids]
img_ids_fish = [self.get_img_id_from_id(seq, id) for id in ids_fish]
for img_id in img_ids:
if not ((image_00 / f"{img_id:010d}.png").exists() and (image_01 / f"{img_id:010d}.png").exists()):
return False
if self.return_fisheye:
for img_id in img_ids_fish:
if not ((image_02 / f"{img_id:010d}.png").exists() and (image_03 / f"{img_id:010d}.png").exists()):
return False
return True
@staticmethod
def _get_sequences(data_path):
all_sequences = []
seqs_path = Path(data_path) / "data_2d_raw"
for seq in seqs_path.iterdir():
if not seq.is_dir():
continue
all_sequences.append(seq.name)
return all_sequences
@staticmethod
def _full_split(sequences, img_ids, check_integrity):
datapoints = []
for seq in sorted(sequences):
ids = [id for id in range(len(img_ids[seq])) if check_integrity(seq, id)]
datapoints_seq = [(seq, id, False) for id in ids] + [(seq, id, True) for id in ids]
datapoints.extend(datapoints_seq)
return datapoints
@staticmethod
def _semantics_split(sequences, data_path, img_ids):
datapoints = []
for seq in sorted(sequences):
datapoints_seq = [(seq, id, False) for id in range(len(img_ids[seq]))]
datapoints_seq = [dp for dp in datapoints_seq if os.path.exists(os.path.join(data_path, "data_2d_semantics", "train", seq, "image_00", "semantic_rgb", f"{img_ids[seq][dp[1]]:010d}.png"))]
datapoints.extend(datapoints_seq)
return datapoints
@staticmethod
def _load_split(split_path, img_ids):
img_id2id = {seq: {id: i for i, id in enumerate(ids)} for seq, ids in img_ids.items()}
with open(split_path, "r") as f:
lines = f.readlines()
def split_line(l):
segments = l.split(" ")
seq = segments[0]
id = img_id2id[seq][int(segments[1])]
return seq, id, segments[2][0] == "r"
return list(map(split_line, lines))
@staticmethod
def _load_calibs(data_path, fisheye_rotation=0):
data_path = Path(data_path)
calib_folder = data_path / "calibration"
cam_to_pose_file = calib_folder / "calib_cam_to_pose.txt"
cam_to_velo_file = calib_folder / "calib_cam_to_velo.txt"
intrinsics_file = calib_folder / "perspective.txt"
fisheye_02_file = calib_folder / "image_02.yaml"
fisheye_03_file = calib_folder / "image_03.yaml"
cam_to_pose_data = {}
with open(cam_to_pose_file, 'r') as f:
for line in f.readlines():
key, value = line.split(':', 1)
try:
cam_to_pose_data[key] = np.array([float(x) for x in value.split()], dtype=np.float32)
except ValueError:
pass
cam_to_velo_data = None
with open(cam_to_velo_file, 'r') as f:
line = f.readline()
try:
cam_to_velo_data = np.array([float(x) for x in line.split()], dtype=np.float32)
except ValueError:
pass
intrinsics_data = {}
with open(intrinsics_file, 'r') as f:
for line in f.readlines():
key, value = line.split(':', 1)
try:
intrinsics_data[key] = np.array([float(x) for x in value.split()], dtype=np.float32)
except ValueError:
pass
with open(fisheye_02_file, 'r') as f:
f.readline() # Skips first line that defines the YAML version
fisheye_02_data = yaml.safe_load(f)
with open(fisheye_03_file, 'r') as f:
f.readline() # Skips first line that defines the YAML version
fisheye_03_data = yaml.safe_load(f)
im_size_rect = (int(intrinsics_data["S_rect_00"][1]), int(intrinsics_data["S_rect_00"][0]))
im_size_fish = (fisheye_02_data["image_height"], fisheye_02_data["image_width"])
# Projection matrices
# We use these projection matrices also when resampling the fisheye cameras.
# This makes downstream processing easier, but it could be done differently.
P_rect_00 = np.reshape(intrinsics_data['P_rect_00'], (3, 4))
P_rect_01 = np.reshape(intrinsics_data['P_rect_01'], (3, 4))
# Rotation matrices from raw to rectified -> Needs to be inverted later
R_rect_00 = np.eye(4, dtype=np.float32)
R_rect_01 = np.eye(4, dtype=np.float32)
R_rect_00[:3, :3] = np.reshape(intrinsics_data['R_rect_00'], (3, 3))
R_rect_01[:3, :3] = np.reshape(intrinsics_data['R_rect_01'], (3, 3))
# Rotation matrices from resampled fisheye to raw fisheye
fisheye_rotation = np.array(fisheye_rotation).reshape((1, 2))
R_02 = np.eye(4, dtype=np.float32)
R_03 = np.eye(4, dtype=np.float32)
R_02[:3, :3] = Rotation.from_euler("xy", fisheye_rotation[:, [1, 0]], degrees=True).as_matrix().astype(np.float32)
R_03[:3, :3] = Rotation.from_euler("xy", fisheye_rotation[:, [1, 0]] * np.array([[1, -1]]), degrees=True).as_matrix().astype(np.float32)
# Load cam to pose transforms
T_00_to_pose = np.eye(4, dtype=np.float32)
T_01_to_pose = np.eye(4, dtype=np.float32)
T_02_to_pose = np.eye(4, dtype=np.float32)
T_03_to_pose = np.eye(4, dtype=np.float32)
T_00_to_velo = np.eye(4, dtype=np.float32)
T_00_to_pose[:3, :] = np.reshape(cam_to_pose_data["image_00"], (3, 4))
T_01_to_pose[:3, :] = np.reshape(cam_to_pose_data["image_01"], (3, 4))
T_02_to_pose[:3, :] = np.reshape(cam_to_pose_data["image_02"], (3, 4))
T_03_to_pose[:3, :] = np.reshape(cam_to_pose_data["image_03"], (3, 4))
T_00_to_velo[:3, :] = np.reshape(cam_to_velo_data, (3, 4))
# Compute cam to pose transforms for rectified perspective cameras
T_rect_00_to_pose = T_00_to_pose @ np.linalg.inv(R_rect_00)
T_rect_01_to_pose = T_01_to_pose @ np.linalg.inv(R_rect_01)
# Compute cam to pose transform for fisheye cameras
T_02_to_pose = T_02_to_pose @ R_02
T_03_to_pose = T_03_to_pose @ R_03
# Compute velo to cameras and velo to pose transforms
T_velo_to_rect_00 = R_rect_00 @ np.linalg.inv(T_00_to_velo)
T_velo_to_pose = T_rect_00_to_pose @ T_velo_to_rect_00
T_velo_to_rect_01 = np.linalg.inv(T_rect_01_to_pose) @ T_velo_to_pose
# Calibration matrix is the same for both perspective cameras
K = P_rect_00[:3, :3]
# Normalize calibration
f_x = K[0, 0] / im_size_rect[1]
f_y = K[1, 1] / im_size_rect[0]
c_x = K[0, 2] / im_size_rect[1]
c_y = K[1, 2] / im_size_rect[0]
# Change to image coordinates [-1, 1]
K[0, 0] = f_x * 2.
K[1, 1] = f_y * 2.
K[0, 2] = c_x * 2. - 1
K[1, 2] = c_y * 2. - 1
# Convert fisheye calibration to [-1, 1] image dimensions
fisheye_02_data["projection_parameters"]["gamma1"] = (fisheye_02_data["projection_parameters"]["gamma1"] / im_size_fish[1]) * 2.
fisheye_02_data["projection_parameters"]["gamma2"] = (fisheye_02_data["projection_parameters"]["gamma2"] / im_size_fish[0]) * 2.
fisheye_02_data["projection_parameters"]["u0"] = (fisheye_02_data["projection_parameters"]["u0"] / im_size_fish[1]) * 2. - 1.
fisheye_02_data["projection_parameters"]["v0"] = (fisheye_02_data["projection_parameters"]["v0"] / im_size_fish[0]) * 2. - 1.
fisheye_03_data["projection_parameters"]["gamma1"] = (fisheye_03_data["projection_parameters"]["gamma1"] / im_size_fish[1]) * 2.
fisheye_03_data["projection_parameters"]["gamma2"] = (fisheye_03_data["projection_parameters"]["gamma2"] / im_size_fish[0]) * 2.
fisheye_03_data["projection_parameters"]["u0"] = (fisheye_03_data["projection_parameters"]["u0"] / im_size_fish[1]) * 2. - 1.
fisheye_03_data["projection_parameters"]["v0"] = (fisheye_03_data["projection_parameters"]["v0"] / im_size_fish[0]) * 2. - 1.
# Use same camera calibration as perspective cameras for resampling
# K_fisheye = np.eye(3, dtype=np.float32)
# K_fisheye[0, 0] = 2
# K_fisheye[1, 1] = 2
K_fisheye = K
calibs = {
"K_perspective": K,
"K_fisheye": K_fisheye,
"T_cam_to_pose": {
"00": T_rect_00_to_pose,
"01": T_rect_01_to_pose,
"02": T_02_to_pose,
"03": T_03_to_pose,
},
"T_velo_to_cam": {
"00": T_velo_to_rect_00,
"01": T_velo_to_rect_01,
},
"T_velo_to_pose": T_velo_to_pose,
"fisheye": {
"calib_02": fisheye_02_data,
"calib_03": fisheye_03_data,
"R_02": R_02[:3, :3],
"R_03": R_03[:3, :3]
},
"im_size": im_size_rect
}
return calibs
@staticmethod
def _get_resamplers(calibs, K_target, target_image_size):
resampler_02 = FisheyeToPinholeSampler(K_target, target_image_size, calibs["fisheye"]["calib_02"], calibs["fisheye"]["R_02"])
resampler_03 = FisheyeToPinholeSampler(K_target, target_image_size, calibs["fisheye"]["calib_03"], calibs["fisheye"]["R_03"])
return resampler_02, resampler_03
@staticmethod
def _load_poses(pose_path, sequences):
ids = {}
poses = {}
for seq in sequences:
pose_file = Path(pose_path) / seq / f"poses.txt"
try:
pose_data = np.loadtxt(pose_file)
except FileNotFoundError:
print(f'Ground truth poses are not avaialble for sequence {seq}.')
ids_seq = pose_data[:, 0].astype(int)
poses_seq = pose_data[:, 1:].astype(np.float32).reshape((-1, 3, 4))
poses_seq = np.concatenate((poses_seq, np.zeros_like(poses_seq[:, :1, :])), axis=1)
poses_seq[:, 3, 3] = 1
ids[seq] = ids_seq
poses[seq] = poses_seq
return ids, poses
@staticmethod
def _load_3d_bboxes(bbox_path, sequences):
bboxes = {}
for seq in sequences:
with open(Path(bbox_path) / f"{seq}.xml", "rb") as f:
tree = ET.parse(f)
root = tree.getroot()
objects = defaultdict(list)
num_bbox = 0
for child in root:
if child.find('transform') is None:
continue | obj = KITTI360Bbox3D() | 0 | 2023-11-12 21:53:27+00:00 | 8k |
pedramhaqiqi/LANPONG | lanpong/server/server.py | [
{
"identifier": "Game",
"path": "lanpong/game/game.py",
"snippet": "class Game:\n \"\"\"\n Game object for pong\n \"\"\"\n\n DEFAULT_ROWS = 24\n DEFAULT_COLS = 70\n STATS_HEIGHT = 3\n GAME_LENGTH = 3\n SCORE_DISPLAY_TIME = 2\n\n def __init__(\n self,\n rows=DEFAU... | import re
import socket
import threading
import time
import paramiko
import numpy as np
from itertools import count
from ..game.game import Game
from lanpong.server.ssh import SSHServer
from lanpong.server.ping import Ping
from lanpong.server.db import DB | 6,521 | ]
):
# Center each line.
start = (cols - len(line)) // 2
screen[current_row + i, start : len(line) + start] = list(line)
return Game.screen_to_tui(screen)
def wait_for_char(channel, channel_file, valid_chars):
"""
Waits for a character from the client that is in the valid_chars set.
"""
while not channel.closed:
char = channel_file.read(1).decode()
if char in valid_chars:
return char
class Server:
def __init__(self, key_file_name="test_key") -> None:
self.lock = threading.Lock()
self.db = DB()
self.server_key = paramiko.RSAKey.from_private_key_file(filename=key_file_name)
# Set of usernames of connected clients.
# Used to prevent multiple connections from the same user.
self.connections = set()
self.waiting_screen = get_message_screen(
f"You are player 1. Waiting for player 2..."
)
self.games = []
self.games_lock = threading.Lock()
def start_server(self, host="0.0.0.0", port=2222):
"""Starts an SSH server on specified port and address
Args:
host (str): Server host addr. Defaults to '0.0.0.0'.
port (int): Port. Defaults to 2222.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_sock:
# Bind socket to port and start listening for connections.
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind((host, port))
server_sock.listen(100)
print(f"Listening for connection on {host}:{port}")
# Accept multiple connections, thread-out
while True:
client_socket, client_addr = server_sock.accept()
print(f"Incoming connection from {client_addr[0]}:{client_addr[1]}")
client_thread = threading.Thread(
target=self.handle_client, args=(client_socket,)
)
client_thread.start()
def handle_game(self, game: Game):
"""
Handles the non-paddle game updates (mainly the ball)
"""
game.is_game_started_event.wait()
while game.loser == 0:
game.update_game()
time.sleep(0.05)
def handle_ping(self, game: Game, ping: Ping, name, player_id):
"""
Handles the ping updates
"""
game.is_game_started_event.wait()
while game.loser == 0:
game.update_network_stats(f"{name}'s PING: {ping.get():.3F}ms", player_id)
time.sleep(0.05)
def echo_line(self, channel_file, channel):
line = ""
while True:
char = channel_file.read(1).decode()
# Handle backspace (ASCII 8 or '\b' or '\x7F')
if char in {"\x08", "\b", "\x7F"}:
if line:
# Remove the last character from the line and move the cursor back
line = line[:-1]
elif char == "\r" or char == "\n":
break
else:
line += char
channel.sendall(char)
return line
def get_game_or_create(self, username):
"""
Returns a game that is not full, or creates a new one
Returns:
(Game, int): Game and player id
"""
with self.games_lock:
# Get a game that is not full, or None if all games are full.
game = next((g for g in self.games if not g.is_full()), None)
if game is None:
# No game available, create a new one.
game = Game()
self.games.append(game)
# Create a thread for this game and start it.
game_thread = threading.Thread(target=self.handle_game, args=(game,))
game_thread.start()
player_id = game.initialize_player(username)
return game, player_id
def handle_client(self, client_socket):
"""
Handles a client connection.
"""
try:
# Initialize the SSH server protocol for this connection.
transport = paramiko.Transport(client_socket)
|
CLEAR_SCREEN = "\x1b[H\x1b[J"
HIDE_CURSOR = "\033[?25l"
SHOW_CURSOR = "\033[?25h"
LOGO_ASCII = """\
_ ___ _ _ ______ _____ _ _ _____
| | / _ \ | \ | || ___ \ _ | \ | | __ \\
| | / /_\ \| \| || |_/ / | | | \| | | \/
| | | _ || . ` || __/| | | | . ` | | __
| |____| | | || |\ || | \ \_/ / |\ | |_\ \\
\_____/\_| |_/\_| \_/\_| \___/\_| \_/\____/""".splitlines()
def get_message_screen(message):
"""
Returns a screen with the message centered.
"""
screen = Game.get_blank_screen(stats_height=0)
rows, cols = screen.shape
assert len(message) < cols - 2
start = (cols - len(message)) // 2
screen[rows // 2, start : start + len(message)] = list(message)
return Game.screen_to_tui(screen)
def send_frame(channel, frame):
"""
Sends a frame to the client.
"""
return channel.sendall("".join([CLEAR_SCREEN, frame, HIDE_CURSOR]))
def get_lobby_screen(db, username=""):
"""
Returns the lobby screen with the leaderboard and options.
"""
screen = Game.get_blank_screen(stats_height=0)
rows, cols = screen.shape
assert len(LOGO_ASCII[0]) < cols - 2
start = (cols - len(LOGO_ASCII[0])) // 2
for i, line in enumerate(LOGO_ASCII):
# Center each line of the logo.
screen[1 + i, start : start + len(line)] = list(line)
current_row = 1 + len(LOGO_ASCII) + 1
for i, line in enumerate(
[f"Welcome to LAN PONG, {username}!", "Leaderboard:"]
+ [
f"{i + 1}. {user['username']} - {user['score']}"
for i, user in enumerate(db.get_top_users(10))
]
+ [
"",
"Press key to proceed:",
"[1] Matchmaking",
"[2] Public key configuration",
]
):
# Center each line.
start = (cols - len(line)) // 2
screen[current_row + i, start : len(line) + start] = list(line)
return Game.screen_to_tui(screen)
def wait_for_char(channel, channel_file, valid_chars):
"""
Waits for a character from the client that is in the valid_chars set.
"""
while not channel.closed:
char = channel_file.read(1).decode()
if char in valid_chars:
return char
class Server:
def __init__(self, key_file_name="test_key") -> None:
self.lock = threading.Lock()
self.db = DB()
self.server_key = paramiko.RSAKey.from_private_key_file(filename=key_file_name)
# Set of usernames of connected clients.
# Used to prevent multiple connections from the same user.
self.connections = set()
self.waiting_screen = get_message_screen(
f"You are player 1. Waiting for player 2..."
)
self.games = []
self.games_lock = threading.Lock()
def start_server(self, host="0.0.0.0", port=2222):
"""Starts an SSH server on specified port and address
Args:
host (str): Server host addr. Defaults to '0.0.0.0'.
port (int): Port. Defaults to 2222.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_sock:
# Bind socket to port and start listening for connections.
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind((host, port))
server_sock.listen(100)
print(f"Listening for connection on {host}:{port}")
# Accept multiple connections, thread-out
while True:
client_socket, client_addr = server_sock.accept()
print(f"Incoming connection from {client_addr[0]}:{client_addr[1]}")
client_thread = threading.Thread(
target=self.handle_client, args=(client_socket,)
)
client_thread.start()
def handle_game(self, game: Game):
"""
Handles the non-paddle game updates (mainly the ball)
"""
game.is_game_started_event.wait()
while game.loser == 0:
game.update_game()
time.sleep(0.05)
def handle_ping(self, game: Game, ping: Ping, name, player_id):
"""
Handles the ping updates
"""
game.is_game_started_event.wait()
while game.loser == 0:
game.update_network_stats(f"{name}'s PING: {ping.get():.3F}ms", player_id)
time.sleep(0.05)
def echo_line(self, channel_file, channel):
line = ""
while True:
char = channel_file.read(1).decode()
# Handle backspace (ASCII 8 or '\b' or '\x7F')
if char in {"\x08", "\b", "\x7F"}:
if line:
# Remove the last character from the line and move the cursor back
line = line[:-1]
elif char == "\r" or char == "\n":
break
else:
line += char
channel.sendall(char)
return line
def get_game_or_create(self, username):
"""
Returns a game that is not full, or creates a new one
Returns:
(Game, int): Game and player id
"""
with self.games_lock:
# Get a game that is not full, or None if all games are full.
game = next((g for g in self.games if not g.is_full()), None)
if game is None:
# No game available, create a new one.
game = Game()
self.games.append(game)
# Create a thread for this game and start it.
game_thread = threading.Thread(target=self.handle_game, args=(game,))
game_thread.start()
player_id = game.initialize_player(username)
return game, player_id
def handle_client(self, client_socket):
"""
Handles a client connection.
"""
try:
# Initialize the SSH server protocol for this connection.
transport = paramiko.Transport(client_socket) | ssh_server = SSHServer(self) | 1 | 2023-11-13 04:32:20+00:00 | 8k |
maagic6/SDIMV | SDIMV.py | [
{
"identifier": "imageProcess",
"path": "image.py",
"snippet": "class imageProcess:\n def __init__(self, fn):\n ft = filetype.guess(fn)\n self.data = {\"prompt\": \"\", \n \"negative_prompt\": \"\", \n \"steps\": \"\", \n \"sample... | import sys, subprocess, qdarkstyle
from PyQt6.QtWidgets import (
QApplication,
QFrame,
QGraphicsPixmapItem,
QGraphicsScene,
QGraphicsView,
QGridLayout,
QLabel,
QLineEdit,
QMenu,
QToolBar,
QVBoxLayout,
QHBoxLayout,
QWidget,
QPushButton,
QScrollArea,
QDockWidget,
QMessageBox,
)
from PyQt6.QtGui import QIcon, QAction, QFont, QPainter, QMovie, QPixmap, QDesktopServices
from PyQt6.QtCore import Qt, QRectF, QEvent, QUrl, QSettings, QSystemSemaphore, QSharedMemory
from PyQt6.QtMultimedia import QMediaPlayer
from PyQt6.QtMultimediaWidgets import QGraphicsVideoItem
from pathlib import Path
from qframelesswindow import FramelessMainWindow
from image import imageProcess
from file_handler import FileHandler
from custom_widgets import CustomDockWidget, CustomLineEdit, CustomTextEdit, CustomListWidget, CustomTitleBar, ZoomableGraphicsView
from icon import resource_path
from about_dialog import AboutDialog | 5,467 |
class MainWindow(FramelessMainWindow):
def __init__(self):
super().__init__()
self.fileHandler = FileHandler(self)
#window size
self.setTitleBar(CustomTitleBar(self))
self.setWindowTitle('SDIMV')
self.titleBar.raise_()
self.settings = QSettings("maagic6", "SDIMV")
savedGeometry = self.settings.value("main_window_geometry")
if savedGeometry is not None:
self.restoreGeometry(savedGeometry)
else:
self.resize(720,720)
qr = self.frameGeometry()
cp = self.screen().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
iconPath = resource_path("icon/icon.ico")
self.setWindowIcon(QIcon(iconPath))
toolbar = QToolBar("Toolbar")
toolbar.setStyleSheet("QToolBar {background: transparent;}"
"QToolButton {background: transparent; border: none;}"
"QToolButton:hover {background: rgba(195, 195, 255, 50);}")
iconPath2 = resource_path("icon/add.png")
iconPath3 = resource_path("icon/remove.png")
iconPath4 = resource_path("icon/clear.png")
iconPath5 = resource_path("icon/about.png")
addAction = QAction(QIcon(iconPath2), "Add", self)
addAction.triggered.connect(self.fileHandler.openFileDialog)
removeAction = QAction(QIcon(iconPath3), "Remove", self)
removeAction.triggered.connect(self.fileHandler.removeSelectedItem)
clearAction = QAction(QIcon(iconPath4), "Clear", self)
clearAction.triggered.connect(self.fileHandler.clearFileList)
aboutAction = QAction(QIcon(iconPath5), "About", self)
aboutAction.triggered.connect(self.showAboutDialog)
toolbar.addAction(addAction)
toolbar.addAction(removeAction)
toolbar.addAction(clearAction)
toolbar.addAction(aboutAction)
toolbar.setObjectName("Toolbar")
self.addToolBar(toolbar)
self.imagePreviewFrame = QFrame()
self.imagePreviewFrame.setFrameShape(QFrame.Shape.Box)
self.imagePreviewFrame.setLineWidth(1)
self.imagePreviewFrame.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.imageFrame = QVBoxLayout()
self.imagePreviewFrame.setLayout(self.imageFrame)
self.imageScene = QGraphicsScene()
self.imageView = ZoomableGraphicsView(self.imageScene)
self.imageView.setRenderHint(QPainter.RenderHint.Antialiasing, True)
self.imageView.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
self.imageView.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.imageFrame.addWidget(self.imageView)
|
class MainWindow(FramelessMainWindow):
def __init__(self):
super().__init__()
self.fileHandler = FileHandler(self)
#window size
self.setTitleBar(CustomTitleBar(self))
self.setWindowTitle('SDIMV')
self.titleBar.raise_()
self.settings = QSettings("maagic6", "SDIMV")
savedGeometry = self.settings.value("main_window_geometry")
if savedGeometry is not None:
self.restoreGeometry(savedGeometry)
else:
self.resize(720,720)
qr = self.frameGeometry()
cp = self.screen().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
iconPath = resource_path("icon/icon.ico")
self.setWindowIcon(QIcon(iconPath))
toolbar = QToolBar("Toolbar")
toolbar.setStyleSheet("QToolBar {background: transparent;}"
"QToolButton {background: transparent; border: none;}"
"QToolButton:hover {background: rgba(195, 195, 255, 50);}")
iconPath2 = resource_path("icon/add.png")
iconPath3 = resource_path("icon/remove.png")
iconPath4 = resource_path("icon/clear.png")
iconPath5 = resource_path("icon/about.png")
addAction = QAction(QIcon(iconPath2), "Add", self)
addAction.triggered.connect(self.fileHandler.openFileDialog)
removeAction = QAction(QIcon(iconPath3), "Remove", self)
removeAction.triggered.connect(self.fileHandler.removeSelectedItem)
clearAction = QAction(QIcon(iconPath4), "Clear", self)
clearAction.triggered.connect(self.fileHandler.clearFileList)
aboutAction = QAction(QIcon(iconPath5), "About", self)
aboutAction.triggered.connect(self.showAboutDialog)
toolbar.addAction(addAction)
toolbar.addAction(removeAction)
toolbar.addAction(clearAction)
toolbar.addAction(aboutAction)
toolbar.setObjectName("Toolbar")
self.addToolBar(toolbar)
self.imagePreviewFrame = QFrame()
self.imagePreviewFrame.setFrameShape(QFrame.Shape.Box)
self.imagePreviewFrame.setLineWidth(1)
self.imagePreviewFrame.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.imageFrame = QVBoxLayout()
self.imagePreviewFrame.setLayout(self.imageFrame)
self.imageScene = QGraphicsScene()
self.imageView = ZoomableGraphicsView(self.imageScene)
self.imageView.setRenderHint(QPainter.RenderHint.Antialiasing, True)
self.imageView.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
self.imageView.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.imageFrame.addWidget(self.imageView)
| self.fileList = CustomListWidget() | 5 | 2023-11-15 19:51:29+00:00 | 8k |
TimbreWatermarking/TimbreWatermarking | watermarking_model/model/conv2_mel_rewm_modules.py | [
{
"identifier": "FCBlock",
"path": "watermarking_model/model/blocks.py",
"snippet": "class FCBlock(nn.Module):\n \"\"\" Fully Connected Block \"\"\"\n\n def __init__(self, in_features, out_features, activation=None, bias=False, dropout=None, spectral_norm=False):\n super(FCBlock, self).__in... | from base64 import encode
from torch.nn import LeakyReLU, Tanh
from .blocks import FCBlock, PositionalEncoding, Mish, Conv1DBlock, Conv2Encoder, WatermarkEmbedder, WatermarkExtracter, ReluBlock
from distortions.frequency import TacotronSTFT, fixed_STFT, tacotron_mel
from distortions.dl import distortion
import torch
import torch.nn as nn
import pdb
import hifigan
import json
import torchaudio
import numpy as np
import os
import librosa
import librosa.display
import matplotlib.pyplot as plt
import os
import matplotlib.pyplot as plt
import librosa
import numpy as np
import librosa.display | 4,069 | y = self.stft.inverse(carrier_wateramrked.squeeze(1), phase.squeeze(1))
return y, carrier_wateramrked
def test_forward(self, x, msg, weight):
num_samples = x.shape[2]
spect, phase = self.stft.transform(x)
carrier_encoded = self.ENc(spect.unsqueeze(1))
watermark_encoded = self.msg_linear_in(msg).transpose(1,2).unsqueeze(1).repeat(1,1,1,carrier_encoded.shape[3])
concatenated_feature = torch.cat((carrier_encoded, spect.unsqueeze(1), weight*watermark_encoded), dim=1)
carrier_wateramrked = self.EM(concatenated_feature)
self.stft.num_samples = num_samples
y = self.stft.inverse(carrier_wateramrked.squeeze(1), phase.squeeze(1))
return y, carrier_wateramrked
def save_forward(self, x, msg):
num_samples = x.shape[2]
spect, phase = self.stft.transform(x)
# save spectrum
save_spectrum(spect, phase, 'linear')
carrier_encoded = self.ENc(spect.unsqueeze(1))
# save feature_map
save_feature_map(carrier_encoded[0])
watermark_encoded = self.msg_linear_in(msg).transpose(1,2).unsqueeze(1).repeat(1,1,1,carrier_encoded.shape[3])
concatenated_feature = torch.cat((carrier_encoded, spect.unsqueeze(1), watermark_encoded), dim=1)
carrier_wateramrked = self.EM(concatenated_feature)
self.stft.num_samples = num_samples
y = self.stft.inverse(carrier_wateramrked.squeeze(1), phase.squeeze(1))
return y, carrier_wateramrked
class Decoder(nn.Module):
def __init__(self, process_config, model_config, msg_length, win_dim, embedding_dim, nlayers_decoder=6, transformer_drop=0.1, attention_heads=8):
super(Decoder, self).__init__()
self.robust = model_config["robust"]
if self.robust:
self.dl = distortion()
self.mel_transform = TacotronSTFT(filter_length=process_config["mel"]["n_fft"], hop_length=process_config["mel"]["hop_length"], win_length=process_config["mel"]["win_length"])
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.vocoder_step = model_config["structure"]["vocoder_step"]
win_dim = int((process_config["mel"]["n_fft"] / 2) + 1)
self.block = model_config["conv2"]["block"]
self.EX = WatermarkExtracter(input_channel=1, hidden_dim=model_config["conv2"]["hidden_dim"], block=self.block)
self.stft = fixed_STFT(process_config["mel"]["n_fft"], process_config["mel"]["hop_length"], process_config["mel"]["win_length"])
self.msg_linear_out = FCBlock(win_dim, msg_length)
self.weight_linear = FCBlock(win_dim, 1)
def forward(self, y, global_step):
# print(y.shape)
# import pdb
# pdb.set_trace()
y_identity = y.clone()
if global_step > self.vocoder_step:
y_mel = self.mel_transform.mel_spectrogram(y.squeeze(1))
# y = self.vocoder(y_mel)
y_d = (self.mel_transform.griffin_lim(magnitudes=y_mel)).unsqueeze(1)
else:
y_d = y
if self.robust:
y_d_d = self.dl(y_d, self.robust)
else:
y_d_d = y_d
# print(f"dl:{y.shape}")
spect, phase = self.stft.transform(y_d_d)
# pdb.set_trace()
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
spect_identity, phase_identity = self.stft.transform(y_identity)
extracted_wm_identity = self.EX(spect_identity.unsqueeze(1)).squeeze(1)
msg_identity = torch.mean(extracted_wm_identity,dim=2, keepdim=True).transpose(1,2)
msg_identity = self.msg_linear_out(msg_identity)
return msg, msg_identity
def get_weight(self, y):
y_identity = y
spect_identity, phase_identity = self.stft.transform(y_identity)
extracted_wm_identity = self.EX(spect_identity.unsqueeze(1)).squeeze(1)
msg_identity = torch.mean(extracted_wm_identity,dim=2, keepdim=True).transpose(1,2)
weight = self.weight_linear(msg_identity)
return weight
def test_forward(self, y):
spect, phase = self.stft.transform(y)
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
return msg
def save_forward(self, y):
# save mel_spectrum
y_mel = self.mel_transform.mel_spectrogram(y.squeeze(1))
save_spectrum(y_mel, y_mel, 'mel')
y = (self.mel_transform.griffin_lim(magnitudes=y_mel)).unsqueeze(1)
spect, phase = self.stft.transform(y)
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
return msg
def mel_test_forward(self, spect):
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
return msg
class Discriminator(nn.Module):
def __init__(self, process_config):
super(Discriminator, self).__init__()
self.conv = nn.Sequential(
|
def save_spectrum(spect, phase, flag='linear'):
root = "draw_figure"
spec = librosa.amplitude_to_db(spect.squeeze(0).cpu().numpy(), ref=np.max)
img=librosa.display.specshow(spec, sr=22050, x_axis='time', y_axis='log', y_coords=None);
plt.axis('off')
plt.savefig(os.path.join(root, flag + '_amplitude_spectrogram.png'), bbox_inches='tight', pad_inches=0.0)
spec = librosa.amplitude_to_db(phase.squeeze(0).cpu().numpy(), ref=np.max)
img=librosa.display.specshow(spec, sr=22050, x_axis='time', y_axis='log');
plt.axis('off')
plt.savefig(os.path.join(root, flag + '_phase_spectrogram.png'), bbox_inches='tight', pad_inches=0.0)
def save_feature_map(feature_maps):
feature_maps = feature_maps.cpu().numpy()
root = "draw_figure"
output_folder = os.path.join(root,"feature_map_or")
if not os.path.exists(output_folder):
os.makedirs(output_folder)
n_channels = feature_maps.shape[0]
for channel_idx in range(n_channels):
fig, ax = plt.subplots()
ax.imshow(feature_maps[channel_idx, :, :], cmap='gray')
ax.axis('off')
output_file = os.path.join(output_folder, f'feature_map_channel_{channel_idx + 1}.png')
plt.savefig(output_file, bbox_inches='tight', pad_inches=0.0)
plt.close(fig)
def get_vocoder(device):
with open("hifigan/config.json", "r") as f:
config = json.load(f)
config = hifigan.AttrDict(config)
vocoder = hifigan.Generator(config)
ckpt = torch.load("./hifigan/model/VCTK_V1/generator_v1")
vocoder.load_state_dict(ckpt["generator"])
vocoder.eval()
vocoder.remove_weight_norm()
vocoder.to(device)
freeze_model_and_submodules(vocoder)
return vocoder
def freeze_model_and_submodules(model):
for param in model.parameters():
param.requires_grad = False
for module in model.children():
if isinstance(module, nn.Module):
freeze_model_and_submodules(module)
class Encoder(nn.Module):
def __init__(self, process_config, model_config, msg_length, win_dim, embedding_dim, nlayers_encoder=6, transformer_drop=0.1, attention_heads=8):
super(Encoder, self).__init__()
self.name = "conv2"
win_dim = int((process_config["mel"]["n_fft"] / 2) + 1)
self.add_carrier_noise = False
self.block = model_config["conv2"]["block"]
self.layers_CE = model_config["conv2"]["layers_CE"]
self.EM_input_dim = model_config["conv2"]["hidden_dim"] + 2
self.layers_EM = model_config["conv2"]["layers_EM"]
self.vocoder_step = model_config["structure"]["vocoder_step"]
#MLP for the input wm
self.msg_linear_in = FCBlock(msg_length, win_dim, activation=LeakyReLU(inplace=True))
#stft transform
self.stft = fixed_STFT(process_config["mel"]["n_fft"], process_config["mel"]["hop_length"], process_config["mel"]["win_length"])
self.ENc = Conv2Encoder(input_channel=1, hidden_dim = model_config["conv2"]["hidden_dim"], block=self.block, n_layers=self.layers_CE)
self.EM = WatermarkEmbedder(input_channel=self.EM_input_dim, hidden_dim = model_config["conv2"]["hidden_dim"], block=self.block, n_layers=self.layers_EM)
def forward(self, x, msg, weight, global_step):
num_samples = x.shape[2]
spect, phase = self.stft.transform(x)
carrier_encoded = self.ENc(spect.unsqueeze(1))
watermark_encoded = self.msg_linear_in(msg).transpose(1,2).unsqueeze(1).repeat(1,1,1,carrier_encoded.shape[3])
concatenated_feature = torch.cat((carrier_encoded, spect.unsqueeze(1), weight*watermark_encoded), dim=1)
carrier_wateramrked = self.EM(concatenated_feature)
self.stft.num_samples = num_samples
y = self.stft.inverse(carrier_wateramrked.squeeze(1), phase.squeeze(1))
return y, carrier_wateramrked
def test_forward(self, x, msg, weight):
num_samples = x.shape[2]
spect, phase = self.stft.transform(x)
carrier_encoded = self.ENc(spect.unsqueeze(1))
watermark_encoded = self.msg_linear_in(msg).transpose(1,2).unsqueeze(1).repeat(1,1,1,carrier_encoded.shape[3])
concatenated_feature = torch.cat((carrier_encoded, spect.unsqueeze(1), weight*watermark_encoded), dim=1)
carrier_wateramrked = self.EM(concatenated_feature)
self.stft.num_samples = num_samples
y = self.stft.inverse(carrier_wateramrked.squeeze(1), phase.squeeze(1))
return y, carrier_wateramrked
def save_forward(self, x, msg):
num_samples = x.shape[2]
spect, phase = self.stft.transform(x)
# save spectrum
save_spectrum(spect, phase, 'linear')
carrier_encoded = self.ENc(spect.unsqueeze(1))
# save feature_map
save_feature_map(carrier_encoded[0])
watermark_encoded = self.msg_linear_in(msg).transpose(1,2).unsqueeze(1).repeat(1,1,1,carrier_encoded.shape[3])
concatenated_feature = torch.cat((carrier_encoded, spect.unsqueeze(1), watermark_encoded), dim=1)
carrier_wateramrked = self.EM(concatenated_feature)
self.stft.num_samples = num_samples
y = self.stft.inverse(carrier_wateramrked.squeeze(1), phase.squeeze(1))
return y, carrier_wateramrked
class Decoder(nn.Module):
def __init__(self, process_config, model_config, msg_length, win_dim, embedding_dim, nlayers_decoder=6, transformer_drop=0.1, attention_heads=8):
super(Decoder, self).__init__()
self.robust = model_config["robust"]
if self.robust:
self.dl = distortion()
self.mel_transform = TacotronSTFT(filter_length=process_config["mel"]["n_fft"], hop_length=process_config["mel"]["hop_length"], win_length=process_config["mel"]["win_length"])
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.vocoder_step = model_config["structure"]["vocoder_step"]
win_dim = int((process_config["mel"]["n_fft"] / 2) + 1)
self.block = model_config["conv2"]["block"]
self.EX = WatermarkExtracter(input_channel=1, hidden_dim=model_config["conv2"]["hidden_dim"], block=self.block)
self.stft = fixed_STFT(process_config["mel"]["n_fft"], process_config["mel"]["hop_length"], process_config["mel"]["win_length"])
self.msg_linear_out = FCBlock(win_dim, msg_length)
self.weight_linear = FCBlock(win_dim, 1)
def forward(self, y, global_step):
# print(y.shape)
# import pdb
# pdb.set_trace()
y_identity = y.clone()
if global_step > self.vocoder_step:
y_mel = self.mel_transform.mel_spectrogram(y.squeeze(1))
# y = self.vocoder(y_mel)
y_d = (self.mel_transform.griffin_lim(magnitudes=y_mel)).unsqueeze(1)
else:
y_d = y
if self.robust:
y_d_d = self.dl(y_d, self.robust)
else:
y_d_d = y_d
# print(f"dl:{y.shape}")
spect, phase = self.stft.transform(y_d_d)
# pdb.set_trace()
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
spect_identity, phase_identity = self.stft.transform(y_identity)
extracted_wm_identity = self.EX(spect_identity.unsqueeze(1)).squeeze(1)
msg_identity = torch.mean(extracted_wm_identity,dim=2, keepdim=True).transpose(1,2)
msg_identity = self.msg_linear_out(msg_identity)
return msg, msg_identity
def get_weight(self, y):
y_identity = y
spect_identity, phase_identity = self.stft.transform(y_identity)
extracted_wm_identity = self.EX(spect_identity.unsqueeze(1)).squeeze(1)
msg_identity = torch.mean(extracted_wm_identity,dim=2, keepdim=True).transpose(1,2)
weight = self.weight_linear(msg_identity)
return weight
def test_forward(self, y):
spect, phase = self.stft.transform(y)
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
return msg
def save_forward(self, y):
# save mel_spectrum
y_mel = self.mel_transform.mel_spectrogram(y.squeeze(1))
save_spectrum(y_mel, y_mel, 'mel')
y = (self.mel_transform.griffin_lim(magnitudes=y_mel)).unsqueeze(1)
spect, phase = self.stft.transform(y)
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
return msg
def mel_test_forward(self, spect):
extracted_wm = self.EX(spect.unsqueeze(1)).squeeze(1)
msg = torch.mean(extracted_wm,dim=2, keepdim=True).transpose(1,2)
msg = self.msg_linear_out(msg)
return msg
class Discriminator(nn.Module):
def __init__(self, process_config):
super(Discriminator, self).__init__()
self.conv = nn.Sequential( | ReluBlock(1,16,3,1,1), | 7 | 2023-11-13 01:40:03+00:00 | 8k |
nillion-oss/tinysig | src/tinysig/tecdsa.py | [
{
"identifier": "add",
"path": "src/tinysig/utils.py",
"snippet": "def add(values: list[int], size: int) -> int:\ndef add_ec(points: list[EccPoint]) -> int:\ndef generate_additive_shares(secret: int, n: int, size: int) -> list[int]:\ndef multiply(values: list[int], size: int) -> int:\ndef egcd(a: int, p... | from Crypto.Hash import SHA256
from phe import paillier
from typing import List
from .utils import add, add_ec, multiply, rand, egcd, verify_dsa_signature, verify_ecdsa_signature
from .setup import DSASetup, ECDSASetup
from .network import Network, Client | 4,641 | result = scalar * ec_point
# DB management
node.set_open(result, label_result)
def encrypt_and_delete_exp_sh_local(self, label: str, client_id: int) -> None:
"""
Encrypt the share of the exponent element of the LAMBDA pair and delete the original
LAMBDA pair.
Parameters:
label (str): The label for LAMBDA pair.
client_id (int): Client id.
Returns:
None
"""
for node in self.nodes:
# DB management
clear_share = node.get_share(label+"_lambda_sh_exp")
# Local operation:
## Encrypt share
enc_sh_val = node.he_public_keys[client_id - 1].encrypt(clear_share)
## Delete lambda pair
node.delete_share(label+"_lambda_sh_exp")
node.delete_share(label+"_lambda_sh_base")
# DB management
sh_label = label+"_enc_sh_exp"
node.set_share(enc_sh_val, sh_label)
def send_public_key_to_client(self, label: str, client: Client) -> None:
"""
Nodes send public key to client.
Parameters:
label (str): The label for LAMBDA pair.
client_id (int): Client id.
Returns:
None
"""
all_y = [node.get_open(label+"_pk") for node in self.nodes]
# Check if all elements in the list are equal
are_all_equal = all(y == all_y[0] for y in all_y)
if are_all_equal:
client.set_open(all_y[0], label+"_pk")
else:
raise PublicKeyDisagreement("Abort.")
def distributed_key_generation_protocol(self, client_id: int, label=None) -> None:
"""
Execute a distributed key generation protocol for a specific client.
Parameters:
client_id (int): The unique identifier for the client.
label (str, optional): A custom label associated with the client. Defaults to None.
Returns:
None
"""
# Check there exist a client
client = next((client for client in self.clients if client.id == client_id), None)
if client == None:
raise TypeError(f"Client with id {client_id} is not part of the network.")
label = str(client_id)+"th_client_"+str(label) if label else str(client_id)+"th_client_"+"x"
delete = not self.debug
# Step 1
self.get_lambda([label])
# Step 2
self.key_agreement_protocol(label, delete=delete)
# Step 3
self.send_public_key_to_client(label, client)
# Step 4
self.encrypt_and_delete_exp_sh_local(label, client_id)
def compute_r_local(self, label: str, client: Client, delete=True) -> None:
"""
Compute r.
Parameters:
label (str): The label of the r element.
client (Client): A client.
Returns:
None
"""
for node in self.nodes:
# DB management
R = node.get_open(label + "_pk")
# Local operation
r = R % self.q if self.setup == DSASetup else int(R.x)
# DB management
node.set_open(r, label + "_r")
node.delete_open(label + "_pk")
client.set_open(r, label + "_r")
def invert_masked_factor_local(self, label) -> None:
"""
Invert a masked factor.
Parameters:
label (str): The label of the masked factor to be inverted.
Returns:
None
"""
for node in self.nodes:
# DB management
masked_factor = node.get_open(label+"_sk")
share = node.get_share(label+"_lambda_sh_exp")
# Local operation
## Invert masked factor
|
class ThresholdSignature(Network):
clients: List[Client]
def __init__(self, N, C, setup=None, debug=False):
self.debug = debug
if setup is None:
self.dsa = DSASetup.generate_dsa_setup()
self.setup = DSASetup
super().__init__(N, self.dsa.q, self.dsa.h)
elif type(setup) == DSASetup:
self.dsa = setup
self.setup = DSASetup
super().__init__(N, self.dsa.q, self.dsa.h)
elif type(setup) == ECDSASetup:
self.ecdsa = setup.generate_ecdsa_setup()
self.setup = ECDSASetup
super().__init__(N, self.ecdsa.q, self.ecdsa.h)
else:
raise TypeError("Invalid type provided. "
"Please use either 'DSASetup' or 'ECDSASetup' types."
)
# Generate public and private keys for the paillier homomorphic encryption scheme
for i in range(C):
pub_key, priv_key = paillier.generate_paillier_keypair()
self.clients[i].he_private_key = priv_key
for node in self.nodes:
node.he_public_keys[i] = pub_key
for client in self.clients:
client.he_public_keys[i] = pub_key
def get_lambda(self, labels: list[str]) -> None:
"""
Emulates the generation of LAMBDA pairs :math:`([h^{\gamma}], [\gamma])` between all nodes.
Parameters:
labels (list[str]): A list of labels for which lambda values will be generated
and stored.
Returns:
None
"""
n = len(labels)
h = self.h
q = self.q
q_minus_one = q - 1
for l in range(n):
# Locally generate lambda
alpha = rand(q_minus_one)
h_alpha = pow(h, alpha, q)
self.share(alpha, q_minus_one, labels[l]+"_lambda_sh_exp")
self.share(h_alpha, q, labels[l]+"_lambda_sh_base")
def rss_protocol(self, size: int, label: str) -> None:
"""
Random Secret Sharing (RSS) Protocol.
This function implements a one-round RSS protocol. The goal is to share a random
secret value among a group of nodes using a specific label for the shares.
Parameters:
size (int): The maximum size of the random secret to be generated and shared.
label (str): A label to identify the shared secrets and their associated operations.
Returns:
None
"""
# Round 1
for node in self.nodes:
# Step 1: locally generate random secret
random_element = rand(size)
# Step 2: share random secret with all nodes
self.share(random_element, size, label+"sh_node_"+str(node.id))
# All local
for node in self.nodes:
# DB management
list_of_shares = [
node.get_share(label + "sh_node_" + str(other_node.id))
for other_node in self.nodes
]
# Step 3: add locally all shares
random_sum = add(list_of_shares, size)
# DB management
sh_label = label+"_sh_exp"
node.set_share(random_sum, sh_label)
if not self.debug:
[node.delete_share(label + "sh_node_" + str(other_node.id))
for other_node in self.nodes]
def pow_share_protocol(self, base_type: str, get_label: str, save_label: str) -> None:
"""
Compute a power-sharing protocol among a group of nodes.
This function implements a one-round protocol to securely compute :math:`b^{s}` where
the exponent is a secret shared element between the nodes.
Parameters:
base_type (str): The type of base used: 'exp', when base to be used is self.h;
'base', when the base to be used is self.dsa.g. Note: 'base'
option can only be use for the DSA setup.
get_label (str): The label to retrieve shares of 's' from nodes.
save_label (str): The label to save the final result to.
Returns:
None
"""
if base_type not in ["exp", "base"]:
raise ValueError("{} is not one of the specified base types.\
Please choose one of the following:\n \
['exp', 'base']".format(base_type))
prime = self.q if base_type == "exp" else self.dsa.p
# Round 1
for node in self.nodes:
# DB management
exponent = node.get_share(get_label+"_sh_"+base_type)
# Step 1: compute base^share
if base_type == "exp":
h_exp = pow(self.h, exponent, prime)
else:
h_exp = pow(self.dsa.g, exponent, prime)
# Step 2: Broadcast base^share to nodes
self.broadcast(h_exp, "pow_share_node_"+str(node.id))
# All local
for node in self.nodes:
# DB management
base_exps = [
node.get_open("pow_share_node_"+str(other_node.id))
for other_node in self.nodes
]
# Step 3: multiply locally all powers of shares
val = multiply(base_exps, prime)
# DB management
node.set_open(val, save_label)
if not self.debug:
[node.delete_open("pow_share_node_"+str(other_node.id))
for other_node in self.nodes]
def ec_pow_share_protocol(self, get_label: str, save_label: str) -> None:
"""
Execute an elliptic curve (EC) version of power-sharing protocol.
This function implements a one-round protocol to securely compute
:math:`scalar\cdot G` where the scalar is a secret shared element between the nodes.
Parameters:
get_label (str): The label used to retrieve scalar shares from nodes.
save_label (str): The label used to save the result of the power-sharing protocol.
Returns:
None
"""
# Round 1
for node in self.nodes:
# DB management
scalar_sh = node.get_share(get_label+"_sh_base")
# Step 1:
sh_G = scalar_sh * self.ecdsa.G
# Step 2:
self.broadcast(sh_G, "ec_pow_share_node_"+str(node.id))
# All local
for node in self.nodes:
# DB management
base_exps = [
node.get_open("ec_pow_share_node_"+str(other_node.id))
for other_node in self.nodes
]
# Step 3: add locally all point shares
val = add_ec(base_exps)
# DB management
node.set_open(val, save_label)
if not self.debug:
[node.delete_open("ec_pow_share_node_"+str(other_node.id))
for other_node in self.nodes]
def subtract_exp_shares_local(self, label_a: str, label_b: str, label_r: str) -> None:
"""
Subtract the shares of the exponent of two labels and store the result in another label.
Parameters:
label_a (str): The label for the first operand.
label_b (str): The label for the second operand.
label_r (str): The label where the result is stored.
Returns:
None
"""
q_minus_one = self.q - 1
for node in self.nodes:
# DB management
share_a = node.get_share(label_a+"_sh_exp")
share_b = node.get_share(label_b+"_sh_exp")
# Local operation: subtraction
share_r = (share_a - share_b) % q_minus_one
# DB management
label = label_r+"_sh_exp"
node.set_share(share_r, label)
def pow_local(self, label_base: str, label_exponent: str, label_result: str) -> None:
"""
Compute the power of a base saved in open database raised to an exponent and store the result.
Parameters:
label_base (str): The label for the base.
label_exponent (str): The label for the exponent.
label_result (str): The label for the element where the result is stored.
Returns:
None
"""
for node in self.nodes:
# DB management
base = node.get_open(label_base)
exponent = node.get_open(label_exponent)
# Local operation: power
result = pow(base, exponent, self.dsa.p)
# DB management
node.set_open(result, label_result)
def key_agreement_protocol(self, label: str, delete=True) -> None:
"""
Perform a key agreement protocol to derive a mask of the secret key and the
corresponding public key.
Parameters:
label (str): The label of the pair associated with the secret key mask.
delete (bool, optional): Whether to delete intermediate data after the protocol.
Defaults to True.
Returns:
None
"""
q_minus_one = self.q - 1
# Round 1
# Step 1:
random_label = "random"
self.rss_protocol(q_minus_one, random_label)
# Round 2
# Step 2:
random_minus_label = random_label + "_minus_" + label
self.subtract_exp_shares_local(random_label, label + "_lambda", random_minus_label)
base_type_exp = "exp"
self.pow_share_protocol(base_type_exp, random_minus_label, label + "_sk")
if self.setup == DSASetup:
# Step 3:
base_type_base = "base"
self.pow_share_protocol(base_type_base, label + "_lambda", label + "_pre_pk")
# Step 4:
self.pow_local(label + "_pre_pk", label + "_sk", label + "_pk")
else:
# Step 3:
self.ec_pow_share_protocol(label + "_lambda", label + "_pre_pk")
# Step 4:
self.ec_mult_local(label + "_pre_pk", label + "_sk", label + "_pk")
# DB management
## Option only for testing purposes
if delete:
[node.delete_share(random_minus_label+"_sh_exp") for node in self.nodes]
[node.delete_share(random_label+"_sh_exp") for node in self.nodes]
[node.delete_open(label + "_pre_pk") for node in self.nodes]
def ec_mult_local(self, label_ec_point: str, label_scalar: str, label_result: str) -> None:
"""
Compute the multiplication of a scalar value with an elliptic point curve
and store the result.
Parameters:
label_ec_point (str): The label for the elliptic curve point.
label_scalar (str): The label for the scalar.
label_result (str): The label for the element where the result is stored.
Returns:
None
"""
for node in self.nodes:
# DB management
ec_point = node.get_open(label_ec_point)
scalar = node.get_open(label_scalar)
# Local operation: mult
result = scalar * ec_point
# DB management
node.set_open(result, label_result)
def encrypt_and_delete_exp_sh_local(self, label: str, client_id: int) -> None:
"""
Encrypt the share of the exponent element of the LAMBDA pair and delete the original
LAMBDA pair.
Parameters:
label (str): The label for LAMBDA pair.
client_id (int): Client id.
Returns:
None
"""
for node in self.nodes:
# DB management
clear_share = node.get_share(label+"_lambda_sh_exp")
# Local operation:
## Encrypt share
enc_sh_val = node.he_public_keys[client_id - 1].encrypt(clear_share)
## Delete lambda pair
node.delete_share(label+"_lambda_sh_exp")
node.delete_share(label+"_lambda_sh_base")
# DB management
sh_label = label+"_enc_sh_exp"
node.set_share(enc_sh_val, sh_label)
def send_public_key_to_client(self, label: str, client: Client) -> None:
"""
Nodes send public key to client.
Parameters:
label (str): The label for LAMBDA pair.
client_id (int): Client id.
Returns:
None
"""
all_y = [node.get_open(label+"_pk") for node in self.nodes]
# Check if all elements in the list are equal
are_all_equal = all(y == all_y[0] for y in all_y)
if are_all_equal:
client.set_open(all_y[0], label+"_pk")
else:
raise PublicKeyDisagreement("Abort.")
def distributed_key_generation_protocol(self, client_id: int, label=None) -> None:
"""
Execute a distributed key generation protocol for a specific client.
Parameters:
client_id (int): The unique identifier for the client.
label (str, optional): A custom label associated with the client. Defaults to None.
Returns:
None
"""
# Check there exist a client
client = next((client for client in self.clients if client.id == client_id), None)
if client == None:
raise TypeError(f"Client with id {client_id} is not part of the network.")
label = str(client_id)+"th_client_"+str(label) if label else str(client_id)+"th_client_"+"x"
delete = not self.debug
# Step 1
self.get_lambda([label])
# Step 2
self.key_agreement_protocol(label, delete=delete)
# Step 3
self.send_public_key_to_client(label, client)
# Step 4
self.encrypt_and_delete_exp_sh_local(label, client_id)
def compute_r_local(self, label: str, client: Client, delete=True) -> None:
"""
Compute r.
Parameters:
label (str): The label of the r element.
client (Client): A client.
Returns:
None
"""
for node in self.nodes:
# DB management
R = node.get_open(label + "_pk")
# Local operation
r = R % self.q if self.setup == DSASetup else int(R.x)
# DB management
node.set_open(r, label + "_r")
node.delete_open(label + "_pk")
client.set_open(r, label + "_r")
def invert_masked_factor_local(self, label) -> None:
"""
Invert a masked factor.
Parameters:
label (str): The label of the masked factor to be inverted.
Returns:
None
"""
for node in self.nodes:
# DB management
masked_factor = node.get_open(label+"_sk")
share = node.get_share(label+"_lambda_sh_exp")
# Local operation
## Invert masked factor | inv_masked_factor = egcd(masked_factor, self.q) | 0 | 2023-11-14 13:55:41+00:00 | 8k |
Exscientia/physicsml | src/physicsml/models/mace/modules/blocks.py | [
{
"identifier": "Activation",
"path": "src/physicsml/models/mace/modules/_activation.py",
"snippet": "class Activation(torch.nn.Module):\n r\"\"\"Scalar activation function.\n\n Odd scalar inputs require activation functions with a defined parity (odd or even).\n\n Parameters\n ----------\n ... | from typing import Optional
from e3nn import nn, o3
from torch_geometric.utils.scatter import scatter
from ._activation import Activation
from .irreps_tools import reshape_irreps, tp_out_irreps_with_instructions
from .radial import BesselBasis, PolynomialCutoff
from .symmetric_contraction import SymmetricContraction
import torch | 3,849 |
class RadialEmbeddingBlock(torch.nn.Module):
def __init__(
self,
r_max: float,
num_bessel: int,
num_polynomial_cutoff: int,
) -> None:
super().__init__()
self.bessel_fn = BesselBasis(r_max=r_max, num_basis=num_bessel)
self.cutoff_fn = PolynomialCutoff(r_max=r_max, p=num_polynomial_cutoff)
self.out_dim = num_bessel
def forward(
self,
edge_lengths: torch.Tensor, # [n_edges, 1]
) -> torch.Tensor:
bessel = self.bessel_fn(edge_lengths) # [n_edges, n_basis]
cutoff = self.cutoff_fn(edge_lengths) # [n_edges, 1]
output: torch.Tensor = bessel * cutoff # [n_edges, n_basis]
return output
class NodeUpdateBlock(torch.nn.Module):
def __init__(
self,
node_attrs_irreps: o3.Irreps,
node_feats_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
residual_connection: bool,
) -> None:
super().__init__()
# net to compute W m_i
self.linear = o3.Linear(
hidden_irreps,
hidden_irreps,
internal_weights=True,
shared_weights=True,
)
if residual_connection:
# residual connection from original node attrs and node features
self.residual_connection_layer = o3.FullyConnectedTensorProduct(
node_feats_irreps,
node_attrs_irreps,
hidden_irreps,
)
else:
self.residual_connection_layer = None
def forward(
self,
m_i: torch.Tensor,
node_feats: torch.Tensor,
node_attrs: torch.Tensor,
) -> torch.Tensor:
if self.residual_connection_layer is not None:
node_feats = self.linear(m_i) + self.residual_connection_layer(
node_feats,
node_attrs,
)
else:
node_feats = self.linear(m_i)
return node_feats
class MessageBlock(torch.nn.Module):
def __init__(
self,
interaction_irreps: o3.Irreps,
node_attrs_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
correlation: int,
) -> None:
super().__init__()
# symmetric contraction to make A_i into messages m_i = W B_i
self.symmetric_contractions = SymmetricContraction(
irreps_in=interaction_irreps,
irreps_out=hidden_irreps,
correlation=correlation,
num_elements=node_attrs_irreps.dim,
)
def forward(self, a_i: torch.Tensor, node_attrs: torch.Tensor) -> torch.Tensor:
# contract the A_i's with element dependent weights and generalised CG coefs to get m_i = W B_i
m_i: torch.Tensor = self.symmetric_contractions(a_i, node_attrs)
return m_i
class InteractionBlock(torch.nn.Module):
def __init__(
self,
node_feats_irreps: o3.Irreps,
node_attrs_irreps: o3.Irreps,
edge_attrs_irreps: o3.Irreps,
edge_feats_irreps: o3.Irreps,
interaction_irreps: o3.Irreps,
avg_num_neighbours: float,
mix_with_node_attrs: bool = False,
) -> None:
super().__init__()
self.avg_num_neighbours = avg_num_neighbours
self.linear_node_feats = o3.Linear(
node_feats_irreps,
node_feats_irreps,
internal_weights=True,
shared_weights=True,
)
# TensorProduct
# find the only possible results from the tensor prod of node feats with edge attrs into targets
# only do the tensor prod for these possibilities
|
class NonLinearReadoutBlock(torch.nn.Module):
def __init__(
self,
irreps_in: o3.Irreps,
MLP_irreps: o3.Irreps,
irreps_out: o3.Irreps,
) -> None:
super().__init__()
self.linear_1 = o3.Linear(irreps_in=irreps_in, irreps_out=MLP_irreps)
self.non_linearity = Activation(irreps_in=MLP_irreps, acts=[torch.nn.SiLU()])
self.linear_2 = o3.Linear(irreps_in=MLP_irreps, irreps_out=irreps_out)
def forward(self, x: torch.Tensor) -> torch.Tensor: # [n_nodes, irreps] # [..., ]
x = self.linear_1(x)
x = self.non_linearity(x)
x = self.linear_2(x)
return x
class RadialEmbeddingBlock(torch.nn.Module):
def __init__(
self,
r_max: float,
num_bessel: int,
num_polynomial_cutoff: int,
) -> None:
super().__init__()
self.bessel_fn = BesselBasis(r_max=r_max, num_basis=num_bessel)
self.cutoff_fn = PolynomialCutoff(r_max=r_max, p=num_polynomial_cutoff)
self.out_dim = num_bessel
def forward(
self,
edge_lengths: torch.Tensor, # [n_edges, 1]
) -> torch.Tensor:
bessel = self.bessel_fn(edge_lengths) # [n_edges, n_basis]
cutoff = self.cutoff_fn(edge_lengths) # [n_edges, 1]
output: torch.Tensor = bessel * cutoff # [n_edges, n_basis]
return output
class NodeUpdateBlock(torch.nn.Module):
def __init__(
self,
node_attrs_irreps: o3.Irreps,
node_feats_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
residual_connection: bool,
) -> None:
super().__init__()
# net to compute W m_i
self.linear = o3.Linear(
hidden_irreps,
hidden_irreps,
internal_weights=True,
shared_weights=True,
)
if residual_connection:
# residual connection from original node attrs and node features
self.residual_connection_layer = o3.FullyConnectedTensorProduct(
node_feats_irreps,
node_attrs_irreps,
hidden_irreps,
)
else:
self.residual_connection_layer = None
def forward(
self,
m_i: torch.Tensor,
node_feats: torch.Tensor,
node_attrs: torch.Tensor,
) -> torch.Tensor:
if self.residual_connection_layer is not None:
node_feats = self.linear(m_i) + self.residual_connection_layer(
node_feats,
node_attrs,
)
else:
node_feats = self.linear(m_i)
return node_feats
class MessageBlock(torch.nn.Module):
def __init__(
self,
interaction_irreps: o3.Irreps,
node_attrs_irreps: o3.Irreps,
hidden_irreps: o3.Irreps,
correlation: int,
) -> None:
super().__init__()
# symmetric contraction to make A_i into messages m_i = W B_i
self.symmetric_contractions = SymmetricContraction(
irreps_in=interaction_irreps,
irreps_out=hidden_irreps,
correlation=correlation,
num_elements=node_attrs_irreps.dim,
)
def forward(self, a_i: torch.Tensor, node_attrs: torch.Tensor) -> torch.Tensor:
# contract the A_i's with element dependent weights and generalised CG coefs to get m_i = W B_i
m_i: torch.Tensor = self.symmetric_contractions(a_i, node_attrs)
return m_i
class InteractionBlock(torch.nn.Module):
def __init__(
self,
node_feats_irreps: o3.Irreps,
node_attrs_irreps: o3.Irreps,
edge_attrs_irreps: o3.Irreps,
edge_feats_irreps: o3.Irreps,
interaction_irreps: o3.Irreps,
avg_num_neighbours: float,
mix_with_node_attrs: bool = False,
) -> None:
super().__init__()
self.avg_num_neighbours = avg_num_neighbours
self.linear_node_feats = o3.Linear(
node_feats_irreps,
node_feats_irreps,
internal_weights=True,
shared_weights=True,
)
# TensorProduct
# find the only possible results from the tensor prod of node feats with edge attrs into targets
# only do the tensor prod for these possibilities
| tp_out_irreps, instructions = tp_out_irreps_with_instructions( | 2 | 2023-11-10 13:54:53+00:00 | 8k |
naver-ai/scob | model/decoders/transformer_decoder.py | [
{
"identifier": "BaseDecoder",
"path": "model/decoders/base.py",
"snippet": "class BaseDecoder(nn.Module, metaclass=abc.ABCMeta):\n downstream_evaluator = DownstreamEvaluator()\n\n @abc.abstractmethod\n def get_step_out_dict(\n self,\n batch,\n batch_idx,\n loader_id... | from collections import defaultdict
from asian_bart import AsianBartForCausalLM
from Levenshtein import distance
from overrides import overrides
from transformers import AutoConfig, AutoModelForCausalLM
from model.decoders.base import BaseDecoder
from model.losses import WeightLoss, get_loss
from model.model_utils import get_tokenizer
from utils.constants import COMMON_SPECIAL_TOKENS, DecoderTypes, HeadTypes, Tasks
from utils.misc import get_file, is_otor
import torch
import torch.nn as nn
import torch.nn.functional as F
import transformers | 4,339 | reg_outputs = self.reg_head(decoder_outputs.hidden_states[-1])
block_quads = dec_batch["block_quads"][:, 1:].contiguous()
block_first_tokens = dec_batch["block_first_tokens"][:, 1:].contiguous()
loc_loss = self.loc_loss_2head_func(reg_outputs, block_quads)
loc_loss = loc_loss.mean(-1)
loc_loss = loc_loss * block_first_tokens
loc_loss = loc_loss.sum(1) / block_first_tokens.sum(1)
# To avoid NaN loss
loc_loss = torch.nan_to_num(loc_loss, nan=0.0, posinf=0.0, neginf=0.0)
loc_loss = self.weight_loss(dec_batch, loc_loss).mean()
return loc_loss
def get_decoder_hidden_states(self, decoder_outputs):
decoder_hidden_states = []
for token_idx, all_layers_hidden_states in enumerate(
decoder_outputs.hidden_states[:-1]
):
if token_idx == 0:
decoder_hidden_states.append(
all_layers_hidden_states[-1][:, -1, :].unsqueeze(1).contiguous()
)
else:
decoder_hidden_states.append(all_layers_hidden_states[-1].contiguous())
if len(decoder_hidden_states) == 0:
return 0
decoder_hidden_states = torch.cat(decoder_hidden_states, 1)
return decoder_hidden_states
def get_pr_loc_outputs(self, dec_batch, decoder_outputs, reg_outputs):
bsz = reg_outputs.shape[0]
pr_loc_outputs = [[] for _ in range(bsz)]
for example_idx, sequence in enumerate(decoder_outputs.sequences):
task_name = dec_batch["task_names"][example_idx]
target_block_token_id = self.target_block_token_id_dict[task_name]
is_target_block_token_indices = (
sequence[:-1][dec_batch["max_end_prompt_token_idx"] + 1 :]
== target_block_token_id
)
pr_loc_outputs[example_idx] = reg_outputs[
example_idx, is_target_block_token_indices, :
]
return pr_loc_outputs
def get_pr_confs(self, dec_batch, decoder_outputs):
logits = torch.stack(decoder_outputs.scores).permute(1, 0, 2).contiguous()
probs = nn.functional.softmax(logits, -1).cpu().numpy()
pr_confs = []
for example_idx, sequence in enumerate(decoder_outputs.sequences):
task_name = dec_batch["task_names"][example_idx]
target_block_start_token_id = self.target_block_start_token_id_dict[
task_name
]
target_block_token_id = self.target_block_token_id_dict[task_name]
wo_prompt_seq = sequence[
torch.nonzero(sequence == self.end_prompt_token_id) + 1 :
]
seq_pr_confs = []
token_probs = []
for token_idx, token_id in enumerate(wo_prompt_seq):
if task_name == "object_detection":
if token_id == target_block_token_id:
seq_pr_confs.append(
probs[example_idx, token_idx - 1].max()
) # cls confidence
# seq_pr_confs.append(probs[example_idx, token_idx-5:token_idx-1].max(1).mean()) # box confidence mean
else:
if token_id == target_block_start_token_id: # [START_TEXT_BLOCK]
token_probs.clear()
elif token_id == target_block_token_id: # [END_TEXT_BLOCK]
# Since pr_reg_outputs is generated on every [END_TEXT_BLOCK]
if len(token_probs) == 0:
block_prob = 0.0
else:
block_prob = sum(token_probs) / len(token_probs)
seq_pr_confs.append(block_prob)
token_probs.clear()
else:
token_probs.append(probs[example_idx, token_idx, token_id])
pr_confs.append(seq_pr_confs)
return pr_confs
def __get_reg_head(self, n_loc_head_hidden_layers):
# https://github.com/facebookresearch/detr/blob/main/models/detr.py#L38
# https://github.com/facebookresearch/detr/blob/091a817eca74b8b97e35e4531c1c39f89fbe38eb/models/detr.py#L289
reg_heads = []
hidden_dim = self.model.config.hidden_size
for _ in range(n_loc_head_hidden_layers):
reg_heads.extend([nn.Linear(hidden_dim, hidden_dim), nn.ReLU()])
reg_heads.append(nn.Linear(hidden_dim, 8))
return nn.Sequential(*reg_heads)
def prepare_inputs_for_inference(
self, input_ids, past=None, attention_mask=None, use_cache=None, **model_kwargs
):
input_shape = input_ids.shape
if attention_mask is None:
attention_mask = input_ids.new_ones(input_shape)
if past is not None:
input_ids = input_ids[:, -1:]
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"past_key_values": past,
"use_cache": use_cache,
"encoder_hidden_states": model_kwargs["encoder_hidden_states"],
}
def _add_special_tokens(self, dataset_items):
special_tokens = []
for dataset_item in dataset_items:
| """
SCOB
Copyright (c) 2023-present NAVER Cloud Corp.
MIT license
"""
class TransformerDecoder(BaseDecoder):
def __init__(self, cfg, decoder_cfg, decoder_name):
super().__init__()
self.cfg = cfg
self.decoder_cfg = decoder_cfg
self.decoder_name = decoder_name
self.model = _get_huggingface_decoder(decoder_cfg)
if self.decoder_cfg.kwargs.n_prune_layers > 0:
_prune_decoder_layers(self.model, self.decoder_cfg)
self.tokenizer = get_tokenizer(
decoder_cfg.huggingface_path,
decoder_cfg.kwargs.tokenizer_name,
self.decoder_name,
cfg.model.resume_model_path,
cfg.model.w_pretrained_model_path,
decoder_cfg.kwargs.tokenizer_path,
)
self.decoder_max_length = decoder_cfg.kwargs.decoder_max_length
self._add_special_tokens(cfg.dataset_items)
self.end_prompt_token = "[END_PROMPT]"
self.end_prompt_token_id = self.tokenizer.convert_tokens_to_ids(
self.end_prompt_token
)
self.decoder_end_token = "[END]"
self.end_token_id = self.tokenizer.convert_tokens_to_ids(self.decoder_end_token)
self.target_block_start_token_id_dict = {
Tasks.OCR_READ: self.tokenizer.convert_tokens_to_ids("[START_BOX]"),
Tasks.OCR_READ_2HEAD: self.tokenizer.convert_tokens_to_ids(
"[START_TEXT_BLOCK]"
),
Tasks.OCR_READ_TEXTINSTANCEPADDING: self.tokenizer.convert_tokens_to_ids(
"[START_BOX]"
),
Tasks.OTOR: self.tokenizer.convert_tokens_to_ids("[START_BOX]"),
Tasks.OTOR_ORACLE: self.tokenizer.convert_tokens_to_ids("[START_BOX]"),
}
self.target_block_token_id_dict = {
Tasks.OCR_READ: self.tokenizer.convert_tokens_to_ids("[END_BOX]"),
Tasks.OCR_READ_TEXTINSTANCEPADDING: self.tokenizer.convert_tokens_to_ids(
"[END_BOX]"
),
Tasks.OCR_READ_2HEAD: self.tokenizer.convert_tokens_to_ids(
"[END_TEXT_BLOCK]"
),
Tasks.OTOR: self.tokenizer.convert_tokens_to_ids("[END_BOX]"),
Tasks.OTOR_ORACLE: self.tokenizer.convert_tokens_to_ids("[END_BOX]"),
}
self.model.resize_token_embeddings(len(self.tokenizer))
self.model.prepare_inputs_for_generation = self.prepare_inputs_for_inference
self.weight_loss = WeightLoss(cfg.dataset_items)
self.loss_func = get_loss(decoder_cfg.loss_func)
self.ignore_index = -100
self.calc_val_loss = decoder_cfg.calc_val_loss
self.calc_confidence = decoder_cfg.calc_confidence
self.connector_size = self.model.config.hidden_size
if decoder_cfg.head_type == HeadTypes.TWO_HEAD:
self.loc_loss_2head_func = get_loss(decoder_cfg.loc_loss_2head_func)
self.reg_head = self.__get_reg_head(
decoder_cfg.kwargs.n_loc_head_hidden_layers
)
if decoder_cfg.scob.use:
self.projector_q = self._get_projector(decoder_cfg.scob.project_dim)
self.projector_k = self._get_projector(decoder_cfg.scob.project_dim)
self.otor_scale_factor = decoder_cfg.scob.loss_weight
def _get_projector(self, output_dim):
hidden_size = self.model.config.hidden_size
projection_head = nn.Sequential(
nn.Linear(hidden_size, hidden_size),
nn.ReLU(True),
nn.Linear(hidden_size, output_dim),
)
return projection_head
@overrides
def forward(self, dec_batch, connector_out, enc_kwargs):
if self.training:
output_dict, losses_dict, kwargs = self.train_forward(
dec_batch, connector_out
)
else:
output_dict, losses_dict, kwargs = self.valtest_forward(
dec_batch, connector_out
)
return output_dict, losses_dict, kwargs
def train_forward(self, dec_batch, connector_out):
input_ids = dec_batch["input_ids"]
attention_mask = dec_batch["attention_mask"]
labels = dec_batch["labels"]
if is_otor(dec_batch["task_names"][0], oracle=True):
input_ids = torch.cat((input_ids, dec_batch["origin_input_ids"]), 0)
attention_mask = torch.cat((attention_mask, attention_mask), 0)
labels = torch.cat((labels, dec_batch["origin_labels"]), 0)
elif is_otor(dec_batch["task_names"][0]):
input_ids = torch.cat((input_ids, dec_batch["origin_input_ids"]), 0)
attention_mask = torch.cat((attention_mask, attention_mask), 0)
labels = torch.cat((labels, labels), 0)
input_ids = input_ids[:, :-1].contiguous()
attention_mask = attention_mask[:, :-1].contiguous()
labels = labels[:, 1:].contiguous()
decoder_outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
encoder_hidden_states=connector_out,
# labels=labels, # comment out to get per-example loss
output_hidden_states=True,
)
projection = None
if self.decoder_cfg.scob.use:
bsz = decoder_outputs.hidden_states[-1].shape[0]
projection = torch.cat(
[
self.projector_q(decoder_outputs.hidden_states[-1][: int(bsz / 2)]),
self.projector_k(decoder_outputs.hidden_states[-1][int(bsz / 2) :]),
],
dim=0,
)
pr_sequences = None # Not used in Train phase
token_loss = self.get_per_example_loss(
dec_batch, decoder_outputs.logits, labels, projection
)
supcon_loss = 0
if (
is_otor(dec_batch["task_names"][0], or_oracle=True)
and self.decoder_cfg.scob.use
):
supcon_loss = token_loss["supcon_loss"]
token_loss = token_loss["token_loss"]
aux_loss = 0
if self.decoder_cfg.aux_loss:
aux_loss = self.get_per_example_aux_loss(
dec_batch, decoder_outputs.hidden_states[1:-1], labels
)
if self.do_2head_regression(dec_batch):
loc_loss = self.get_per_example_2head_loc_loss(dec_batch, decoder_outputs)
else:
loc_loss = 0
token_loss *= self.decoder_cfg.token_loss_weight
loc_loss *= self.decoder_cfg.loc_loss_weight
decoder_loss = token_loss + loc_loss + aux_loss + supcon_loss
output_dict = {
"pr_sequences": pr_sequences,
"pr_loc_outputs": None, # Not used in Train phase
"pr_confs": None, # Not used in Train phase
}
losses_dict = {
"decoder_token_loss": token_loss,
"decoder_aux_loss": aux_loss,
"decoder_supcon_loss": supcon_loss,
"decoder_loc_loss": loc_loss,
"decoder_loss": decoder_loss,
}
kwargs = {}
return output_dict, losses_dict, kwargs
def do_2head_regression(self, dec_batch):
do_reg = False
if self.decoder_cfg.head_type == HeadTypes.TWO_HEAD and (
"block_quads" in dec_batch or "od_block_quads" in dec_batch
):
do_reg = True
return do_reg
def valtest_forward(self, dec_batch, connector_out):
input_ids = dec_batch["input_ids"]
if is_otor(dec_batch["task_names"][0], or_oracle=True):
bsz, _, _ = connector_out.size()
connector_out = connector_out[: int(bsz / 2)]
bsz = input_ids.shape[0]
do_reg = self.do_2head_regression(dec_batch)
# https://github.com/huggingface/transformers/blob/master/src/transformers/generation_utils.py#L640
decoder_outputs = self.model.generate(
input_ids=input_ids[:, : dec_batch["max_end_prompt_token_idx"] + 1],
encoder_hidden_states=connector_out,
max_length=self.decoder_max_length + 1,
num_beams=1,
early_stopping=False if self.calc_val_loss else True,
use_cache=True,
eos_token_id=self.end_token_id,
return_dict_in_generate=True,
output_scores=True,
output_hidden_states=do_reg,
forced_eos_token_id=False,
)
if self.decoder_cfg.kwargs.tokenizer_name.startswith("char_"):
pr_sequences = []
for pr_idx in range(decoder_outputs.sequences.shape[0]):
pr_sequence = "".join(
self.tokenizer.convert_ids_to_tokens(
decoder_outputs.sequences[pr_idx, :-1]
)
)
pr_sequences.append(pr_sequence)
else:
pr_sequences = self.tokenizer.batch_decode(
decoder_outputs.sequences[:, :-1]
)
if self.calc_val_loss:
scores = torch.stack(decoder_outputs.scores).permute(1, 0, 2).contiguous()
scores = scores[:, :-1, :].contiguous()
labels = dec_batch["labels"][
:, dec_batch["max_end_prompt_token_idx"] + 1 :
].contiguous()
decoder_token_loss = self.get_per_example_loss(dec_batch, scores, labels)
else:
decoder_token_loss = 0 # dummy value
if do_reg:
decoder_hidden_states = self.get_decoder_hidden_states(decoder_outputs)
if torch.is_tensor(decoder_hidden_states):
reg_outputs = self.reg_head(decoder_hidden_states)
pr_loc_outputs = self.get_pr_loc_outputs(
dec_batch, decoder_outputs, reg_outputs
)
else:
pr_loc_outputs = [[] for _ in range(bsz)]
if self.calc_val_loss:
decoder_loc_loss = 0 # Not implemented yet
else:
decoder_loc_loss = 0 # dummy value
else:
pr_loc_outputs = [[] for _ in range(bsz)]
decoder_loc_loss = 0
if self.calc_confidence:
pr_confs = self.get_pr_confs(dec_batch, decoder_outputs)
else:
pr_confs = [[] for _ in range(bsz)]
decoder_token_loss *= self.decoder_cfg.token_loss_weight
decoder_loc_loss *= self.decoder_cfg.loc_loss_weight
decoder_loss = decoder_token_loss + decoder_loc_loss
output_dict = {
"pr_sequences": pr_sequences,
"pr_loc_outputs": pr_loc_outputs,
"pr_confs": pr_confs,
}
losses_dict = {
"decoder_token_loss": decoder_token_loss,
"decoder_loc_loss": decoder_loc_loss,
"decoder_loss": decoder_loss,
}
kwargs = {}
return output_dict, losses_dict, kwargs
def get_per_example_2head_loc_loss(self, dec_batch, decoder_outputs):
reg_outputs = self.reg_head(decoder_outputs.hidden_states[-1])
block_quads = dec_batch["block_quads"][:, 1:].contiguous()
block_first_tokens = dec_batch["block_first_tokens"][:, 1:].contiguous()
loc_loss = self.loc_loss_2head_func(reg_outputs, block_quads)
loc_loss = loc_loss.mean(-1)
loc_loss = loc_loss * block_first_tokens
loc_loss = loc_loss.sum(1) / block_first_tokens.sum(1)
# To avoid NaN loss
loc_loss = torch.nan_to_num(loc_loss, nan=0.0, posinf=0.0, neginf=0.0)
loc_loss = self.weight_loss(dec_batch, loc_loss).mean()
return loc_loss
def get_decoder_hidden_states(self, decoder_outputs):
decoder_hidden_states = []
for token_idx, all_layers_hidden_states in enumerate(
decoder_outputs.hidden_states[:-1]
):
if token_idx == 0:
decoder_hidden_states.append(
all_layers_hidden_states[-1][:, -1, :].unsqueeze(1).contiguous()
)
else:
decoder_hidden_states.append(all_layers_hidden_states[-1].contiguous())
if len(decoder_hidden_states) == 0:
return 0
decoder_hidden_states = torch.cat(decoder_hidden_states, 1)
return decoder_hidden_states
def get_pr_loc_outputs(self, dec_batch, decoder_outputs, reg_outputs):
bsz = reg_outputs.shape[0]
pr_loc_outputs = [[] for _ in range(bsz)]
for example_idx, sequence in enumerate(decoder_outputs.sequences):
task_name = dec_batch["task_names"][example_idx]
target_block_token_id = self.target_block_token_id_dict[task_name]
is_target_block_token_indices = (
sequence[:-1][dec_batch["max_end_prompt_token_idx"] + 1 :]
== target_block_token_id
)
pr_loc_outputs[example_idx] = reg_outputs[
example_idx, is_target_block_token_indices, :
]
return pr_loc_outputs
def get_pr_confs(self, dec_batch, decoder_outputs):
logits = torch.stack(decoder_outputs.scores).permute(1, 0, 2).contiguous()
probs = nn.functional.softmax(logits, -1).cpu().numpy()
pr_confs = []
for example_idx, sequence in enumerate(decoder_outputs.sequences):
task_name = dec_batch["task_names"][example_idx]
target_block_start_token_id = self.target_block_start_token_id_dict[
task_name
]
target_block_token_id = self.target_block_token_id_dict[task_name]
wo_prompt_seq = sequence[
torch.nonzero(sequence == self.end_prompt_token_id) + 1 :
]
seq_pr_confs = []
token_probs = []
for token_idx, token_id in enumerate(wo_prompt_seq):
if task_name == "object_detection":
if token_id == target_block_token_id:
seq_pr_confs.append(
probs[example_idx, token_idx - 1].max()
) # cls confidence
# seq_pr_confs.append(probs[example_idx, token_idx-5:token_idx-1].max(1).mean()) # box confidence mean
else:
if token_id == target_block_start_token_id: # [START_TEXT_BLOCK]
token_probs.clear()
elif token_id == target_block_token_id: # [END_TEXT_BLOCK]
# Since pr_reg_outputs is generated on every [END_TEXT_BLOCK]
if len(token_probs) == 0:
block_prob = 0.0
else:
block_prob = sum(token_probs) / len(token_probs)
seq_pr_confs.append(block_prob)
token_probs.clear()
else:
token_probs.append(probs[example_idx, token_idx, token_id])
pr_confs.append(seq_pr_confs)
return pr_confs
def __get_reg_head(self, n_loc_head_hidden_layers):
# https://github.com/facebookresearch/detr/blob/main/models/detr.py#L38
# https://github.com/facebookresearch/detr/blob/091a817eca74b8b97e35e4531c1c39f89fbe38eb/models/detr.py#L289
reg_heads = []
hidden_dim = self.model.config.hidden_size
for _ in range(n_loc_head_hidden_layers):
reg_heads.extend([nn.Linear(hidden_dim, hidden_dim), nn.ReLU()])
reg_heads.append(nn.Linear(hidden_dim, 8))
return nn.Sequential(*reg_heads)
def prepare_inputs_for_inference(
self, input_ids, past=None, attention_mask=None, use_cache=None, **model_kwargs
):
input_shape = input_ids.shape
if attention_mask is None:
attention_mask = input_ids.new_ones(input_shape)
if past is not None:
input_ids = input_ids[:, -1:]
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"past_key_values": past,
"use_cache": use_cache,
"encoder_hidden_states": model_kwargs["encoder_hidden_states"],
}
def _add_special_tokens(self, dataset_items):
special_tokens = []
for dataset_item in dataset_items:
| special_token_file = get_file( | 8 | 2023-11-15 00:40:08+00:00 | 8k |
speckai/speck | src/python/speck/connections/anthropic.py | [
{
"identifier": "NOT_GIVEN",
"path": "src/python/speck/chat/entities.py",
"snippet": "NOT_GIVEN = None"
},
{
"identifier": "ChatConfig",
"path": "src/python/speck/chat/entities.py",
"snippet": "class ChatConfig:\n # Todo: add typed params here\n # Todo: Create conversions to other ... | import json
import httpx
import requests
from typing import Union
from ..chat.entities import (
NOT_GIVEN,
ChatConfig,
IChatClient,
LogConfig,
MessageChunk,
Prompt,
Response,
Stream,
)
from .connector import IConnector
from .providers import Providers | 5,422 | """
Name: Anthropic
URL: https://anthropic.ai/
Features:
- Chat
"""
def _process_chunk(obj) -> MessageChunk:
return MessageChunk(content=obj["completion"])
class AnthropicStream:
def __init__(self, iterator):
self.iterator = iterator
self.closed = False
def __iter__(self):
return self
def __next__(self):
while True:
if self.closed:
raise StopIteration
obj = next(self.iterator)
line = obj.decode("utf-8")
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("stop_reason") is not None:
self.closed = True
if data.get("completion") is not None:
return data
else:
continue
class AnthropicResponse(Response):
def __init__(self, obj):
content = obj["completion"]
super().__init__(
content=content,
prompt_tokens=None,
completion_tokens=None,
raw=obj,
)
class AnthropicConnector(IConnector, IChatClient):
def __init__(self, api_key: str = None, client: "Speck" = None):
super().__init__(client=client, provider=Providers.Anthropic)
if api_key is not None:
self.api_key = api_key
self.url = "https://api.anthropic.com/v1/complete"
def _convert_messages_to_prompt(self, messages: Prompt) -> str:
res = ""
if messages.messages[0].role == "system":
res = "System: " + messages.messages[0].content + "\n\n"
for msg in messages.messages:
if msg.role == "system":
continue
res += (
f"{'Human' if msg.role == 'user' else 'Assistant'}: "
+ msg.content
+ "\n\n"
)
res += "Assistant:"
return res
def _process_kwargs(self, prompt: Prompt, config: ChatConfig, **config_kwargs):
if config is NOT_GIVEN:
config = ChatConfig(**config_kwargs)
# Todo: convert to default config based on class param
# Remove all None values
all_kwargs = {k: v for k, v in vars(config).items() if v is not None}
input = self._convert_messages_to_prompt(prompt)
headers = {
"anthropic-version": config.get("anthropic_version", "2023-06-01"),
"content-type": "application/json",
"x-api-key": self.api_key,
}
data = {
"model": config.model,
"prompt": input,
"max_tokens_to_sample": config.max_tokens or 100,
"stream": config.stream,
"temperature": config.temperature,
**config.chat_args,
}
blocked_kwargs = ["provider", "_log", "chat_args", "stream", "max_tokens"]
for k, v in all_kwargs.items():
if k not in data and k not in blocked_kwargs:
data[k] = v
log_config: LogConfig = None
if config_kwargs.get("_log"):
if self._client.log_config:
log_config = self._client.log_config
elif not config_kwargs.get("log_config"):
raise ValueError(
"No log config found. Define the log config in the log or client."
)
else:
log_config = config_kwargs.get("log_config")
return headers, data, all_kwargs, log_config
def chat(
self, prompt: Prompt, config: ChatConfig = NOT_GIVEN, **config_kwargs
| """
Name: Anthropic
URL: https://anthropic.ai/
Features:
- Chat
"""
def _process_chunk(obj) -> MessageChunk:
return MessageChunk(content=obj["completion"])
class AnthropicStream:
def __init__(self, iterator):
self.iterator = iterator
self.closed = False
def __iter__(self):
return self
def __next__(self):
while True:
if self.closed:
raise StopIteration
obj = next(self.iterator)
line = obj.decode("utf-8")
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("stop_reason") is not None:
self.closed = True
if data.get("completion") is not None:
return data
else:
continue
class AnthropicResponse(Response):
def __init__(self, obj):
content = obj["completion"]
super().__init__(
content=content,
prompt_tokens=None,
completion_tokens=None,
raw=obj,
)
class AnthropicConnector(IConnector, IChatClient):
def __init__(self, api_key: str = None, client: "Speck" = None):
super().__init__(client=client, provider=Providers.Anthropic)
if api_key is not None:
self.api_key = api_key
self.url = "https://api.anthropic.com/v1/complete"
def _convert_messages_to_prompt(self, messages: Prompt) -> str:
res = ""
if messages.messages[0].role == "system":
res = "System: " + messages.messages[0].content + "\n\n"
for msg in messages.messages:
if msg.role == "system":
continue
res += (
f"{'Human' if msg.role == 'user' else 'Assistant'}: "
+ msg.content
+ "\n\n"
)
res += "Assistant:"
return res
def _process_kwargs(self, prompt: Prompt, config: ChatConfig, **config_kwargs):
if config is NOT_GIVEN:
config = ChatConfig(**config_kwargs)
# Todo: convert to default config based on class param
# Remove all None values
all_kwargs = {k: v for k, v in vars(config).items() if v is not None}
input = self._convert_messages_to_prompt(prompt)
headers = {
"anthropic-version": config.get("anthropic_version", "2023-06-01"),
"content-type": "application/json",
"x-api-key": self.api_key,
}
data = {
"model": config.model,
"prompt": input,
"max_tokens_to_sample": config.max_tokens or 100,
"stream": config.stream,
"temperature": config.temperature,
**config.chat_args,
}
blocked_kwargs = ["provider", "_log", "chat_args", "stream", "max_tokens"]
for k, v in all_kwargs.items():
if k not in data and k not in blocked_kwargs:
data[k] = v
log_config: LogConfig = None
if config_kwargs.get("_log"):
if self._client.log_config:
log_config = self._client.log_config
elif not config_kwargs.get("log_config"):
raise ValueError(
"No log config found. Define the log config in the log or client."
)
else:
log_config = config_kwargs.get("log_config")
return headers, data, all_kwargs, log_config
def chat(
self, prompt: Prompt, config: ChatConfig = NOT_GIVEN, **config_kwargs | ) -> Union[AnthropicResponse, Stream]: | 7 | 2023-11-15 05:46:05+00:00 | 8k |
hahnyuan/ASVD4LLM | huggingface_repos/build_asvd_repo.py | [
{
"identifier": "evaluate_model",
"path": "evaluate.py",
"snippet": "@torch.no_grad()\ndef evaluate_model(\n model,\n tokenizer,\n model_name,\n tasks,\n eval_ppl=\"\",\n num_fewshot=0,\n limit=-1,\n batch_size=1,\n):\n \"\"\"\n model: model name\n limit: number of test ... | import sys
import argparse
import torch
import os
import json
from transformers import AutoModelForCausalLM, AutoTokenizer, OPTForCausalLM
from transformers.models.opt.configuration_opt import OPTConfig
from evaluate import evaluate_model
from datautils import get_calib_data
from act_aware_utils import calib_input_distribution, calib_fisher_info
from sensitivity import calib_sensitivity_ppl, calib_sensitivity_stable_rank
from quantization import rtn_quant_sequential
from binary_search import binary_search_truncation_rank
from modules.svd_linear import SVDLinear | 6,422 |
sys.path.append(".")
def main(args):
model_id = args.model_id
# Load model
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_id, device_map="auto", torch_dtype=torch.float16, trust_remote_code=True
)
# sensitivity calibration
calib_loader = get_calib_data(args.calib_dataset, tokenizer, model_id, 256)
if "fisher" in args.scaling_method:
|
sys.path.append(".")
def main(args):
model_id = args.model_id
# Load model
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_id, device_map="auto", torch_dtype=torch.float16, trust_remote_code=True
)
# sensitivity calibration
calib_loader = get_calib_data(args.calib_dataset, tokenizer, model_id, 256)
if "fisher" in args.scaling_method: | calib_fisher_info(model, calib_loader, args.use_cache) | 3 | 2023-11-10 02:18:36+00:00 | 8k |
chaiNNer-org/spandrel | src/spandrel/architectures/GFPGAN/arch/gfpganv1_arch.py | [
{
"identifier": "FusedLeakyReLU",
"path": "src/spandrel/architectures/GFPGAN/arch/fused_act.py",
"snippet": "class FusedLeakyReLU(nn.Module):\n def __init__(self, channel, negative_slope=0.2, scale=2**0.5):\n super().__init__()\n\n self.bias = nn.Parameter(torch.zeros(channel))\n ... | import math
import random
import torch
from torch import nn
from torch.nn import functional as F
from .fused_act import FusedLeakyReLU
from .stylegan2_arch import (
ConvLayer,
EqualConv2d,
EqualLinear,
ResBlock,
ScaledLeakyReLU,
StyleGAN2Generator,
) | 6,247 | latent2 = (
styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)
)
latent = torch.cat([latent1, latent2], 1)
# main generation
out = self.constant_input(latent.shape[0])
out = self.style_conv1(out, latent[:, 0], noise=noise[0])
skip = self.to_rgb1(out, latent[:, 1])
i = 1
for conv1, conv2, noise1, noise2, to_rgb in zip(
self.style_convs[::2],
self.style_convs[1::2],
noise[1::2],
noise[2::2],
self.to_rgbs,
):
out = conv1(out, latent[:, i], noise=noise1)
# the conditions may have fewer levels
if i < len(conditions):
# SFT part to combine the conditions
if self.sft_half: # only apply SFT to half of the channels
out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1)
out_sft = out_sft * conditions[i - 1] + conditions[i]
out = torch.cat([out_same, out_sft], dim=1)
else: # apply SFT to all the channels
out = out * conditions[i - 1] + conditions[i]
out = conv2(out, latent[:, i + 1], noise=noise2)
skip = to_rgb(out, latent[:, i + 2], skip) # feature back to the rgb space
i += 2
image = skip
if return_latents:
return image, latent
else:
return image, None
class ConvUpLayer(nn.Module):
"""Convolutional upsampling layer. It uses bilinear upsampler + Conv.
Args:
in_channels (int): Channel number of the input.
out_channels (int): Channel number of the output.
kernel_size (int): Size of the convolving kernel.
stride (int): Stride of the convolution. Default: 1
padding (int): Zero-padding added to both sides of the input. Default: 0.
bias (bool): If ``True``, adds a learnable bias to the output. Default: ``True``.
bias_init_val (float): Bias initialized value. Default: 0.
activate (bool): Whether use activateion. Default: True.
"""
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
bias=True,
bias_init_val=0,
activate=True,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
# self.scale is used to scale the convolution weights, which is related to the common initializations.
self.scale = 1 / math.sqrt(in_channels * kernel_size**2)
self.weight = nn.Parameter(
torch.randn(out_channels, in_channels, kernel_size, kernel_size)
)
if bias and not activate:
self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))
else:
self.register_parameter("bias", None)
# activation
if activate:
if bias:
self.activation = FusedLeakyReLU(out_channels)
else:
self.activation = ScaledLeakyReLU(0.2)
else:
self.activation = None
def forward(self, x):
# bilinear upsample
out = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
# conv
out = F.conv2d(
out,
self.weight * self.scale,
bias=self.bias,
stride=self.stride,
padding=self.padding,
)
# activation
if self.activation is not None:
out = self.activation(out)
return out
class ResUpBlock(nn.Module):
"""Residual block with upsampling.
Args:
in_channels (int): Channel number of the input.
out_channels (int): Channel number of the output.
"""
def __init__(self, in_channels, out_channels):
super().__init__()
| # type: ignore
class StyleGAN2GeneratorSFT(StyleGAN2Generator):
"""StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).
Args:
out_size (int): The spatial size of outputs.
num_style_feat (int): Channel number of style features. Default: 512.
num_mlp (int): Layer number of MLP style layers. Default: 8.
channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.
resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. A cross production will be
applied to extent 1D resample kernel to 2D resample kernel. Default: (1, 3, 3, 1).
lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.
narrow (float): The narrow ratio for channels. Default: 1.
sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.
"""
def __init__(
self,
out_size,
num_style_feat=512,
num_mlp=8,
channel_multiplier=2,
resample_kernel=(1, 3, 3, 1),
lr_mlp=0.01,
narrow=1,
sft_half=False,
):
super().__init__(
out_size,
num_style_feat=num_style_feat,
num_mlp=num_mlp,
channel_multiplier=channel_multiplier,
resample_kernel=resample_kernel,
lr_mlp=lr_mlp,
narrow=narrow,
)
self.sft_half = sft_half
def forward(
self,
styles,
conditions,
input_is_latent=False,
noise=None,
randomize_noise=True,
truncation=1,
truncation_latent=None,
inject_index=None,
return_latents=False,
):
"""Forward function for StyleGAN2GeneratorSFT.
Args:
styles (list[Tensor]): Sample codes of styles.
conditions (list[Tensor]): SFT conditions to generators.
input_is_latent (bool): Whether input is latent style. Default: False.
noise (Tensor | None): Input noise or None. Default: None.
randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.
truncation (float): The truncation ratio. Default: 1.
truncation_latent (Tensor | None): The truncation latent tensor. Default: None.
inject_index (int | None): The injection index for mixing noise. Default: None.
return_latents (bool): Whether to return style latents. Default: False.
"""
# style codes -> latents with Style MLP layer
if not input_is_latent:
styles = [self.style_mlp(s) for s in styles]
# noises
if noise is None:
if randomize_noise:
noise = [None] * self.num_layers # for each style conv layer
else: # use the stored noise
noise = [
getattr(self.noises, f"noise{i}") for i in range(self.num_layers)
]
# style truncation
if truncation < 1:
style_truncation = []
for style in styles:
style_truncation.append(
truncation_latent + truncation * (style - truncation_latent)
)
styles = style_truncation
# get style latents with injection
if len(styles) == 1:
inject_index = self.num_latent
if styles[0].ndim < 3:
# repeat latent code for all the layers
latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
else: # used for encoder with different latent code for each layer
latent = styles[0]
elif len(styles) == 2: # mixing noises
if inject_index is None:
inject_index = random.randint(1, self.num_latent - 1)
latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
latent2 = (
styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)
)
latent = torch.cat([latent1, latent2], 1)
# main generation
out = self.constant_input(latent.shape[0])
out = self.style_conv1(out, latent[:, 0], noise=noise[0])
skip = self.to_rgb1(out, latent[:, 1])
i = 1
for conv1, conv2, noise1, noise2, to_rgb in zip(
self.style_convs[::2],
self.style_convs[1::2],
noise[1::2],
noise[2::2],
self.to_rgbs,
):
out = conv1(out, latent[:, i], noise=noise1)
# the conditions may have fewer levels
if i < len(conditions):
# SFT part to combine the conditions
if self.sft_half: # only apply SFT to half of the channels
out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1)
out_sft = out_sft * conditions[i - 1] + conditions[i]
out = torch.cat([out_same, out_sft], dim=1)
else: # apply SFT to all the channels
out = out * conditions[i - 1] + conditions[i]
out = conv2(out, latent[:, i + 1], noise=noise2)
skip = to_rgb(out, latent[:, i + 2], skip) # feature back to the rgb space
i += 2
image = skip
if return_latents:
return image, latent
else:
return image, None
class ConvUpLayer(nn.Module):
"""Convolutional upsampling layer. It uses bilinear upsampler + Conv.
Args:
in_channels (int): Channel number of the input.
out_channels (int): Channel number of the output.
kernel_size (int): Size of the convolving kernel.
stride (int): Stride of the convolution. Default: 1
padding (int): Zero-padding added to both sides of the input. Default: 0.
bias (bool): If ``True``, adds a learnable bias to the output. Default: ``True``.
bias_init_val (float): Bias initialized value. Default: 0.
activate (bool): Whether use activateion. Default: True.
"""
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
bias=True,
bias_init_val=0,
activate=True,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
# self.scale is used to scale the convolution weights, which is related to the common initializations.
self.scale = 1 / math.sqrt(in_channels * kernel_size**2)
self.weight = nn.Parameter(
torch.randn(out_channels, in_channels, kernel_size, kernel_size)
)
if bias and not activate:
self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))
else:
self.register_parameter("bias", None)
# activation
if activate:
if bias:
self.activation = FusedLeakyReLU(out_channels)
else:
self.activation = ScaledLeakyReLU(0.2)
else:
self.activation = None
def forward(self, x):
# bilinear upsample
out = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
# conv
out = F.conv2d(
out,
self.weight * self.scale,
bias=self.bias,
stride=self.stride,
padding=self.padding,
)
# activation
if self.activation is not None:
out = self.activation(out)
return out
class ResUpBlock(nn.Module):
"""Residual block with upsampling.
Args:
in_channels (int): Channel number of the input.
out_channels (int): Channel number of the output.
"""
def __init__(self, in_channels, out_channels):
super().__init__()
| self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True) | 1 | 2023-11-17 01:11:47+00:00 | 8k |
Mj23978/OpenServer | openserver/core/llm_models/llm_model_factory.py | [
{
"identifier": "ChatTogetherModel",
"path": "openserver/core/llm_models/together.py",
"snippet": "class ChatTogetherModel(BaseChat):\n def __init__(self, input: LLmInputInterface) -> None:\n self.client = ChatTogetherLLM(\n together_api_key=input.api_key,\n model=input.m... | from .together import ChatTogetherModel, TogetherModel
from .ai21 import AI21Model
from .fireworks import ChatFireworksModel, FireworksModel
from .palm import ChatGooglePalmModel, GooglePalmModel
from .base import LLmInputInterface, LLMType
from .cohere import ChatCohereModel, CohereModel
from .openai import ChatOpenAIModel, OpenAIModel
from .llama_cpp import LlamaCppModel
from .gf4 import ChatG4FModel, G4FModel
from .fake import FakeChatModel, FakeModel | 5,503 |
class LLMFactory:
@classmethod
def get_model(cls, input: LLmInputInterface, provider_name: LLMType | str = 'free'):
if isinstance(provider_name, str):
provider_name = LLMType.get_type(provider_name.lower())
if provider_name == LLMType.OPENAI:
|
class LLMFactory:
@classmethod
def get_model(cls, input: LLmInputInterface, provider_name: LLMType | str = 'free'):
if isinstance(provider_name, str):
provider_name = LLMType.get_type(provider_name.lower())
if provider_name == LLMType.OPENAI: | return OpenAIModel(input) | 12 | 2023-11-11 00:32:31+00:00 | 8k |
motexture/VSeq2VSeq | models/unet_blocks.py | [
{
"identifier": "TemporalConvLayer",
"path": "models/resnet.py",
"snippet": "class TemporalConvLayer(nn.Module):\n def __init__(self, in_dim, out_dim=None, dropout=0.0):\n super().__init__()\n\n out_dim = out_dim or in_dim\n self.in_dim = in_dim\n self.out_dim = out_dim\n\... | import torch
from torch import nn
from itertools import zip_longest
from .resnet import TemporalConvLayer, Downsample2D, ResnetBlock2D, Upsample2D
from .transformers import Transformer2DModel, TransformerTemporalModel, TransformerTemporalConditioningModel | 6,994 | # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def get_down_block(
down_block_type,
num_layers,
in_channels,
out_channels,
temb_channels,
add_downsample,
resnet_eps,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
downsample_padding=None,
only_cross_attention=False,
upcast_attention=False
):
if down_block_type == "DownBlock3D":
return DownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding
)
elif down_block_type == "CrossAttnDownBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
return CrossAttnDownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention
)
raise ValueError(f"{down_block_type} does not exist.")
def get_up_block(
up_block_type,
num_layers,
in_channels,
out_channels,
prev_output_channel,
temb_channels,
add_upsample,
resnet_eps,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
only_cross_attention=False,
upcast_attention=False
):
if up_block_type == "UpBlock3D":
return UpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups
)
elif up_block_type == "CrossAttnUpBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
return CrossAttnUpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention
)
raise ValueError(f"{up_block_type} does not exist.")
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels=1,
output_scale_factor=1.0,
cross_attention_dim=1280,
upcast_attention=False,
):
super().__init__()
self.gradient_checkpointing = False
self.has_cross_attention = True
self.attn_num_head_channels = attn_num_head_channels
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
resnets = [
| # Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def get_down_block(
down_block_type,
num_layers,
in_channels,
out_channels,
temb_channels,
add_downsample,
resnet_eps,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
downsample_padding=None,
only_cross_attention=False,
upcast_attention=False
):
if down_block_type == "DownBlock3D":
return DownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding
)
elif down_block_type == "CrossAttnDownBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
return CrossAttnDownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention
)
raise ValueError(f"{down_block_type} does not exist.")
def get_up_block(
up_block_type,
num_layers,
in_channels,
out_channels,
prev_output_channel,
temb_channels,
add_upsample,
resnet_eps,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
only_cross_attention=False,
upcast_attention=False
):
if up_block_type == "UpBlock3D":
return UpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups
)
elif up_block_type == "CrossAttnUpBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
return CrossAttnUpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_groups=resnet_groups,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention
)
raise ValueError(f"{up_block_type} does not exist.")
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels=1,
output_scale_factor=1.0,
cross_attention_dim=1280,
upcast_attention=False,
):
super().__init__()
self.gradient_checkpointing = False
self.has_cross_attention = True
self.attn_num_head_channels = attn_num_head_channels
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
resnets = [ | ResnetBlock2D( | 2 | 2023-11-14 09:09:09+00:00 | 8k |
AI-sandbox/HyperFast | hyperfast/hyperfast.py | [
{
"identifier": "config",
"path": "hyperfast/config.py",
"snippet": ""
},
{
"identifier": "seed_everything",
"path": "hyperfast/utils.py",
"snippet": "def seed_everything(seed: int):\n random.seed(seed)\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n np.random.seed(seed)\n tor... | import os
import math
import torch
import requests
import numpy as np
import pandas as pd
import torch.nn.functional as F
from torch import Tensor
from types import SimpleNamespace
from .config import config
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from .utils import (
seed_everything,
transform_data_for_main_network,
forward_main_network,
nn_bias_logits,
fine_tune_main_network,
)
from .model import HyperFast | 4,569 | x_test = self._scaler.transform(x_test)
return x_test
def _initialize_fit_attributes(self):
self._rfs = []
self._pcas = []
self._main_networks = []
self._X_preds = []
self._y_preds = []
def _sample_data(self, X, y):
indices = torch.randperm(len(X))[: self.batch_size]
X_pred, y_pred = X[indices].flatten(start_dim=1), y[indices]
if X_pred.shape[0] < self._cfg.n_dims:
n_repeats = math.ceil(self._cfg.n_dims / X_pred.shape[0])
X_pred = torch.repeat_interleave(X_pred, n_repeats, axis=0)
y_pred = torch.repeat_interleave(y_pred, n_repeats, axis=0)
return X_pred, y_pred
def _store_network(self, rf, pca, main_network, X_pred, y_pred):
self._rfs.append(rf)
self._pcas.append(pca)
self._main_networks.append(main_network)
self._X_preds.append(X_pred)
self._y_preds.append(y_pred)
def fit(self, X, y, cat_features=[]):
"""
Generates a main model for the given data.
Args:
X (array-like): Input features.
y (array-like): Target values.
cat_features (list, optional): List of categorical features. Defaults to an empty list.
"""
seed_everything(self.seed)
X, y = check_X_y(X, y)
self._cat_features = cat_features
self.n_features_in_ = X.shape[1]
self.classes_ = np.unique(y)
X, y = self._preprocess_fitting_data(X, y)
self._initialize_fit_attributes()
for n in range(self.n_ensemble):
X_pred, y_pred = self._sample_data(X, y)
self.n_classes_ = len(torch.unique(y_pred).cpu().numpy())
rf, pca, main_network = self._model(X_pred, y_pred, self.n_classes_)
if self.optimization == "ensemble_optimize":
rf, pca, main_network, self._model.nn_bias = fine_tune_main_network(
self._cfg,
X_pred,
y_pred,
self.n_classes_,
rf,
pca,
main_network,
self._model.nn_bias,
self.device,
self.optimize_steps,
self.batch_size,
)
self._store_network(rf, pca, main_network, X_pred, y_pred)
if self.optimization == "optimize" and self.optimize_steps > 0:
assert len(self._main_networks) == 1
(
self._rfs[0],
self._pcas[0],
self._main_networks[0],
self._model.nn_bias,
) = fine_tune_main_network(
self._cfg,
X,
y,
self.n_classes_,
self._rfs[0],
self._pcas[0],
self._main_networks[0],
self._model.nn_bias,
self.device,
self.optimize_steps,
self.batch_size,
)
return self
def predict_proba(self, X):
check_is_fitted(self)
X = check_array(X)
X = self._preprocess_test_data(X)
with torch.no_grad():
X = torch.Tensor(X).to(self.device)
orig_X = X
yhats = []
for jj in range(len(self._main_networks)):
main_network = self._main_networks[jj]
rf = self._rfs[jj]
pca = self._pcas[jj]
X_pred = self._X_preds[jj]
y_pred = self._y_preds[jj]
X_transformed = transform_data_for_main_network(
X=X, cfg=self._cfg, rf=rf, pca=pca
)
outputs, intermediate_activations = forward_main_network(
X_transformed, main_network
)
if self.nn_bias:
X_pred_ = transform_data_for_main_network(
X=X_pred, cfg=self._cfg, rf=rf, pca=pca
)
outputs_pred, intermediate_activations_pred = forward_main_network(
X_pred_, main_network
)
for bb, bias in enumerate(self._model.nn_bias):
if bb == 0:
|
class HyperFastClassifier(BaseEstimator):
"""
A scikit-learn-like interface for the HyperFast model.
Attributes:
device (str): Device to run the model on.
n_ensemble (int): Number of ensemble models to use.
batch_size (int): Size of the batch for weight prediction and ensembling.
nn_bias (bool): Whether to use nearest neighbor bias.
optimization (str): Strategy for optimization, can be None, 'optimize', or 'ensemble_optimize'.
optimize_steps (int): Number of optimization steps.
torch_pca (bool): Whether to use PyTorch-based PCA optimized for GPU (fast) or scikit-learn PCA (slower).
seed (int): Random seed for reproducibility.
"""
def __init__(
self,
device="cuda:0",
n_ensemble=16,
batch_size=2048,
nn_bias=False,
optimization="ensemble_optimize",
optimize_steps=64,
torch_pca=True,
seed=3,
):
self.device = device
self.n_ensemble = n_ensemble
self.batch_size = batch_size
self.nn_bias = nn_bias
self.optimization = optimization
self.optimize_steps = optimize_steps
self.torch_pca = torch_pca
self.seed = seed
seed_everything(self.seed)
self._cfg = self._load_config(config, self.device, self.torch_pca, self.nn_bias)
self._model = self._initialize_model(self._cfg)
def _load_config(self, config, device, torch_pca, nn_bias):
cfg = SimpleNamespace(**config)
cfg.device = device
cfg.torch_pca = torch_pca
cfg.nn_bias = nn_bias
return cfg
def _initialize_model(self, cfg):
model = HyperFast(cfg).to(cfg.device)
if not os.path.exists(cfg.model_path):
self._download_model(cfg.model_url, cfg.model_path)
try:
print(f"Loading model from {cfg.model_path}...", flush=True)
model.load_state_dict(
torch.load(cfg.model_path, map_location=torch.device(cfg.device))
)
print(f"Model loaded from {cfg.model_path}", flush=True)
except FileNotFoundError as e:
raise FileNotFoundError(f"Model file not found at {cfg.model_path}") from e
model.eval()
return model
def _download_model(self, url, local_path):
print(
f"Downloading model from {url}, since no model was found at {local_path}",
flush=True,
)
response = requests.get(url)
if response.status_code == 200:
with open(local_path, "wb") as f:
f.write(response.content)
print(f"Model downloaded and saved to {local_path}")
else:
raise ConnectionError(f"Failed to download the model from {url}")
def _preprocess_fitting_data(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:
x = np.array(x, dtype=np.float32).copy()
y = np.array(y, dtype=np.int64).copy()
# Impute missing values for numerical features with the mean
self._num_imputer = SimpleImputer(missing_values=np.nan, strategy="mean")
self._all_feature_idxs = np.arange(x.shape[1])
self._numerical_feature_idxs = np.setdiff1d(
self._all_feature_idxs, self._cat_features
)
if len(self._numerical_feature_idxs) > 0:
self._num_imputer.fit(x[:, self._numerical_feature_idxs])
x[:, self._numerical_feature_idxs] = self._num_imputer.transform(
x[:, self._numerical_feature_idxs]
)
if len(self._cat_features) > 0:
# Impute missing values for categorical features with the most frequent category
self.cat_imputer = SimpleImputer(
missing_values=np.nan, strategy="most_frequent"
)
self.cat_imputer.fit(x[:, self._cat_features])
x[:, self._cat_features] = self.cat_imputer.transform(
x[:, self._cat_features]
)
# One-hot encode categorical features
x = pd.DataFrame(x)
self.one_hot_encoder = ColumnTransformer(
transformers=[
(
"cat",
OneHotEncoder(sparse=False, handle_unknown="ignore"),
self._cat_features,
)
],
remainder="passthrough",
)
self.one_hot_encoder.fit(x)
x = self.one_hot_encoder.transform(x)
# Standardize data
self._scaler = StandardScaler()
self._scaler.fit(x)
x = self._scaler.transform(x)
return torch.tensor(x, dtype=torch.float).to(self.device), torch.tensor(
y, dtype=torch.long
).to(self.device)
def _preprocess_test_data(self, x_test):
x_test = np.array(x_test, dtype=np.float32).copy()
# Impute missing values for numerical features with the mean
if len(self._numerical_feature_idxs) > 0:
x_test[:, self._numerical_feature_idxs] = self._num_imputer.transform(
x_test[:, self._numerical_feature_idxs]
)
if len(self._cat_features) > 0:
# Impute missing values for categorical features with the most frequent category
x_test[:, self._cat_features] = self.cat_imputer.transform(
x_test[:, self._cat_features]
)
# One-hot encode categorical features
x_test = pd.DataFrame(x_test)
x_test = self.one_hot_encoder.transform(x_test)
# Standardize data
x_test = self._scaler.transform(x_test)
return x_test
def _initialize_fit_attributes(self):
self._rfs = []
self._pcas = []
self._main_networks = []
self._X_preds = []
self._y_preds = []
def _sample_data(self, X, y):
indices = torch.randperm(len(X))[: self.batch_size]
X_pred, y_pred = X[indices].flatten(start_dim=1), y[indices]
if X_pred.shape[0] < self._cfg.n_dims:
n_repeats = math.ceil(self._cfg.n_dims / X_pred.shape[0])
X_pred = torch.repeat_interleave(X_pred, n_repeats, axis=0)
y_pred = torch.repeat_interleave(y_pred, n_repeats, axis=0)
return X_pred, y_pred
def _store_network(self, rf, pca, main_network, X_pred, y_pred):
self._rfs.append(rf)
self._pcas.append(pca)
self._main_networks.append(main_network)
self._X_preds.append(X_pred)
self._y_preds.append(y_pred)
def fit(self, X, y, cat_features=[]):
"""
Generates a main model for the given data.
Args:
X (array-like): Input features.
y (array-like): Target values.
cat_features (list, optional): List of categorical features. Defaults to an empty list.
"""
seed_everything(self.seed)
X, y = check_X_y(X, y)
self._cat_features = cat_features
self.n_features_in_ = X.shape[1]
self.classes_ = np.unique(y)
X, y = self._preprocess_fitting_data(X, y)
self._initialize_fit_attributes()
for n in range(self.n_ensemble):
X_pred, y_pred = self._sample_data(X, y)
self.n_classes_ = len(torch.unique(y_pred).cpu().numpy())
rf, pca, main_network = self._model(X_pred, y_pred, self.n_classes_)
if self.optimization == "ensemble_optimize":
rf, pca, main_network, self._model.nn_bias = fine_tune_main_network(
self._cfg,
X_pred,
y_pred,
self.n_classes_,
rf,
pca,
main_network,
self._model.nn_bias,
self.device,
self.optimize_steps,
self.batch_size,
)
self._store_network(rf, pca, main_network, X_pred, y_pred)
if self.optimization == "optimize" and self.optimize_steps > 0:
assert len(self._main_networks) == 1
(
self._rfs[0],
self._pcas[0],
self._main_networks[0],
self._model.nn_bias,
) = fine_tune_main_network(
self._cfg,
X,
y,
self.n_classes_,
self._rfs[0],
self._pcas[0],
self._main_networks[0],
self._model.nn_bias,
self.device,
self.optimize_steps,
self.batch_size,
)
return self
def predict_proba(self, X):
check_is_fitted(self)
X = check_array(X)
X = self._preprocess_test_data(X)
with torch.no_grad():
X = torch.Tensor(X).to(self.device)
orig_X = X
yhats = []
for jj in range(len(self._main_networks)):
main_network = self._main_networks[jj]
rf = self._rfs[jj]
pca = self._pcas[jj]
X_pred = self._X_preds[jj]
y_pred = self._y_preds[jj]
X_transformed = transform_data_for_main_network(
X=X, cfg=self._cfg, rf=rf, pca=pca
)
outputs, intermediate_activations = forward_main_network(
X_transformed, main_network
)
if self.nn_bias:
X_pred_ = transform_data_for_main_network(
X=X_pred, cfg=self._cfg, rf=rf, pca=pca
)
outputs_pred, intermediate_activations_pred = forward_main_network(
X_pred_, main_network
)
for bb, bias in enumerate(self._model.nn_bias):
if bb == 0: | outputs = nn_bias_logits( | 4 | 2023-11-14 05:56:47+00:00 | 8k |
TCLResearchEurope/torch-dag | torch_dag/patterns_v2/transform.py | [
{
"identifier": "DagModule",
"path": "torch_dag/core/dag_module.py",
"snippet": "class DagModule(torch.nn.Module):\n MAX_LEN_REPR = None\n\n def __init__(\n self,\n name: str,\n vertices: Optional[List[Vertex]] = None,\n output_vertex: Optional[InnerVert... | import sys
import enum
import copy
import logging
import numpy as np
import torch
from typing import Any, Type, Union
from typing import Dict
from typing import List
from typing import Tuple
from typing import Callable
from torch_dag.core.dag_module import DagModule
from torch_dag.core.dag_module import InnerVertex, InputVertex
from torch_dag.patterns_v2.pattern import Pattern
from torch_dag.patterns_v2.match import Match | 5,641 |
logger = logging.getLogger(__name__)
class SelectionType(enum.Enum):
FIRST = 'first'
LAST = 'last'
ALL = 'all'
ALL_BUT_FIRST = 'all_but_first'
ALL_BUT_LAST = 'all_but_last'
class Transform:
"""
For more information on patterns please refer to https://gitlab.com/tcl-research/auto-ml/blog/-/blob/main/2022-06-16-patterns/README.md or https://gitlab.com/tcl-research/auto-ml/node-api/-/blob/master/tutorials/advanced/pattens.ipynb
"""
PRESERVE_PARAMS_FROM = 'preserve_old_params_from'
@staticmethod
def _assert_forward_pass_equal(
|
logger = logging.getLogger(__name__)
class SelectionType(enum.Enum):
FIRST = 'first'
LAST = 'last'
ALL = 'all'
ALL_BUT_FIRST = 'all_but_first'
ALL_BUT_LAST = 'all_but_last'
class Transform:
"""
For more information on patterns please refer to https://gitlab.com/tcl-research/auto-ml/blog/-/blob/main/2022-06-16-patterns/README.md or https://gitlab.com/tcl-research/auto-ml/node-api/-/blob/master/tutorials/advanced/pattens.ipynb
"""
PRESERVE_PARAMS_FROM = 'preserve_old_params_from'
@staticmethod
def _assert_forward_pass_equal( | cell1: DagModule, | 0 | 2023-11-17 15:36:44+00:00 | 8k |
timlrx/simple-ai-agents | tests/test_chat_session.py | [
{
"identifier": "ChatLLMSession",
"path": "simple_ai_agents/chat_session.py",
"snippet": "class ChatLLMSession(ChatSession):\n system: str = \"You are a helpful assistant.\"\n llm_options: Optional[LLMOptions] = {\"model\": \"gpt-3.5-turbo\"}\n\n def prepare_request(\n self,\n pro... | import pytest
from dotenv import load_dotenv
from pydantic import BaseModel
from simple_ai_agents.chat_session import ChatLLMSession
from simple_ai_agents.models import LLMOptions | 3,816 |
load_dotenv()
class UserDetail(BaseModel):
name: str
age: int
def test_prepare_request():
sess = ChatLLMSession()
prompt = "Hello, how can I help you?"
system = "Test system"
|
load_dotenv()
class UserDetail(BaseModel):
name: str
age: int
def test_prepare_request():
sess = ChatLLMSession()
prompt = "Hello, how can I help you?"
system = "Test system" | llm_options: LLMOptions = {"model": "test-model", "temperature": 0.5} | 1 | 2023-11-10 06:01:25+00:00 | 8k |
DIAGNijmegen/HoVer-UNet | run_train.py | [
{
"identifier": "apply_postprocessing",
"path": "train/apply_postprocessing.py",
"snippet": "def apply_postprocessing(path_weights, path_test, model):\n model.load_state_dict(torch.load(path_weights)['model_state_dict'])\n model.eval()\n data_infer = DatasetPannuke(path_test, mode='infer')\n ... | import argparse
import json
import os
import numpy as np
import segmentation_models_pytorch as smp
import torch
from multiprocessing import cpu_count
from pathlib import Path
from torch.utils.data import DataLoader
from train.apply_postprocessing import apply_postprocessing
from data.pannuke_distillation_dataset import DatasetPannuke
from losses.losses import loss_fcn
from train.trainer import train | 4,149 | use_true_labels = False
# Generate all path
project_dir = os.path.join(base_project_dir, project_name)
experiment_name = f'experiment_{experiment_group}_{experiment_id}'
experiment_dir = os.path.join(project_dir, experiment_name)
centroids_path = os.path.join(experiment_dir, 'centroids')
checkpoint_dir = os.path.join(experiment_dir, 'checkpoints')
path_example = os.path.join(experiment_dir, 'examples')
instance_map_path = os.path.join(experiment_dir, 'instance_maps')
######### DIRECTORIES SETTING ##################
if not os.path.exists(project_dir):
os.mkdir(project_dir)
train_state = 0 # 0 train, 1 infer, 2 stats
best_epoch = None
if not os.path.exists(experiment_dir):
os.mkdir(experiment_dir)
os.mkdir(path_example)
os.makedirs(centroids_path)
os.makedirs(instance_map_path)
else:
exists_checkpoint = os.path.exists(checkpoint_dir)
exists_statistics = os.path.exists(os.path.join(experiment_dir, 'statistics.json'))
exists_tissue = os.path.exists(os.path.join(experiment_dir, 'tissue_stats.csv'))
exists_pred_map = os.path.exists(os.path.join(experiment_dir, 'pred_masks.npy'))
if exists_checkpoint and not exists_statistics:
checkpoints = sorted([int(x.split('_')[-1].split('.')[0]) for x in os.listdir(checkpoint_dir)])
checkpoint_id = checkpoints[-1]
path_weights = os.path.join(checkpoint_dir, f'checkpoint_epoch_{checkpoint_id}.pth')
else:
if not exists_statistics:
pass
elif exists_statistics and not exists_pred_map:
train_state = 1
checkpoints = sorted([int(x.split('_')[-1].split('.')[0]) for x in os.listdir(checkpoint_dir)])
best_epoch = checkpoints[-1]
elif exists_pred_map and not exists_tissue:
train_state = 2
else:
print("No operation")
exit(-1)
print("train state %s" % train_state)
print("""
Base directory: %s
Project directory: %s
Experiment directory: %s
Checkpoint directory: %s
Examples directory: %s
Centroids directory: %s
Instance map directory: %s
""" % (
base_project_dir, project_dir, experiment_dir, checkpoint_dir, path_example, centroids_path, instance_map_path))
###########################################################################
with open(os.path.join(experiment_dir, 'metadata.json'), 'w') as mf:
mf.write(json.dumps(args.__dict__))
##################### DATASET SETTING #####################################
print("""
Input shape: %s
Output shape: %s
Types numbers: %s
Path train: %s
Path validation: %s
Path test: %s
Pannuke path: %s
Batch size: %s
Epochs: %s
Encoder: %s
""" % (
input_shape, output_shape, nr_types, path_train, path_val, path_test, pannuke_path, batch_size, nr_epochs,
encoder_name))
train_set = DatasetPannuke(path_train, mode='train', hovernet_predictions=use_hovernet_predictions,
true_labels=use_true_labels)
val_set = DatasetPannuke(path_val, mode='train', hovernet_predictions=use_hovernet_predictions,
true_labels=use_true_labels)
num_workers = cpu_count() // 2
if num_workers > 8:
num_workers = 8
num_workers =0
print(f'Num workers per dataloader: {num_workers}')
dataloader_train = DataLoader(train_set, batch_size=batch_size, shuffle=True, pin_memory=True,
num_workers=num_workers,)# prefetch_factor=2)
dataloader_val = DataLoader(val_set, batch_size=batch_size, shuffle=False, pin_memory=True,
num_workers=num_workers)#, prefetch_factor=2)
###################################################################################
############################## NETWORK AND TRAINING SETTING #####################################
model = smp.Unet(classes=nr_types, encoder_name=encoder_name, ).to('cuda', memory_format=torch.channels_last)
optimizer = torch.optim.Adam(model.parameters(), lr=lr, betas=(0.9, 0.999))
start_epoch = 0
if path_weights:
checkpoint_dict = torch.load(path_weights)
model.load_state_dict(checkpoint_dict['model_state_dict'])
optimizer.load_state_dict(checkpoint_dict['optimizer_state_dict'])
start_epoch = checkpoint_dict['epoch']
if 'train_mode' in checkpoint_dict:
train_mode = checkpoint_dict['train_mode']
print(
f"Resume model info: epoch: {checkpoint_dict['epoch']}, train_loss: {checkpoint_dict['train_loss']}, val_loss: {checkpoint_dict['val_loss']}")
grad_scaler = torch.cuda.amp.GradScaler()
metrics = dict()
#########################################################################################
with open(os.path.join(experiment_dir, 'metadata.json'), 'w') as mf:
mf.write(json.dumps(args.__dict__))
lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, mode='min', min_lr=1e-7, patience=5,
threshold=1e-3)
# LAUNCH TRAINING
if train_state == 0:
best_epoch = train(model, dataloader_train, dataloader_val, nr_epochs, optimizer, grad_scaler,
scheduler=lr_scheduler,
|
if __name__ == '__main__':
torch.cuda.set_device(0)
parser = argparse.ArgumentParser(prog="Train network for nuclei segmentation")
parser.add_argument_group("Info")
parser.add_argument('--base_project_dir', type=str, required=True)
parser.add_argument('--project_name', type=str, required=True)
parser.add_argument('--experiment_group', default=0, type=int, required=True)
parser.add_argument('--experiment_id', default=0, type=int, required=True)
parser.add_argument('--path_train', type=str, required=True)
parser.add_argument('--path_val', type=str, required=True)
parser.add_argument('--path_test', type=str, required=True)
parser.add_argument('--batch_size', default=64, type=int, choices={4, 8, 16, 32, 64, 128, 256})
parser.add_argument('--nr_epochs', default=240, type=int)
parser.add_argument('--lr', default=1e-4, type=float)
parser.add_argument('--pannuke_path', type=str, required=True)
parser.add_argument('--encoder', default='mit_b2',
help='see https://smp.readthedocs.io/en/latest/encoders.html')
parser.add_argument('--use_true_labels', default=1, type=int, choices={0, 1})
parser.add_argument('--use_hovernet_predictions', default=1, type=int, choices={0, 1})
parser.add_argument('--loss_t', default=3, type=int, choices={1, 3, 5, 10, 15, 30})
parser.add_argument('--loss_alpha', default=0.5, type=float)
args = parser.parse_args()
base_project_dir = args.base_project_dir
project_name = args.project_name
experiment_group = args.experiment_group
experiment_id = args.experiment_id
path_weights = None
input_shape = (256, 256)
output_shape = (256, 256)
nr_types = 10
path_train = args.path_train
path_val = args.path_val
path_test = args.path_test
foldid = path_test.split('.')[0][-1]
pannuke_path = args.pannuke_path
true_path = f'{pannuke_path}/Fold{foldid}/masks/fold{foldid}'
batch_size = args.batch_size
nr_epochs = args.nr_epochs
encoder_name = args.encoder
lr = args.lr
loss_alpha = args.loss_alpha
loss_t = args.loss_t
early_stopping = True
use_true_labels = True
if args.use_true_labels == 0:
use_true_labels = False
use_hovernet_predictions = True
if args.use_hovernet_predictions == 0:
use_hovernet_predictions = False
if use_hovernet_predictions and not use_true_labels:
loss_alpha = 1
print("Warning: student_loss_type will be ignored")
print("Warning: loss_alpha will be ignored")
if use_true_labels and not use_hovernet_predictions:
loss_alpha = 0
loss_t = 0
print("Warning: distill_loss_type will be ignored")
print("Warning: loss_alpha will be ignored")
print("Warning: loss_t will be ignored")
if use_true_labels and use_hovernet_predictions:
if loss_alpha == 0:
use_hovernet_predictions = False
if loss_alpha == 1:
use_true_labels = False
# Generate all path
project_dir = os.path.join(base_project_dir, project_name)
experiment_name = f'experiment_{experiment_group}_{experiment_id}'
experiment_dir = os.path.join(project_dir, experiment_name)
centroids_path = os.path.join(experiment_dir, 'centroids')
checkpoint_dir = os.path.join(experiment_dir, 'checkpoints')
path_example = os.path.join(experiment_dir, 'examples')
instance_map_path = os.path.join(experiment_dir, 'instance_maps')
######### DIRECTORIES SETTING ##################
if not os.path.exists(project_dir):
os.mkdir(project_dir)
train_state = 0 # 0 train, 1 infer, 2 stats
best_epoch = None
if not os.path.exists(experiment_dir):
os.mkdir(experiment_dir)
os.mkdir(path_example)
os.makedirs(centroids_path)
os.makedirs(instance_map_path)
else:
exists_checkpoint = os.path.exists(checkpoint_dir)
exists_statistics = os.path.exists(os.path.join(experiment_dir, 'statistics.json'))
exists_tissue = os.path.exists(os.path.join(experiment_dir, 'tissue_stats.csv'))
exists_pred_map = os.path.exists(os.path.join(experiment_dir, 'pred_masks.npy'))
if exists_checkpoint and not exists_statistics:
checkpoints = sorted([int(x.split('_')[-1].split('.')[0]) for x in os.listdir(checkpoint_dir)])
checkpoint_id = checkpoints[-1]
path_weights = os.path.join(checkpoint_dir, f'checkpoint_epoch_{checkpoint_id}.pth')
else:
if not exists_statistics:
pass
elif exists_statistics and not exists_pred_map:
train_state = 1
checkpoints = sorted([int(x.split('_')[-1].split('.')[0]) for x in os.listdir(checkpoint_dir)])
best_epoch = checkpoints[-1]
elif exists_pred_map and not exists_tissue:
train_state = 2
else:
print("No operation")
exit(-1)
print("train state %s" % train_state)
print("""
Base directory: %s
Project directory: %s
Experiment directory: %s
Checkpoint directory: %s
Examples directory: %s
Centroids directory: %s
Instance map directory: %s
""" % (
base_project_dir, project_dir, experiment_dir, checkpoint_dir, path_example, centroids_path, instance_map_path))
###########################################################################
with open(os.path.join(experiment_dir, 'metadata.json'), 'w') as mf:
mf.write(json.dumps(args.__dict__))
##################### DATASET SETTING #####################################
print("""
Input shape: %s
Output shape: %s
Types numbers: %s
Path train: %s
Path validation: %s
Path test: %s
Pannuke path: %s
Batch size: %s
Epochs: %s
Encoder: %s
""" % (
input_shape, output_shape, nr_types, path_train, path_val, path_test, pannuke_path, batch_size, nr_epochs,
encoder_name))
train_set = DatasetPannuke(path_train, mode='train', hovernet_predictions=use_hovernet_predictions,
true_labels=use_true_labels)
val_set = DatasetPannuke(path_val, mode='train', hovernet_predictions=use_hovernet_predictions,
true_labels=use_true_labels)
num_workers = cpu_count() // 2
if num_workers > 8:
num_workers = 8
num_workers =0
print(f'Num workers per dataloader: {num_workers}')
dataloader_train = DataLoader(train_set, batch_size=batch_size, shuffle=True, pin_memory=True,
num_workers=num_workers,)# prefetch_factor=2)
dataloader_val = DataLoader(val_set, batch_size=batch_size, shuffle=False, pin_memory=True,
num_workers=num_workers)#, prefetch_factor=2)
###################################################################################
############################## NETWORK AND TRAINING SETTING #####################################
model = smp.Unet(classes=nr_types, encoder_name=encoder_name, ).to('cuda', memory_format=torch.channels_last)
optimizer = torch.optim.Adam(model.parameters(), lr=lr, betas=(0.9, 0.999))
start_epoch = 0
if path_weights:
checkpoint_dict = torch.load(path_weights)
model.load_state_dict(checkpoint_dict['model_state_dict'])
optimizer.load_state_dict(checkpoint_dict['optimizer_state_dict'])
start_epoch = checkpoint_dict['epoch']
if 'train_mode' in checkpoint_dict:
train_mode = checkpoint_dict['train_mode']
print(
f"Resume model info: epoch: {checkpoint_dict['epoch']}, train_loss: {checkpoint_dict['train_loss']}, val_loss: {checkpoint_dict['val_loss']}")
grad_scaler = torch.cuda.amp.GradScaler()
metrics = dict()
#########################################################################################
with open(os.path.join(experiment_dir, 'metadata.json'), 'w') as mf:
mf.write(json.dumps(args.__dict__))
lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, mode='min', min_lr=1e-7, patience=5,
threshold=1e-3)
# LAUNCH TRAINING
if train_state == 0:
best_epoch = train(model, dataloader_train, dataloader_val, nr_epochs, optimizer, grad_scaler,
scheduler=lr_scheduler, | criterion=lambda x, y, z: loss_fcn(x, y, z, alpha=loss_alpha, T=loss_t), | 2 | 2023-11-10 09:37:29+00:00 | 8k |
joyn-gg/discord.http | discord_http/backend.py | [
{
"identifier": "Command",
"path": "discord_http/commands.py",
"snippet": "class Command:\n def __init__(\n self,\n command: Callable,\n name: str,\n description: Optional[str] = None,\n guild_ids: Optional[list[Union[utils.Snowflake, int]]] = None,\n type: A... | import asyncio
import logging
import signal
from datetime import datetime
from hypercorn.asyncio import serve
from hypercorn.config import Config as HyperConfig
from nacl.exceptions import BadSignatureError
from nacl.signing import VerifyKey
from quart import Quart, request, abort
from quart import Response as QuartResponse
from quart.logging import default_handler
from quart.utils import MustReloadError, restart
from typing import Optional, Any, Union, TYPE_CHECKING
from .commands import Command, Interaction, Listener, SubGroup
from .enums import InteractionType
from .errors import CheckFailed
from .response import BaseResponse, Ping, MessageResponse
from .client import Client
from .context import Context | 6,985 | "task": task
})
class DiscordHTTP(Quart):
def __init__(self, *, client: "Client"):
"""
This serves as the fundemental HTTP server for Discord Interactions
We recommend to not touch this class, unless you know what you're doing
"""
self.uptime: datetime = datetime.now()
self.bot: "Client" = client
self.loop = self.bot.loop
self.debug_events = self.bot.debug_events
self._cog_commands: dict[str, Command] = {}
self._cog_interactions: dict[str, Interaction] = {}
self._cog_listeners: list[Listener] = []
super().__init__(__name__)
# Remove Quart's default logging handler
_quart_log = logging.getLogger("quart.app")
_quart_log.removeHandler(default_handler)
_quart_log.setLevel(logging.CRITICAL)
async def validate_request(self) -> None:
""" Used to validate requests sent by Discord Webhooks """
if not self.bot.public_key:
return abort(401, "invalid public key")
verify_key = VerifyKey(bytes.fromhex(self.bot.public_key))
signature: str = request.headers.get("X-Signature-Ed25519", "")
timestamp: str = request.headers.get("X-Signature-Timestamp", "")
try:
data = await request.data
body = data.decode("utf-8")
verify_key.verify(
f"{timestamp}{body}".encode(),
bytes.fromhex(signature)
)
except BadSignatureError:
abort(401, "invalid request signature")
except Exception:
abort(400, "invalid request body")
def error_messages(
self,
ctx: "Context",
e: Exception
) -> Optional[MessageResponse]:
"""
Used to return error messages to Discord
Parameters
----------
ctx: `Context`
The context of the command
e: `Exception`
The exception that was raised
Returns
-------
`Optional[MessageResponse]`
The message response provided by the library error handler
"""
if isinstance(e, CheckFailed):
return ctx.response.send_message(
content=str(e),
ephemeral=True
)
def _dig_subcommand(
self,
cmd: Union[Command, SubGroup],
data: dict
) -> tuple[Optional[Command], list[dict]]:
""" Used to dig through subcommands to execute correct command/autocomplete """
data_options: list[dict] = data["data"].get("options", [])
while isinstance(cmd, SubGroup):
find_next_step = next((
g for g in data_options
if g.get("name", None) and not g.get("value", None)
), None)
if not find_next_step:
return abort(400, "invalid command")
cmd = cmd.subcommands.get(find_next_step["name"], None) # type: ignore
if not cmd:
_log.warn(
f"Unhandled subcommand: {find_next_step['name']} "
"(not found in local command list)"
)
return abort(404, "command not found")
data_options = find_next_step.get("options", [])
return cmd, data_options
async def _index_interaction(self) -> Union[BaseResponse, QuartResponse, dict]:
"""
The main function to handle all HTTP requests sent by Discord
Please do not touch this function, unless you know what you're doing
"""
await self.validate_request()
data = await request.json
if self.debug_events:
self.bot.dispatch("raw_interaction", data)
context = self.bot._context(self.bot, data)
data_type = data.get("type", -1)
match data_type:
case InteractionType.ping:
|
if TYPE_CHECKING:
_log = logging.getLogger(__name__)
__all__ = (
"DiscordHTTP",
)
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
""" Used by Quart to cancel all tasks on shutdown. """
tasks = [
task for task in asyncio.all_tasks(loop)
if not task.done()
]
if not tasks:
return
for task in list(tasks):
task.cancel()
if task.get_coro().__name__ == "_windows_signal_support":
tasks.remove(task)
loop.run_until_complete(
asyncio.gather(*tasks, return_exceptions=True)
)
for task in tasks:
if not task.cancelled() and task.exception() is not None:
loop.call_exception_handler({
"message": "unhandled exception during shutdown",
"exception": task.exception(),
"task": task
})
class DiscordHTTP(Quart):
def __init__(self, *, client: "Client"):
"""
This serves as the fundemental HTTP server for Discord Interactions
We recommend to not touch this class, unless you know what you're doing
"""
self.uptime: datetime = datetime.now()
self.bot: "Client" = client
self.loop = self.bot.loop
self.debug_events = self.bot.debug_events
self._cog_commands: dict[str, Command] = {}
self._cog_interactions: dict[str, Interaction] = {}
self._cog_listeners: list[Listener] = []
super().__init__(__name__)
# Remove Quart's default logging handler
_quart_log = logging.getLogger("quart.app")
_quart_log.removeHandler(default_handler)
_quart_log.setLevel(logging.CRITICAL)
async def validate_request(self) -> None:
""" Used to validate requests sent by Discord Webhooks """
if not self.bot.public_key:
return abort(401, "invalid public key")
verify_key = VerifyKey(bytes.fromhex(self.bot.public_key))
signature: str = request.headers.get("X-Signature-Ed25519", "")
timestamp: str = request.headers.get("X-Signature-Timestamp", "")
try:
data = await request.data
body = data.decode("utf-8")
verify_key.verify(
f"{timestamp}{body}".encode(),
bytes.fromhex(signature)
)
except BadSignatureError:
abort(401, "invalid request signature")
except Exception:
abort(400, "invalid request body")
def error_messages(
self,
ctx: "Context",
e: Exception
) -> Optional[MessageResponse]:
"""
Used to return error messages to Discord
Parameters
----------
ctx: `Context`
The context of the command
e: `Exception`
The exception that was raised
Returns
-------
`Optional[MessageResponse]`
The message response provided by the library error handler
"""
if isinstance(e, CheckFailed):
return ctx.response.send_message(
content=str(e),
ephemeral=True
)
def _dig_subcommand(
self,
cmd: Union[Command, SubGroup],
data: dict
) -> tuple[Optional[Command], list[dict]]:
""" Used to dig through subcommands to execute correct command/autocomplete """
data_options: list[dict] = data["data"].get("options", [])
while isinstance(cmd, SubGroup):
find_next_step = next((
g for g in data_options
if g.get("name", None) and not g.get("value", None)
), None)
if not find_next_step:
return abort(400, "invalid command")
cmd = cmd.subcommands.get(find_next_step["name"], None) # type: ignore
if not cmd:
_log.warn(
f"Unhandled subcommand: {find_next_step['name']} "
"(not found in local command list)"
)
return abort(404, "command not found")
data_options = find_next_step.get("options", [])
return cmd, data_options
async def _index_interaction(self) -> Union[BaseResponse, QuartResponse, dict]:
"""
The main function to handle all HTTP requests sent by Discord
Please do not touch this function, unless you know what you're doing
"""
await self.validate_request()
data = await request.json
if self.debug_events:
self.bot.dispatch("raw_interaction", data)
context = self.bot._context(self.bot, data)
data_type = data.get("type", -1)
match data_type:
case InteractionType.ping: | _ping = Ping(state=self.bot.state, data=data) | 7 | 2023-11-14 12:50:42+00:00 | 8k |
Ganymede-Bio/bio-curve-fit | tests/test_four_pl_logistic.py | [
{
"identifier": "FourPLLogistic",
"path": "bio_curve_fit/logistic.py",
"snippet": "class FourPLLogistic(BaseEstimator, RegressorMixin, BaseStandardCurve):\n def __init__(\n self,\n A=None,\n B=None,\n C=None,\n D=None,\n LLOD=None,\n ULOD=None,\n ... | import numpy as np
import pandas as pd
import pytest
from bio_curve_fit.logistic import FourPLLogistic
from bio_curve_fit.plotting import plot_standard_curve | 3,685 |
# set a seed for reproducibility
np.random.seed(42)
def test_fit_and_plot():
TEST_PARAMS = [1.0, 1.0, 2.0, 3.0]
x_data = np.logspace(0.00001, 7, 100, base=np.e) # type: ignore
# generate y-data based on the test parameters
y_data = FourPLLogistic.four_param_logistic(
x_data + np.random.normal(0.0, 0.1 * x_data, len(x_data)), *TEST_PARAMS
)
model = FourPLLogistic().fit(
x_data, y_data, weight_func=FourPLLogistic.inverse_variance_weight_function
)
# model should recover parameters used to generate the data
params = list(model.get_params().values())
assert np.isclose(params, TEST_PARAMS, rtol=0.4).all() # type: ignore
r2 = model.score(x_data, y_data)
assert r2 > 0.995
# test plotting
|
# set a seed for reproducibility
np.random.seed(42)
def test_fit_and_plot():
TEST_PARAMS = [1.0, 1.0, 2.0, 3.0]
x_data = np.logspace(0.00001, 7, 100, base=np.e) # type: ignore
# generate y-data based on the test parameters
y_data = FourPLLogistic.four_param_logistic(
x_data + np.random.normal(0.0, 0.1 * x_data, len(x_data)), *TEST_PARAMS
)
model = FourPLLogistic().fit(
x_data, y_data, weight_func=FourPLLogistic.inverse_variance_weight_function
)
# model should recover parameters used to generate the data
params = list(model.get_params().values())
assert np.isclose(params, TEST_PARAMS, rtol=0.4).all() # type: ignore
r2 = model.score(x_data, y_data)
assert r2 > 0.995
# test plotting | plot_standard_curve(x_data, y_data, model) | 1 | 2023-11-13 15:06:15+00:00 | 8k |
chziakas/backbone-learn | backbone_learn/backbone/backbone_clustering.py | [
{
"identifier": "MIOClustering",
"path": "backbone_learn/exact_solvers/mio_clustering.py",
"snippet": "class MIOClustering:\n \"\"\"\n Class for solving clustering problems using Mixed-Integer Optimization.\n \"\"\"\n\n def __init__(\n self,\n n_clusters: int = None,\n t... | from ..exact_solvers.mio_clustering import MIOClustering
from ..heuristic_solvers.kmeans_solver import KMeansSolver
from .backbone_unsupervised import BackboneUnsupervised | 5,072 | # Copyright (c) 2023 Vassilis Digalakis Jr, Christos Ziakas
# Licensed under the MIT License.
class BackboneClustering(BackboneUnsupervised):
"""
Specific implementation of the Backbone method for clustering.
This class uses K-means for heuristic solving and retains MIO optimzer for exact solving.
No screen selector is used in this approach, as K-means is considered efficient for feature selection.
Inherits from:
BackboneBase (ABC): The abstract base class for backbone algorithms.
"""
def set_solvers(self, n_clusters: int = 10, time_limit: int = 1000):
"""
Initializes the clustering method with specified components.
Args:
n_clusters (int, optional): Number of clusters for K-means. Defaults to 10.
time_limit (int): Time limit for the optimization process.
"""
self.screen_selector = None # No screen selector for this clustering approach
| # Copyright (c) 2023 Vassilis Digalakis Jr, Christos Ziakas
# Licensed under the MIT License.
class BackboneClustering(BackboneUnsupervised):
"""
Specific implementation of the Backbone method for clustering.
This class uses K-means for heuristic solving and retains MIO optimzer for exact solving.
No screen selector is used in this approach, as K-means is considered efficient for feature selection.
Inherits from:
BackboneBase (ABC): The abstract base class for backbone algorithms.
"""
def set_solvers(self, n_clusters: int = 10, time_limit: int = 1000):
"""
Initializes the clustering method with specified components.
Args:
n_clusters (int, optional): Number of clusters for K-means. Defaults to 10.
time_limit (int): Time limit for the optimization process.
"""
self.screen_selector = None # No screen selector for this clustering approach | self.heuristic_solver = KMeansSolver(n_clusters=n_clusters) | 1 | 2023-11-18 14:28:12+00:00 | 8k |
newcastleuniversity/DISPEL | dispel/processing/flags.py | [
{
"identifier": "EntityType",
"path": "dispel/data/core.py",
"snippet": "class ReadingSchema:\nclass Evaluation(Epoch):\nclass Session(Epoch):\nclass Reading(FlagMixIn):\n def __init__(\n self,\n *args,\n uuid: str,\n finished: Optional[bool] = None,\n exit_reason: ... | import inspect
from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Dict, Generator, Iterable, Optional, Tuple, Union
from dispel.data.core import EntityType, Reading
from dispel.data.flags import Flag, FlagId, FlagSeverity, FlagType
from dispel.data.levels import Level
from dispel.data.values import AbbreviatedValue as AV
from dispel.processing.utils import TaskMixin
from dispel.utils import set_attributes_from_kwargs | 5,769 | #: The name of the flag
flag_name: Union[AV, str]
#: The type of the flag
flag_type: Union[FlagType, str]
# The severity of the flag
flag_severity: Union[FlagSeverity, str]
#: The detailed reason of the flag
reason: str
#: The stop_processing status of the flag step
stop_processing: bool = False
#: The flagging function
flagging_function: Optional[Callable[..., bool]] = None
def __init__(self, *args, **kwargs):
kwargs = set_attributes_from_kwargs(
self,
"task_name",
"flag_name",
"flag_type",
"flag_severity",
"reason",
"stop_processing",
"flagging_function",
**kwargs,
)
self.kwargs = kwargs
super().__init__(*args, **kwargs)
def get_flag_name(self, **kwargs) -> Union[str, AV]:
"""Get the flag name."""
flag_name = kwargs.get("flag_name", None) or getattr(self, "flag_name")
if isinstance(flag_name, (str, AV)):
return flag_name.format(**kwargs)
raise ValueError("Missing flag name.")
def get_flag_type(self, **kwargs) -> Union[str, FlagType]:
"""Get the flag type."""
flag_type = kwargs.get("flag_type", None) or getattr(self, "flag_type")
if isinstance(flag_type, (str, FlagType)):
return flag_type
raise ValueError("Missing flag type.")
def get_flag_severity(self, **kwargs) -> Union[str, FlagSeverity]:
"""Get the flag severity."""
flag_severity = kwargs.get("flag_severity", None) or getattr(
self, "flag_severity"
)
if isinstance(flag_severity, (str, FlagSeverity)):
return flag_severity
raise ValueError("Missing flag severity.")
def get_reason(self, **kwargs) -> str:
"""Get the flag reason."""
reason = kwargs.get("reason", None) or getattr(self, "reason")
if isinstance(reason, str):
return reason.format(**kwargs)
raise ValueError("Missing flag reason.")
@abstractmethod
def get_flag_targets(
self, reading: Reading, level: Optional[Level] = None, **kwargs
) -> Iterable[EntityType]:
"""Get flag targets.
Parameters
----------
reading
The reading to which the targets are associated.
level
The level associated with the targets (if needed).
kwargs
Keyword arguments from which the flag targets are to be extracted.
Returns
-------
Iterable[EntityType]
An iterable of the flag targets.
"""
raise NotImplementedError
def get_flagging_function(self) -> Optional[Callable[..., bool]]:
"""Get the flagging function."""
# unbind bound methods
func = self.flagging_function
if func is not None and hasattr(func, "__func__"):
return func.__func__ # type: ignore
return func
def get_flagging_functions(self) -> FlaggingFunctionGeneratorType:
"""Get all flagging functions associated with this step."""
if func := self.get_flagging_function():
yield func, {}
members = inspect.getmembers(self, predicate=inspect.isroutine)
for _, func in members:
if func is not None and hasattr(func, "__flagging_function__"):
yield func, func.__flag_kwargs__ # type: ignore
def set_flag_kwargs(self, **kwargs):
"""Set keyword arguments inside flagging function.
Parameters
----------
kwargs
The keyword arguments to be added inside the flagging function
keyword arguments.
"""
_, parent, *_ = inspect.stack()
getattr(self, parent.function).__flag_kwargs__.update(kwargs)
def get_flag(self, **kwargs) -> Flag:
"""Get the flag corresponding to the flag step."""
(all_kwargs := self.kwargs.copy()).update(kwargs)
return Flag(
| """Data entity flag module."""
def flag(_func=None, **kwargs):
"""Decorate a function as a flagging function."""
def wrapper(func):
func.__flagging_function__ = True
func.__flag_kwargs__ = {
**kwargs,
**getattr(func, "__flag_kwargs__", {}),
}
return func
if _func is None:
return wrapper
return wrapper(_func)
FlaggingFunctionGeneratorType = Generator[
Tuple[Callable[..., bool], Dict[str, Any]], None, None
]
class FlagStepMixin(TaskMixin, metaclass=ABCMeta):
"""A flag mix in class."""
#: The name of the flag
flag_name: Union[AV, str]
#: The type of the flag
flag_type: Union[FlagType, str]
# The severity of the flag
flag_severity: Union[FlagSeverity, str]
#: The detailed reason of the flag
reason: str
#: The stop_processing status of the flag step
stop_processing: bool = False
#: The flagging function
flagging_function: Optional[Callable[..., bool]] = None
def __init__(self, *args, **kwargs):
kwargs = set_attributes_from_kwargs(
self,
"task_name",
"flag_name",
"flag_type",
"flag_severity",
"reason",
"stop_processing",
"flagging_function",
**kwargs,
)
self.kwargs = kwargs
super().__init__(*args, **kwargs)
def get_flag_name(self, **kwargs) -> Union[str, AV]:
"""Get the flag name."""
flag_name = kwargs.get("flag_name", None) or getattr(self, "flag_name")
if isinstance(flag_name, (str, AV)):
return flag_name.format(**kwargs)
raise ValueError("Missing flag name.")
def get_flag_type(self, **kwargs) -> Union[str, FlagType]:
"""Get the flag type."""
flag_type = kwargs.get("flag_type", None) or getattr(self, "flag_type")
if isinstance(flag_type, (str, FlagType)):
return flag_type
raise ValueError("Missing flag type.")
def get_flag_severity(self, **kwargs) -> Union[str, FlagSeverity]:
"""Get the flag severity."""
flag_severity = kwargs.get("flag_severity", None) or getattr(
self, "flag_severity"
)
if isinstance(flag_severity, (str, FlagSeverity)):
return flag_severity
raise ValueError("Missing flag severity.")
def get_reason(self, **kwargs) -> str:
"""Get the flag reason."""
reason = kwargs.get("reason", None) or getattr(self, "reason")
if isinstance(reason, str):
return reason.format(**kwargs)
raise ValueError("Missing flag reason.")
@abstractmethod
def get_flag_targets(
self, reading: Reading, level: Optional[Level] = None, **kwargs
) -> Iterable[EntityType]:
"""Get flag targets.
Parameters
----------
reading
The reading to which the targets are associated.
level
The level associated with the targets (if needed).
kwargs
Keyword arguments from which the flag targets are to be extracted.
Returns
-------
Iterable[EntityType]
An iterable of the flag targets.
"""
raise NotImplementedError
def get_flagging_function(self) -> Optional[Callable[..., bool]]:
"""Get the flagging function."""
# unbind bound methods
func = self.flagging_function
if func is not None and hasattr(func, "__func__"):
return func.__func__ # type: ignore
return func
def get_flagging_functions(self) -> FlaggingFunctionGeneratorType:
"""Get all flagging functions associated with this step."""
if func := self.get_flagging_function():
yield func, {}
members = inspect.getmembers(self, predicate=inspect.isroutine)
for _, func in members:
if func is not None and hasattr(func, "__flagging_function__"):
yield func, func.__flag_kwargs__ # type: ignore
def set_flag_kwargs(self, **kwargs):
"""Set keyword arguments inside flagging function.
Parameters
----------
kwargs
The keyword arguments to be added inside the flagging function
keyword arguments.
"""
_, parent, *_ = inspect.stack()
getattr(self, parent.function).__flag_kwargs__.update(kwargs)
def get_flag(self, **kwargs) -> Flag:
"""Get the flag corresponding to the flag step."""
(all_kwargs := self.kwargs.copy()).update(kwargs)
return Flag( | id_=FlagId( | 2 | 2023-11-14 10:06:46+00:00 | 8k |
runDMCA/home-assistant-mazda | custom_components/mazda/pymazda/sensordata/sensor_data_builder.py | [
{
"identifier": "BackgroundEventList",
"path": "custom_components/mazda/pymazda/sensordata/background_event_list.py",
"snippet": "class BackgroundEventList: # noqa: D101\n def __init__(self): # noqa: D107\n self.background_events = []\n\n def randomize(self, sensor_collection_start_timest... | import datetime # noqa: D100
import random
from .background_event_list import BackgroundEventList
from .key_event_list import KeyEventList
from .performance_test_results import PerformanceTestResults
from .sensor_data_encryptor import SensorDataEncryptor
from .sensor_data_util import feistel_cipher, timestamp_to_millis
from .system_info import SystemInfo
from .touch_event_list import TouchEventList | 3,797 |
SDK_VERSION = "2.2.3"
class SensorDataBuilder: # noqa: D101
def __init__(self): # noqa: D107
self.sensor_collection_start_timestamp = datetime.datetime.now(datetime.UTC)
self.device_info_time = random.randrange(3, 8) * 1000
self.system_info = SystemInfo()
self.system_info.randomize()
self.touch_event_list = TouchEventList()
self.key_event_list = KeyEventList()
self.background_event_list = BackgroundEventList()
self.performance_test_results = PerformanceTestResults()
self.performance_test_results.randomize()
|
SDK_VERSION = "2.2.3"
class SensorDataBuilder: # noqa: D101
def __init__(self): # noqa: D107
self.sensor_collection_start_timestamp = datetime.datetime.now(datetime.UTC)
self.device_info_time = random.randrange(3, 8) * 1000
self.system_info = SystemInfo()
self.system_info.randomize()
self.touch_event_list = TouchEventList()
self.key_event_list = KeyEventList()
self.background_event_list = BackgroundEventList()
self.performance_test_results = PerformanceTestResults()
self.performance_test_results.randomize()
| self.sensor_data_encryptor = SensorDataEncryptor() | 3 | 2023-11-14 01:42:43+00:00 | 8k |
ubertidavide/fastbots | fastbots/firefox_bot.py | [
{
"identifier": "config",
"path": "fastbots/config.py",
"snippet": "class DriverType(Enum):\n FIREFOX = 1\n CHROME = 2\nENV_DEVELOPMENT: str = 'development'\nENV_RELEASE: str = 'release'\nLOG_LEVEL: int = config('LOGLEVEL', default=logging.DEBUG, cast=int)\nENV: str = config('ENV', default=ENV_DEV... | import json
import logging
from pathlib import Path
from datetime import datetime
from seleniumwire.webdriver import Firefox
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.remote.webdriver import WebDriver
from fastbots import config, Bot | 4,456 |
logger = logging.getLogger(__name__)
class FirefoxBot(Bot):
"""
Firefox Bot
Class representing the Firefox Bot implementation.
Attributes:
_driver (WebDriver): The WebDriver instance for Firefox.
_wait (WebDriverWait): The WebDriverWait instance for Firefox.
Methods:
__init__(): Initializes all attributes of the Firefox Bot instance.
save_screenshot(): Saves the browser's screenshot to a PNG file.
__load_preferences__(): Loads Firefox preferences from a JSON file.
__load_options__(): Loads Firefox options, including user agent and download directory.
__load_driver__(): Loads and configures options for the Firefox driver.
Example:
```python
with FirefoxBot() as bot:
bot.save_screenshot()
```
"""
def __init__(self) -> None:
"""
Initializes all attributes of the Firefox Bot instance.
"""
super().__init__()
# Load the configured driver
self._driver: WebDriver = self.__load_driver__()
# Default wait
|
logger = logging.getLogger(__name__)
class FirefoxBot(Bot):
"""
Firefox Bot
Class representing the Firefox Bot implementation.
Attributes:
_driver (WebDriver): The WebDriver instance for Firefox.
_wait (WebDriverWait): The WebDriverWait instance for Firefox.
Methods:
__init__(): Initializes all attributes of the Firefox Bot instance.
save_screenshot(): Saves the browser's screenshot to a PNG file.
__load_preferences__(): Loads Firefox preferences from a JSON file.
__load_options__(): Loads Firefox options, including user agent and download directory.
__load_driver__(): Loads and configures options for the Firefox driver.
Example:
```python
with FirefoxBot() as bot:
bot.save_screenshot()
```
"""
def __init__(self) -> None:
"""
Initializes all attributes of the Firefox Bot instance.
"""
super().__init__()
# Load the configured driver
self._driver: WebDriver = self.__load_driver__()
# Default wait | self._wait: WebDriverWait = WebDriverWait(driver=self._driver, timeout=config.SELENIUM_DEFAULT_WAIT, poll_frequency=1) | 0 | 2023-11-16 00:12:09+00:00 | 8k |
intel/llm-on-ray | inference/api_openai_backend/router_app.py | [
{
"identifier": "OpenAIHTTPException",
"path": "inference/api_openai_backend/request_handler.py",
"snippet": "class OpenAIHTTPException(Exception):\n def __init__(\n self,\n status_code: int,\n message: str,\n type: str = \"Unknown\",\n ) -> None:\n self.status_c... | import os
import uuid
import async_timeout
from typing import AsyncGenerator, List
from fastapi import FastAPI, status
from fastapi import Response as FastAPIResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import Response, StreamingResponse
from logger import get_logger
from .request_handler import OpenAIHTTPException, openai_exception_handler
from .query_client import RouterQueryClient
from .openai_protocol import Prompt, ModelResponse, CompletionRequest, ChatCompletionRequest
from .openai_protocol import (
ChatCompletionResponse,
CompletionResponse,
DeltaChoices,
DeltaContent,
DeltaEOS,
DeltaRole,
ChatMessage,
ChatCompletionResponseChoice,
ModelList,
ModelCard,
CompletionResponseChoice,
UsageInfo,
) | 4,346 | TIMEOUT = float(os.environ.get("ROUTER_HTTP_TIMEOUT", 600))
def init() -> FastAPI:
router_app = FastAPI()
router_app.add_exception_handler(OpenAIHTTPException, openai_exception_handler)
router_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
return router_app
router_app = init()
async def _completions_wrapper(
completion_id: str,
body: CompletionRequest,
response: Response,
generator: AsyncGenerator[ModelResponse, None],
) -> AsyncGenerator[str, None]:
had_error = False
async with async_timeout.timeout(TIMEOUT):
all_results = []
async for results in generator:
for subresult in results.unpack():
all_results.append(subresult)
subresult_dict = subresult.dict()
if subresult_dict.get("error"):
response.status_code = subresult_dict["error"]["code"]
# Drop finish reason as OpenAI doesn't expect it
# for errors in streaming
subresult_dict["finish_reason"] = None
logger.error(f"{subresult_dict['error']}")
all_results.pop()
had_error = True
yield "data: " + ModelResponse(
**subresult_dict
).json() + "\n\n"
# Return early in case of an error
break
choices = [
CompletionResponseChoice(
index=0,
text=subresult_dict["generated_text"] or "",
finish_reason=subresult_dict["finish_reason"],
)
]
usage = None
if subresult_dict["finish_reason"]:
usage = (
UsageInfo.from_response(
ModelResponse.merge_stream(*all_results)
)
if all_results
else None
)
yield "data: " + CompletionResponse(
id=completion_id,
object="text_completion",
model=body.model,
choices=choices,
usage=usage,
).json() + "\n\n"
if had_error:
# Return early in case of an error
break
yield "data: [DONE]\n\n"
async def _chat_completions_wrapper(
completion_id: str,
body: ChatCompletionRequest,
response: Response,
generator: AsyncGenerator[ModelResponse, None],
) -> AsyncGenerator[str, None]:
had_error = False
async with async_timeout.timeout(TIMEOUT):
finish_reason = None
choices: List[DeltaChoices] = [
DeltaChoices(
delta=DeltaRole(role="assistant"),
index=0,
finish_reason=None,
)
]
yield "data: " + ChatCompletionResponse(
id=completion_id,
object="chat.completion.chunk",
model=body.model,
choices=choices,
usage=None,
).json() + "\n\n"
all_results = []
async for results in generator:
for subresult in results.unpack():
all_results.append(subresult)
subresult_dict = subresult.dict()
if subresult_dict.get("error"):
response.status_code = subresult_dict["error"]["code"]
logger.error(f"{subresult_dict['error']}")
# Drop finish reason as OpenAI doesn't expect it
# for errors in streaming
subresult_dict["finish_reason"] = None
all_results.pop()
had_error = True
yield "data: " + ModelResponse(
**subresult_dict
).json() + "\n\n"
# Return early in case of an error
break
else:
finish_reason = subresult_dict["finish_reason"]
choices: List[DeltaChoices] = [
DeltaChoices(
| #
# Copyright 2023 The LLM-on-Ray Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ===========================================================================
#
# This file is adapted from
# https://github.com/ray-project/ray-llm/blob/b3560aa55dadf6978f0de0a6f8f91002a5d2bed1/aviary/backend/server/routers/router_app.py
# Copyright 2023 Anyscale
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logger = get_logger(__name__)
# timeout in 10 minutes. Streaming can take longer than 3 min
TIMEOUT = float(os.environ.get("ROUTER_HTTP_TIMEOUT", 600))
def init() -> FastAPI:
router_app = FastAPI()
router_app.add_exception_handler(OpenAIHTTPException, openai_exception_handler)
router_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
return router_app
router_app = init()
async def _completions_wrapper(
completion_id: str,
body: CompletionRequest,
response: Response,
generator: AsyncGenerator[ModelResponse, None],
) -> AsyncGenerator[str, None]:
had_error = False
async with async_timeout.timeout(TIMEOUT):
all_results = []
async for results in generator:
for subresult in results.unpack():
all_results.append(subresult)
subresult_dict = subresult.dict()
if subresult_dict.get("error"):
response.status_code = subresult_dict["error"]["code"]
# Drop finish reason as OpenAI doesn't expect it
# for errors in streaming
subresult_dict["finish_reason"] = None
logger.error(f"{subresult_dict['error']}")
all_results.pop()
had_error = True
yield "data: " + ModelResponse(
**subresult_dict
).json() + "\n\n"
# Return early in case of an error
break
choices = [
CompletionResponseChoice(
index=0,
text=subresult_dict["generated_text"] or "",
finish_reason=subresult_dict["finish_reason"],
)
]
usage = None
if subresult_dict["finish_reason"]:
usage = (
UsageInfo.from_response(
ModelResponse.merge_stream(*all_results)
)
if all_results
else None
)
yield "data: " + CompletionResponse(
id=completion_id,
object="text_completion",
model=body.model,
choices=choices,
usage=usage,
).json() + "\n\n"
if had_error:
# Return early in case of an error
break
yield "data: [DONE]\n\n"
async def _chat_completions_wrapper(
completion_id: str,
body: ChatCompletionRequest,
response: Response,
generator: AsyncGenerator[ModelResponse, None],
) -> AsyncGenerator[str, None]:
had_error = False
async with async_timeout.timeout(TIMEOUT):
finish_reason = None
choices: List[DeltaChoices] = [
DeltaChoices(
delta=DeltaRole(role="assistant"),
index=0,
finish_reason=None,
)
]
yield "data: " + ChatCompletionResponse(
id=completion_id,
object="chat.completion.chunk",
model=body.model,
choices=choices,
usage=None,
).json() + "\n\n"
all_results = []
async for results in generator:
for subresult in results.unpack():
all_results.append(subresult)
subresult_dict = subresult.dict()
if subresult_dict.get("error"):
response.status_code = subresult_dict["error"]["code"]
logger.error(f"{subresult_dict['error']}")
# Drop finish reason as OpenAI doesn't expect it
# for errors in streaming
subresult_dict["finish_reason"] = None
all_results.pop()
had_error = True
yield "data: " + ModelResponse(
**subresult_dict
).json() + "\n\n"
# Return early in case of an error
break
else:
finish_reason = subresult_dict["finish_reason"]
choices: List[DeltaChoices] = [
DeltaChoices( | delta=DeltaContent( | 10 | 2023-11-13 05:08:21+00:00 | 8k |
believethehype/nostrdvm | nostr_dvm/tasks/textextraction_whisperx.py | [
{
"identifier": "check_server_status",
"path": "nostr_dvm/backends/nova_server/utils.py",
"snippet": "def check_server_status(jobID, address) -> str | pd.DataFrame:\n headers = {'Content-type': 'application/x-www-form-urlencoded'}\n url_status = 'http://' + address + '/job_status'\n url_log = '... | import json
import os
import time
from multiprocessing.pool import ThreadPool
from nostr_dvm.backends.nova_server.utils import check_server_status, send_request_to_server, send_file_to_server
from nostr_dvm.interfaces.dvmtaskinterface import DVMTaskInterface, process_venv
from nostr_dvm.utils.admin_utils import AdminConfig
from nostr_dvm.utils.dvmconfig import DVMConfig, build_default_config
from nostr_dvm.utils.mediasource_utils import organize_input_media_data
from nostr_dvm.utils.nip89_utils import NIP89Config, check_and_set_d_tag
from nostr_dvm.utils.definitions import EventDefinitions | 6,178 | media_format = "audio/mp3"
for tag in event.tags():
if tag.as_vec()[0] == 'i':
input_type = tag.as_vec()[2]
if input_type == "url":
url = tag.as_vec()[1]
elif tag.as_vec()[0] == 'param':
print("Param: " + tag.as_vec()[1] + ": " + tag.as_vec()[2])
if tag.as_vec()[1] == "alignment":
alignment = tag.as_vec()[2]
elif tag.as_vec()[1] == "model":
model = tag.as_vec()[2]
elif tag.as_vec()[1] == "range":
try:
t = time.strptime(tag.as_vec()[2], "%H:%M:%S")
seconds = t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec
start_time = float(seconds)
except:
try:
t = time.strptime(tag.as_vec()[2], "%M:%S")
seconds = t.tm_min * 60 + t.tm_sec
start_time = float(seconds)
except:
start_time = tag.as_vec()[2]
try:
t = time.strptime(tag.as_vec()[3], "%H:%M:%S")
seconds = t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec
end_time = float(seconds)
except:
try:
t = time.strptime(tag.as_vec()[3], "%M:%S")
seconds = t.tm_min * 60 + t.tm_sec
end_time = float(seconds)
except:
end_time = float(tag.as_vec()[3])
filepath = organize_input_media_data(url, input_type, start_time, end_time, dvm_config, client, True,
media_format)
path_on_server = send_file_to_server(os.path.realpath(filepath), self.options['server'])
io_input = {
"id": "audio",
"type": "input",
"src": "file:stream",
"uri": path_on_server
}
io_output = {
"id": "transcript",
"type": "output",
"src": "request:annotation:free"
}
request_form['data'] = json.dumps([io_input, io_output])
options = {
"model": model,
"alignment_mode": alignment,
}
request_form['options'] = json.dumps(options)
return request_form
def process(self, request_form):
try:
# Call the process route of NOVA-Server with our request form.
response = send_request_to_server(request_form, self.options['server'])
if bool(json.loads(response)['success']):
print("Job " + request_form['jobID'] + " sent to server")
pool = ThreadPool(processes=1)
thread = pool.apply_async(check_server_status, (request_form['jobID'], self.options['server']))
print("Wait for results of server...")
result = thread.get()
return result
except Exception as e:
raise Exception(e)
# We build an example here that we can call by either calling this file directly from the main directory,
# or by adding it to our playground. You can call the example and adjust it to your needs or redefine it in the
# playground or elsewhere
def build_example(name, identifier, admin_config, server_address):
dvm_config = build_default_config(identifier)
dvm_config.USE_OWN_VENV = False
admin_config.LUD16 = dvm_config.LN_ADDRESS
# A module might have options it can be initialized with, here we set a default model, and the server
# address it should use. These parameters can be freely defined in the task component
options = {'default_model': "base", 'server': server_address}
nip89info = {
"name": name,
"image": "https://image.nostr.build/c33ca6fc4cc038ca4adb46fdfdfda34951656f87ee364ef59095bae1495ce669.jpg",
"about": "I extract text from media files with WhisperX",
"encryptionSupported": True,
"cashuAccepted": True,
"nip90Params": {
"model": {
"required": False,
"values": ["base", "tiny", "small", "medium", "large-v1", "large-v2", "tiny.en", "base.en", "small.en",
"medium.en"]
},
"alignment": {
"required": False,
"values": ["raw", "segment", "word"]
}
}
}
nip89config = NIP89Config()
nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"])
nip89config.CONTENT = json.dumps(nip89info)
return SpeechToTextWhisperX(name=name, dvm_config=dvm_config, nip89config=nip89config,
admin_config=admin_config, options=options)
if __name__ == '__main__':
|
"""
This File contains a Module to transform A media file input on n-server and receive results back.
Accepted Inputs: Url to media file (url)
Outputs: Transcribed text
"""
class SpeechToTextWhisperX(DVMTaskInterface):
KIND: int = EventDefinitions.KIND_NIP90_EXTRACT_TEXT
TASK: str = "speech-to-text"
FIX_COST: float = 10
PER_UNIT_COST: float = 0.1
def __init__(self, name, dvm_config: DVMConfig, nip89config: NIP89Config,
admin_config: AdminConfig = None, options=None):
super().__init__(name, dvm_config, nip89config, admin_config, options)
def is_input_supported(self, tags, client=None, dvm_config=None):
for tag in tags:
if tag.as_vec()[0] == 'i':
input_value = tag.as_vec()[1]
input_type = tag.as_vec()[2]
if input_type != "url":
return False
elif tag.as_vec()[0] == 'output':
output = tag.as_vec()[1]
if output == "" or not (output == "text/plain"):
print("Output format not supported, skipping..")
return False
return True
def create_request_from_nostr_event(self, event, client=None, dvm_config=None):
request_form = {"jobID": event.id().to_hex() + "_" + self.NAME.replace(" ", ""),
"trainerFilePath": r'modules\whisperx\whisperx_transcript.trainer'}
if self.options.get("default_model"):
model = self.options['default_model']
else:
model = "base"
if self.options.get("alignment"):
alignment = self.options['alignment']
else:
alignment = "raw"
url = ""
input_type = "url"
start_time = 0
end_time = 0
media_format = "audio/mp3"
for tag in event.tags():
if tag.as_vec()[0] == 'i':
input_type = tag.as_vec()[2]
if input_type == "url":
url = tag.as_vec()[1]
elif tag.as_vec()[0] == 'param':
print("Param: " + tag.as_vec()[1] + ": " + tag.as_vec()[2])
if tag.as_vec()[1] == "alignment":
alignment = tag.as_vec()[2]
elif tag.as_vec()[1] == "model":
model = tag.as_vec()[2]
elif tag.as_vec()[1] == "range":
try:
t = time.strptime(tag.as_vec()[2], "%H:%M:%S")
seconds = t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec
start_time = float(seconds)
except:
try:
t = time.strptime(tag.as_vec()[2], "%M:%S")
seconds = t.tm_min * 60 + t.tm_sec
start_time = float(seconds)
except:
start_time = tag.as_vec()[2]
try:
t = time.strptime(tag.as_vec()[3], "%H:%M:%S")
seconds = t.tm_hour * 60 * 60 + t.tm_min * 60 + t.tm_sec
end_time = float(seconds)
except:
try:
t = time.strptime(tag.as_vec()[3], "%M:%S")
seconds = t.tm_min * 60 + t.tm_sec
end_time = float(seconds)
except:
end_time = float(tag.as_vec()[3])
filepath = organize_input_media_data(url, input_type, start_time, end_time, dvm_config, client, True,
media_format)
path_on_server = send_file_to_server(os.path.realpath(filepath), self.options['server'])
io_input = {
"id": "audio",
"type": "input",
"src": "file:stream",
"uri": path_on_server
}
io_output = {
"id": "transcript",
"type": "output",
"src": "request:annotation:free"
}
request_form['data'] = json.dumps([io_input, io_output])
options = {
"model": model,
"alignment_mode": alignment,
}
request_form['options'] = json.dumps(options)
return request_form
def process(self, request_form):
try:
# Call the process route of NOVA-Server with our request form.
response = send_request_to_server(request_form, self.options['server'])
if bool(json.loads(response)['success']):
print("Job " + request_form['jobID'] + " sent to server")
pool = ThreadPool(processes=1)
thread = pool.apply_async(check_server_status, (request_form['jobID'], self.options['server']))
print("Wait for results of server...")
result = thread.get()
return result
except Exception as e:
raise Exception(e)
# We build an example here that we can call by either calling this file directly from the main directory,
# or by adding it to our playground. You can call the example and adjust it to your needs or redefine it in the
# playground or elsewhere
def build_example(name, identifier, admin_config, server_address):
dvm_config = build_default_config(identifier)
dvm_config.USE_OWN_VENV = False
admin_config.LUD16 = dvm_config.LN_ADDRESS
# A module might have options it can be initialized with, here we set a default model, and the server
# address it should use. These parameters can be freely defined in the task component
options = {'default_model': "base", 'server': server_address}
nip89info = {
"name": name,
"image": "https://image.nostr.build/c33ca6fc4cc038ca4adb46fdfdfda34951656f87ee364ef59095bae1495ce669.jpg",
"about": "I extract text from media files with WhisperX",
"encryptionSupported": True,
"cashuAccepted": True,
"nip90Params": {
"model": {
"required": False,
"values": ["base", "tiny", "small", "medium", "large-v1", "large-v2", "tiny.en", "base.en", "small.en",
"medium.en"]
},
"alignment": {
"required": False,
"values": ["raw", "segment", "word"]
}
}
}
nip89config = NIP89Config()
nip89config.DTAG = check_and_set_d_tag(identifier, name, dvm_config.PRIVATE_KEY, nip89info["image"])
nip89config.CONTENT = json.dumps(nip89info)
return SpeechToTextWhisperX(name=name, dvm_config=dvm_config, nip89config=nip89config,
admin_config=admin_config, options=options)
if __name__ == '__main__': | process_venv(SpeechToTextWhisperX) | 4 | 2023-11-17 18:32:56+00:00 | 8k |
zouXH-god/meme_web | meme_generator/app.py | [
{
"identifier": "meme_config",
"path": "meme_generator/config.py",
"snippet": "class MemeConfig(BaseModel):\nclass ResourceConfig(BaseModel):\nclass GifConfig(BaseModel):\nclass TranslatorConfig(BaseModel):\nclass ServerConfig(BaseModel):\nclass LogConfig(BaseModel):\nclass Config(BaseModel, extra=Extra... | import base64
import json
import filetype
import httpx
import requests
import uvicorn
from typing import Any, Dict, List, Literal, Optional, Tuple
from fastapi import Depends, FastAPI, Form, HTTPException, Response, UploadFile
from fastapi.responses import HTMLResponse
from pil_utils.types import ColorType, FontStyle, FontWeight
from pydantic import BaseModel, ValidationError
from meme_generator.config import meme_config
from meme_generator.exception import MemeGeneratorException, NoSuchMeme
from meme_generator.log import LOGGING_CONFIG, setup_logger
from meme_generator.manager import get_meme, get_meme_keys, get_memes, get_meme_keywords
from meme_generator.meme import Meme, MemeArgsModel
from meme_generator.utils import TextProperties, render_meme_list | 4,398 | async with httpx.AsyncClient() as client:
response = await client.get(resize_url + url, timeout=60)
content = response.content
media_type = str(filetype.guess_mime(content)) or "text/plain"
return Response(content=content, media_type=media_type)
@app.post("/memes/render_list")
def _(params: RenderMemeListRequest = RenderMemeListRequest()):
try:
meme_list = [
(
get_meme(p.meme_key),
TextProperties(
fill=p.fill,
style=p.style,
weight=p.weight,
stroke_width=p.stroke_width,
stroke_fill=p.stroke_fill,
),
)
for p in params.meme_list
]
except NoSuchMeme as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
result = render_meme_list(
meme_list,
order_direction=params.order_direction,
columns=params.columns,
column_align=params.column_align,
item_padding=params.item_padding,
image_padding=params.image_padding,
bg_color=params.bg_color,
fontsize=params.fontsize,
fontname=params.fontname,
fallback_fonts=params.fallback_fonts,
)
content = result.getvalue()
media_type = str(filetype.guess_mime(content)) or "text/plain"
return Response(content=content, media_type=media_type)
@app.get("/memes/keywords")
def _():
return get_meme_keywords()
@app.get("/memes/keys")
def _():
return get_meme_keys()
@app.get("/memes/{key}/info")
def _(key: str):
try:
meme = get_meme(key)
except NoSuchMeme as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
args_model = (
meme.params_type.args_type.model
if meme.params_type.args_type
else MemeArgsModel
)
properties: Dict[str, Dict[str, Any]] = (
args_model.schema().get("properties", {}).copy()
)
properties.pop("user_infos")
return MemeInfoResponse(
key=meme.key,
keywords=meme.keywords,
patterns=meme.patterns,
params=MemeParamsResponse(
min_images=meme.params_type.min_images,
max_images=meme.params_type.max_images,
min_texts=meme.params_type.min_texts,
max_texts=meme.params_type.max_texts,
default_texts=meme.params_type.default_texts,
args=[
MemeArgsResponse(
name=name,
type=info.get("type", ""),
description=info.get("description"),
default=info.get("default"),
enum=info.get("enum"),
)
for name, info in properties.items()
],
),
)
@app.get("/memes/{key}/preview")
async def _(key: str):
try:
meme = get_meme(key)
# 返回值为byteIO
result = await meme.generate_preview()
except MemeGeneratorException as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
content = result.getvalue()
media_type = str(filetype.guess_mime(content)) or "text/plain"
return Response(content=content, media_type=media_type)
@app.post("/memes/{key}/parse_args")
async def _(key: str, args=None):
if args is None:
args = []
try:
meme = get_meme(key)
return meme.parse_args(args)
except MemeGeneratorException as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
for meme in sorted(get_memes(), key=lambda meme: meme.key):
register_router(meme)
def run_server():
register_routers()
uvicorn.run(
app,
|
app = FastAPI()
class MemeArgsResponse(BaseModel):
name: str
type: str
description: Optional[str] = None
default: Optional[Any] = None
enum: Optional[List[Any]] = None
class MemeParamsResponse(BaseModel):
min_images: int
max_images: int
min_texts: int
max_texts: int
default_texts: List[str]
args: List[MemeArgsResponse]
class MemeInfoResponse(BaseModel):
key: str
keywords: List[str]
patterns: List[str]
params: MemeParamsResponse
def register_router(meme: Meme):
if args_type := meme.params_type.args_type:
args_model = args_type.model
else:
args_model = MemeArgsModel
def args_checker(args: Optional[str] = Form(default=str(args_model().json()))):
if not args:
return MemeArgsModel()
try:
model = args_model.parse_raw(args)
except ValidationError as e:
raise HTTPException(status_code=552, detail=str(e))
return model
@app.post(f"/memes/{meme.key}/")
async def _(
images: List[UploadFile] = [],
images_base64: List[str] = [],
texts: List[str] = meme.params_type.default_texts,
texts_json: List[str] = [],
res: List[str] = [],
args: args_model = Depends(args_checker), # type: ignore
):
if texts_json:
texts = json.loads(texts_json[0])
imgs: List[bytes] = []
for image in images:
imgs.append(await image.read())
if images_base64:
for image_base64 in json.loads(images_base64[0]):
imgs.append(base64.b64decode(image_base64))
texts = [text for text in texts if text]
assert isinstance(args, args_model)
try:
result = await meme(images=imgs, texts=texts, args=args.dict())
except MemeGeneratorException as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
content = result.getvalue()
print(res)
if res:
return base64.b64encode(content)
media_type = str(filetype.guess_mime(content)) or "text/plain"
return Response(content=content, media_type=media_type)
class MemeKeyWithProperties(BaseModel):
meme_key: str
fill: ColorType = "black"
style: FontStyle = "normal"
weight: FontWeight = "normal"
stroke_width: int = 0
stroke_fill: Optional[ColorType] = None
default_meme_list = [
MemeKeyWithProperties(meme_key=meme.key)
for meme in sorted(get_memes(), key=lambda meme: meme.key)
]
class RenderMemeListRequest(BaseModel):
meme_list: List[MemeKeyWithProperties] = default_meme_list
order_direction: Literal["row", "column"] = "column"
columns: int = 4
column_align: Literal["left", "center", "right"] = "left"
item_padding: Tuple[int, int] = (15, 2)
image_padding: Tuple[int, int] = (50, 50)
bg_color: ColorType = "white"
fontsize: int = 30
fontname: str = ""
fallback_fonts: List[str] = []
def register_routers():
@app.get("/")
@app.get("/memes/make")
def _():
with open("templates/make.html", "r") as fp:
html = fp.read()
return HTMLResponse(html)
@app.get("/memes/get_img")
async def _(qq: str = "", url: str = ""):
if qq:
url = f"http://q1.qlogo.cn/g?b=qq&nk={qq}&s=640"
resize_url = ""
else:
resize_url = "https://api.s1f.top/img_resize?w=320&url="
async with httpx.AsyncClient() as client:
response = await client.get(resize_url + url, timeout=60)
content = response.content
media_type = str(filetype.guess_mime(content)) or "text/plain"
return Response(content=content, media_type=media_type)
@app.post("/memes/render_list")
def _(params: RenderMemeListRequest = RenderMemeListRequest()):
try:
meme_list = [
(
get_meme(p.meme_key),
TextProperties(
fill=p.fill,
style=p.style,
weight=p.weight,
stroke_width=p.stroke_width,
stroke_fill=p.stroke_fill,
),
)
for p in params.meme_list
]
except NoSuchMeme as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
result = render_meme_list(
meme_list,
order_direction=params.order_direction,
columns=params.columns,
column_align=params.column_align,
item_padding=params.item_padding,
image_padding=params.image_padding,
bg_color=params.bg_color,
fontsize=params.fontsize,
fontname=params.fontname,
fallback_fonts=params.fallback_fonts,
)
content = result.getvalue()
media_type = str(filetype.guess_mime(content)) or "text/plain"
return Response(content=content, media_type=media_type)
@app.get("/memes/keywords")
def _():
return get_meme_keywords()
@app.get("/memes/keys")
def _():
return get_meme_keys()
@app.get("/memes/{key}/info")
def _(key: str):
try:
meme = get_meme(key)
except NoSuchMeme as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
args_model = (
meme.params_type.args_type.model
if meme.params_type.args_type
else MemeArgsModel
)
properties: Dict[str, Dict[str, Any]] = (
args_model.schema().get("properties", {}).copy()
)
properties.pop("user_infos")
return MemeInfoResponse(
key=meme.key,
keywords=meme.keywords,
patterns=meme.patterns,
params=MemeParamsResponse(
min_images=meme.params_type.min_images,
max_images=meme.params_type.max_images,
min_texts=meme.params_type.min_texts,
max_texts=meme.params_type.max_texts,
default_texts=meme.params_type.default_texts,
args=[
MemeArgsResponse(
name=name,
type=info.get("type", ""),
description=info.get("description"),
default=info.get("default"),
enum=info.get("enum"),
)
for name, info in properties.items()
],
),
)
@app.get("/memes/{key}/preview")
async def _(key: str):
try:
meme = get_meme(key)
# 返回值为byteIO
result = await meme.generate_preview()
except MemeGeneratorException as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
content = result.getvalue()
media_type = str(filetype.guess_mime(content)) or "text/plain"
return Response(content=content, media_type=media_type)
@app.post("/memes/{key}/parse_args")
async def _(key: str, args=None):
if args is None:
args = []
try:
meme = get_meme(key)
return meme.parse_args(args)
except MemeGeneratorException as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
for meme in sorted(get_memes(), key=lambda meme: meme.key):
register_router(meme)
def run_server():
register_routers()
uvicorn.run(
app, | host=meme_config.server.host, | 0 | 2023-11-12 12:31:53+00:00 | 8k |
OKC13/General-Documents-Layout-parser | utils/datasets.py | [
{
"identifier": "xyxy2xywh",
"path": "utils/utils.py",
"snippet": "def xyxy2xywh(x):\n # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\n y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)\n y[:, 0] = (x[:, 0] + x[:, 2]) / ... | import glob
import math
import os
import random
import shutil
import time
import cv2
import numpy as np
import torch
from pathlib import Path
from threading import Thread
from PIL import Image, ExifTags
from torch.utils.data import Dataset
from tqdm import tqdm
from utils.utils import xyxy2xywh, xywh2xyxy
from skimage import io # conda install -c conda-forge scikit-image | 3,979 | nf += 1 # file found
# Create subdataset (a smaller dataset)
if create_datasubset and ns < 1E4:
if ns == 0:
create_folder(path='./datasubset')
os.makedirs('./datasubset/images')
exclude_classes = 43
if exclude_classes not in l[:, 0]:
ns += 1
# shutil.copy(src=self.img_files[i], dst='./datasubset/images/') # copy image
with open('./datasubset/images.txt', 'a') as f:
f.write(self.img_files[i] + '\n')
# Extract object detection boxes for a second stage classifier
if extract_bounding_boxes:
p = Path(self.img_files[i])
img = cv2.imread(str(p))
h, w = img.shape[:2]
for j, x in enumerate(l):
f = '%s%sclassifier%s%g_%g_%s' % (p.parent.parent, os.sep, os.sep, x[0], j, p.name)
if not os.path.exists(Path(f).parent):
os.makedirs(Path(f).parent) # make new output folder
b = x[1:] * [w, h, w, h] # box
b[2:] = b[2:].max() # rectangle to square
b[2:] = b[2:] * 1.3 + 30 # pad
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
assert cv2.imwrite(f, img[b[1]:b[3], b[0]:b[2]]), 'Failure extracting classifier boxes'
else:
ne += 1 # print('empty labels for image %s' % self.img_files[i]) # file empty
# os.system("rm '%s' '%s'" % (self.img_files[i], self.label_files[i])) # remove
pbar.desc = 'Caching labels %s (%g found, %g missing, %g empty, %g duplicate, for %g images)' % (
s, nf, nm, ne, nd, n)
assert nf > 0 or n == 20288, 'No labels found in %s. See %s' % (os.path.dirname(file) + os.sep, help_url)
if not labels_loaded and n > 1000:
print('Saving labels to %s for faster future loading' % np_labels_path)
np.save(np_labels_path, self.labels) # save for next time
# Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
if cache_images: # if training
gb = 0 # Gigabytes of cached images
pbar = tqdm(range(len(self.img_files)), desc='Caching images')
self.img_hw0, self.img_hw = [None] * n, [None] * n
for i in pbar: # max 10k images
self.imgs[i], self.img_hw0[i], self.img_hw[i] = load_image(self, i) # img, hw_original, hw_resized
gb += self.imgs[i].nbytes
pbar.desc = 'Caching images (%.1fGB)' % (gb / 1E9)
# Detect corrupted images https://medium.com/joelthchao/programmatically-detect-corrupted-image-8c1b2006c3d3
detect_corrupted_images = False
if detect_corrupted_images:
for file in tqdm(self.img_files, desc='Detecting corrupted images'):
try:
_ = io.imread(file)
except:
print('Corrupted image detected: %s' % file)
def __len__(self):
return len(self.img_files)
# def __iter__(self):
# self.count = -1
# print('ran dataset iter')
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
# return self
def __getitem__(self, index):
if self.image_weights:
index = self.indices[index]
hyp = self.hyp
if self.mosaic:
# Load mosaic
img, labels = load_mosaic(self, index)
shapes = None
else:
# Load image
img, (h0, w0), (h, w) = load_image(self, index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
# Load labels
labels = []
x = self.labels[index]
if x.size > 0:
# Normalized xywh to pixel xyxy format
labels = x.copy()
labels[:, 1] = ratio[0] * w * (x[:, 1] - x[:, 3] / 2) + pad[0] # pad width
labels[:, 2] = ratio[1] * h * (x[:, 2] - x[:, 4] / 2) + pad[1] # pad height
labels[:, 3] = ratio[0] * w * (x[:, 1] + x[:, 3] / 2) + pad[0]
labels[:, 4] = ratio[1] * h * (x[:, 2] + x[:, 4] / 2) + pad[1]
if self.augment:
# Augment imagespace
if not self.mosaic:
img, labels = random_affine(img, labels,
degrees=hyp['degrees'],
translate=hyp['translate'],
scale=hyp['scale'],
shear=hyp['shear'])
# Augment colorspace
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
# Apply cutouts
# if random.random() < 0.9:
# labels = cutout(img, labels)
nL = len(labels) # number of labels
if nL:
# convert xyxy to xywh
|
help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.dng']
vid_formats = ['.mov', '.avi', '.mp4']
# Get orientation exif tag
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
def exif_size(img):
# Returns exif-corrected PIL size
s = img.size # (width, height)
try:
rotation = dict(img._getexif().items())[orientation]
if rotation == 6: # rotation 270
s = (s[1], s[0])
elif rotation == 8: # rotation 90
s = (s[1], s[0])
except:
pass
return s
class LoadImages: # for inference
def __init__(self, path, img_size=416):
path = str(Path(path)) # os-agnostic
files = []
if os.path.isdir(path):
files = sorted(glob.glob(os.path.join(path, '*.*')))
elif os.path.isfile(path):
files = [path]
images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats]
videos = [x for x in files if os.path.splitext(x)[-1].lower() in vid_formats]
nI, nV = len(images), len(videos)
self.img_size = img_size
self.files = images + videos
self.nF = nI + nV # number of files
self.video_flag = [False] * nI + [True] * nV
self.mode = 'images'
if any(videos):
self.new_video(videos[0]) # new video
else:
self.cap = None
assert self.nF > 0, 'No images or videos found in ' + path
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nF:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = 'video'
ret_val, img0 = self.cap.read()
if not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nF: # last video
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
self.frame += 1
print('video %g/%g (%g/%g) %s: ' % (self.count + 1, self.nF, self.frame, self.nframes, path), end='')
else:
# Read image
self.count += 1
img0 = cv2.imread(path) # BGR
assert img0 is not None, 'Image Not Found ' + path
print('image %g/%g %s: ' % (self.count, self.nF, path), end='')
# Padded resize
img = letterbox(img0, new_shape=self.img_size)[0]
# Convert
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
img = np.ascontiguousarray(img)
# cv2.imwrite(path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image
return path, img, img0, self.cap
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nF # number of files
class LoadWebcam: # for inference
def __init__(self, pipe=0, img_size=416):
self.img_size = img_size
if pipe == '0':
pipe = 0 # local camera
# pipe = 'rtsp://192.168.1.64/1' # IP camera
# pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login
# pipe = 'rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa' # IP traffic camera
# pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
# https://answers.opencv.org/question/215996/changing-gstreamer-pipeline-to-opencv-in-pythonsolved/
# pipe = '"rtspsrc location="rtsp://username:password@192.168.1.64/1" latency=10 ! appsink' # GStreamer
# https://answers.opencv.org/question/200787/video-acceleration-gstremer-pipeline-in-videocapture/
# https://stackoverflow.com/questions/54095699/install-gstreamer-support-for-opencv-python-package # install help
# pipe = "rtspsrc location=rtsp://root:root@192.168.0.91:554/axis-media/media.amp?videocodec=h264&resolution=3840x2160 protocols=GST_RTSP_LOWER_TRANS_TCP ! rtph264depay ! queue ! vaapih264dec ! videoconvert ! appsink" # GStreamer
self.pipe = pipe
self.cap = cv2.VideoCapture(pipe) # video capture object
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if cv2.waitKey(1) == ord('q'): # q to quit
self.cap.release()
cv2.destroyAllWindows()
raise StopIteration
# Read frame
if self.pipe == 0: # local camera
ret_val, img0 = self.cap.read()
img0 = cv2.flip(img0, 1) # flip left-right
else: # IP camera
n = 0
while True:
n += 1
self.cap.grab()
if n % 30 == 0: # skip frames
ret_val, img0 = self.cap.retrieve()
if ret_val:
break
# Print
assert ret_val, 'Camera Error %s' % self.pipe
img_path = 'webcam.jpg'
print('webcam %g: ' % self.count, end='')
# Padded resize
img = letterbox(img0, new_shape=self.img_size)[0]
# Convert
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
img = np.ascontiguousarray(img)
return img_path, img, img0, None
def __len__(self):
return 0
class LoadStreams: # multiple IP or RTSP cameras
def __init__(self, sources='streams.txt', img_size=416):
self.mode = 'images'
self.img_size = img_size
if os.path.isfile(sources):
with open(sources, 'r') as f:
sources = [x.strip() for x in f.read().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs = [None] * n
self.sources = sources
for i, s in enumerate(sources):
# Start the thread to read frames from the video stream
print('%g/%g: %s... ' % (i + 1, n, s), end='')
cap = cv2.VideoCapture(0 if s == '0' else s)
assert cap.isOpened(), 'Failed to open %s' % s
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS) % 100
_, self.imgs[i] = cap.read() # guarantee first frame
thread = Thread(target=self.update, args=([i, cap]), daemon=True)
print(' success (%gx%g at %.2f FPS).' % (w, h, fps))
thread.start()
print('') # newline
# check for common shapes
s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0) # inference shapes
self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
if not self.rect:
print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
def update(self, index, cap):
# Read next stream frame in a daemon thread
n = 0
while cap.isOpened():
n += 1
# _, self.imgs[index] = cap.read()
cap.grab()
if n == 4: # read every 4th frame
_, self.imgs[index] = cap.retrieve()
n = 0
time.sleep(0.01) # wait time
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
img0 = self.imgs.copy()
if cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
# Letterbox
img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0]
# Stack
img = np.stack(img, 0)
# Convert
img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
img = np.ascontiguousarray(img)
return self.sources, img, img0, None
def __len__(self):
return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
class LoadImagesAndLabels(Dataset): # for training/testing
def __init__(self, path, img_size=416, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
cache_images=False, single_cls=False, pad=0.0):
try:
path = str(Path(path)) # os-agnostic
parent = str(Path(path).parent) + os.sep
if os.path.isfile(path): # file
with open(path, 'r') as f:
f = f.read().splitlines()
f = [x.replace('./', parent) if x.startswith('./') else x for x in f] # local to global path
elif os.path.isdir(path): # folder
f = glob.iglob(path + os.sep + '*.*')
else:
raise Exception('%s does not exist' % path)
self.img_files = [x.replace('/', os.sep) for x in f if os.path.splitext(x)[-1].lower() in img_formats]
except:
raise Exception('Error loading data from %s. See %s' % (path, help_url))
n = len(self.img_files)
assert n > 0, 'No images found in %s. See %s' % (path, help_url)
bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
nb = bi[-1] + 1 # number of batches
self.n = n # number of images
self.batch = bi # batch index of image
self.img_size = img_size
self.augment = augment
self.hyp = hyp
self.image_weights = image_weights
self.rect = False if image_weights else rect
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
# Define labels
self.label_files = [x.replace('images', 'labels').replace(os.path.splitext(x)[-1], '.txt')
for x in self.img_files]
# Rectangular Training https://github.com/ultralytics/yolov3/issues/232
if self.rect:
# Read image shapes (wh)
sp = path.replace('.txt', '') + '.shapes' # shapefile path
try:
with open(sp, 'r') as f: # read existing shapefile
s = [x.split() for x in f.read().splitlines()]
assert len(s) == n, 'Shapefile out of sync'
except:
s = [exif_size(Image.open(f)) for f in tqdm(self.img_files, desc='Reading image shapes')]
np.savetxt(sp, s, fmt='%g') # overwrites existing (if any)
# Sort by aspect ratio
s = np.array(s, dtype=np.float64)
ar = s[:, 1] / s[:, 0] # aspect ratio
irect = ar.argsort()
self.img_files = [self.img_files[i] for i in irect]
self.label_files = [self.label_files[i] for i in irect]
self.shapes = s[irect] # wh
ar = ar[irect]
# Set training image shapes
shapes = [[1, 1]] * nb
for i in range(nb):
ari = ar[bi == i]
mini, maxi = ari.min(), ari.max()
if maxi < 1:
shapes[i] = [maxi, 1]
elif mini > 1:
shapes[i] = [1, 1 / mini]
self.batch_shapes = np.ceil(np.array(shapes) * img_size / 32. + pad).astype(np.int) * 32
# Cache labels
self.imgs = [None] * n
self.labels = [np.zeros((0, 5), dtype=np.float32)] * n
create_datasubset, extract_bounding_boxes, labels_loaded = False, False, False
nm, nf, ne, ns, nd = 0, 0, 0, 0, 0 # number missing, found, empty, datasubset, duplicate
np_labels_path = str(Path(self.label_files[0]).parent) + '.npy' # saved labels in *.npy file
if os.path.isfile(np_labels_path):
s = np_labels_path # print string
x = np.load(np_labels_path, allow_pickle=True)
if len(x) == n:
self.labels = x
labels_loaded = True
else:
s = path.replace('images', 'labels')
pbar = tqdm(self.label_files)
for i, file in enumerate(pbar):
if labels_loaded:
l = self.labels[i]
# np.savetxt(file, l, '%g') # save *.txt from *.npy file
else:
try:
with open(file, 'r') as f:
l = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)
except:
nm += 1 # print('missing labels for image %s' % self.img_files[i]) # file missing
continue
if l.shape[0]:
assert l.shape[1] == 5, '> 5 label columns: %s' % file
assert (l >= 0).all(), 'negative labels: %s' % file
try:
assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels: %s' % file
except:
print('non-normalized or out of bounds coordinate labels: %s' % file)
if np.unique(l, axis=0).shape[0] < l.shape[0]: # duplicate rows
nd += 1 # print('WARNING: duplicate rows in %s' % self.label_files[i]) # duplicate rows
if single_cls:
l[:, 0] = 0 # force dataset into single-class mode
self.labels[i] = l
nf += 1 # file found
# Create subdataset (a smaller dataset)
if create_datasubset and ns < 1E4:
if ns == 0:
create_folder(path='./datasubset')
os.makedirs('./datasubset/images')
exclude_classes = 43
if exclude_classes not in l[:, 0]:
ns += 1
# shutil.copy(src=self.img_files[i], dst='./datasubset/images/') # copy image
with open('./datasubset/images.txt', 'a') as f:
f.write(self.img_files[i] + '\n')
# Extract object detection boxes for a second stage classifier
if extract_bounding_boxes:
p = Path(self.img_files[i])
img = cv2.imread(str(p))
h, w = img.shape[:2]
for j, x in enumerate(l):
f = '%s%sclassifier%s%g_%g_%s' % (p.parent.parent, os.sep, os.sep, x[0], j, p.name)
if not os.path.exists(Path(f).parent):
os.makedirs(Path(f).parent) # make new output folder
b = x[1:] * [w, h, w, h] # box
b[2:] = b[2:].max() # rectangle to square
b[2:] = b[2:] * 1.3 + 30 # pad
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
assert cv2.imwrite(f, img[b[1]:b[3], b[0]:b[2]]), 'Failure extracting classifier boxes'
else:
ne += 1 # print('empty labels for image %s' % self.img_files[i]) # file empty
# os.system("rm '%s' '%s'" % (self.img_files[i], self.label_files[i])) # remove
pbar.desc = 'Caching labels %s (%g found, %g missing, %g empty, %g duplicate, for %g images)' % (
s, nf, nm, ne, nd, n)
assert nf > 0 or n == 20288, 'No labels found in %s. See %s' % (os.path.dirname(file) + os.sep, help_url)
if not labels_loaded and n > 1000:
print('Saving labels to %s for faster future loading' % np_labels_path)
np.save(np_labels_path, self.labels) # save for next time
# Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
if cache_images: # if training
gb = 0 # Gigabytes of cached images
pbar = tqdm(range(len(self.img_files)), desc='Caching images')
self.img_hw0, self.img_hw = [None] * n, [None] * n
for i in pbar: # max 10k images
self.imgs[i], self.img_hw0[i], self.img_hw[i] = load_image(self, i) # img, hw_original, hw_resized
gb += self.imgs[i].nbytes
pbar.desc = 'Caching images (%.1fGB)' % (gb / 1E9)
# Detect corrupted images https://medium.com/joelthchao/programmatically-detect-corrupted-image-8c1b2006c3d3
detect_corrupted_images = False
if detect_corrupted_images:
for file in tqdm(self.img_files, desc='Detecting corrupted images'):
try:
_ = io.imread(file)
except:
print('Corrupted image detected: %s' % file)
def __len__(self):
return len(self.img_files)
# def __iter__(self):
# self.count = -1
# print('ran dataset iter')
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
# return self
def __getitem__(self, index):
if self.image_weights:
index = self.indices[index]
hyp = self.hyp
if self.mosaic:
# Load mosaic
img, labels = load_mosaic(self, index)
shapes = None
else:
# Load image
img, (h0, w0), (h, w) = load_image(self, index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
# Load labels
labels = []
x = self.labels[index]
if x.size > 0:
# Normalized xywh to pixel xyxy format
labels = x.copy()
labels[:, 1] = ratio[0] * w * (x[:, 1] - x[:, 3] / 2) + pad[0] # pad width
labels[:, 2] = ratio[1] * h * (x[:, 2] - x[:, 4] / 2) + pad[1] # pad height
labels[:, 3] = ratio[0] * w * (x[:, 1] + x[:, 3] / 2) + pad[0]
labels[:, 4] = ratio[1] * h * (x[:, 2] + x[:, 4] / 2) + pad[1]
if self.augment:
# Augment imagespace
if not self.mosaic:
img, labels = random_affine(img, labels,
degrees=hyp['degrees'],
translate=hyp['translate'],
scale=hyp['scale'],
shear=hyp['shear'])
# Augment colorspace
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
# Apply cutouts
# if random.random() < 0.9:
# labels = cutout(img, labels)
nL = len(labels) # number of labels
if nL:
# convert xyxy to xywh | labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) | 0 | 2023-11-16 08:37:10+00:00 | 8k |
embrake/Aquilify | aquilify/orm/sqlite3.py | [
{
"identifier": "MagicFilter",
"path": "aquilify/orm/filters/magic.py",
"snippet": "class MagicFilter(object):\n def __init__(self, query: str, variables: tuple = None, parameters: dict[str, object] = None) -> None:\n\n \"\"\"\n Magic filter used for advanced processing of sql queries\n... | import sqlite3
from .filters import MagicFilter
from .column import Column, ColumnType
from .constants import Types
from .exceptions import SessionExecuteError
from .table import Table, DynamicTable
from .utils.dict_factory import dict_factory
from .connection import DatabaseConnectionManager
from .transactions import TransactionContextManager, IsolationLevel
from typing import Callable, Union, Type | 3,881 |
class Typing(object):
"""
Namespace with type hints.
"""
AnyTable = Union[MagicFilter, DynamicTable, Table, Type[Table]]
NamespaceTable = Union[DynamicTable, Type[Table]]
AnyColumn = Union[Column, ColumnType]
class Sqlite3:
def __init__(self, path: str) -> None:
self.path = path
def get_path(self) -> str:
return self.path
def __str__(self) -> str:
return self.path
class Session(object):
def __init__(self, tables: list[Typing.NamespaceTable] = None, **kwargs) -> None:
"""
Creates a new session to work with the database.
:param path: Path to the database
:param tables: List of tables to be created during session initialization
:param kwargs: Other options for opening a database [ More details in `sqlite3.connect(...)` ]
"""
self._connection = DatabaseConnectionManager()._get_connection()
self._database = sqlite3.connect(self._connection.get_path(), **kwargs)
self._tables = tables or []
for table in self._tables:
self.create(table)
def create(self, table: Typing.NamespaceTable) -> None:
"""
Creates a new table in the database.
:param table: Table or dynamic table
:return: Nothing
"""
self._database.execute(f"CREATE TABLE IF NOT EXISTS {table.__tablename__} "
f"({', '.join([column.serialize() for column in table.columns().values()])})")
self._database.commit()
def clear(self, table: Typing.NamespaceTable) -> None:
"""
Clears the selected table.
:param table: Table or dynamic table
:return: Nothing
"""
self._database.execute(
f"DELETE FROM {table.__tablename__}"
)
self._database.commit()
def drop(self, table: Typing.NamespaceTable) -> None:
"""
Completely removes the table from the database.
:param table: Table or dynamic table
:return: Nothing
"""
self._database.execute(
f"DROP TABLE IF EXISTS {table.__tablename__}"
)
self._database.commit()
def insert(self, table: Table, replace: bool = False) -> None:
"""
Adds a new row to the table.
:param table: Initialized table object
:param replace: Will replace an existing row
:return: Nothing
"""
values = table.values
try:
self._database.execute(
f"INSERT {'OR REPLACE' if replace else ''} INTO {table.__tablename__} ({', '.join(values.keys())}) "
f"VALUES ({', '.join(['?'] * len(values))})", list(values.values())
)
self._database.commit()
return True
except Exception:
return False
def update(self, data: Typing.AnyTable, table: Table) -> None:
"""
Updates the selected rows in the table.
:param data: Initialized table object
:param table: Any type of table or magic filter
:return: Nothing
"""
if not isinstance(data, (MagicFilter, DynamicTable, Table, type(Table))):
|
class Typing(object):
"""
Namespace with type hints.
"""
AnyTable = Union[MagicFilter, DynamicTable, Table, Type[Table]]
NamespaceTable = Union[DynamicTable, Type[Table]]
AnyColumn = Union[Column, ColumnType]
class Sqlite3:
def __init__(self, path: str) -> None:
self.path = path
def get_path(self) -> str:
return self.path
def __str__(self) -> str:
return self.path
class Session(object):
def __init__(self, tables: list[Typing.NamespaceTable] = None, **kwargs) -> None:
"""
Creates a new session to work with the database.
:param path: Path to the database
:param tables: List of tables to be created during session initialization
:param kwargs: Other options for opening a database [ More details in `sqlite3.connect(...)` ]
"""
self._connection = DatabaseConnectionManager()._get_connection()
self._database = sqlite3.connect(self._connection.get_path(), **kwargs)
self._tables = tables or []
for table in self._tables:
self.create(table)
def create(self, table: Typing.NamespaceTable) -> None:
"""
Creates a new table in the database.
:param table: Table or dynamic table
:return: Nothing
"""
self._database.execute(f"CREATE TABLE IF NOT EXISTS {table.__tablename__} "
f"({', '.join([column.serialize() for column in table.columns().values()])})")
self._database.commit()
def clear(self, table: Typing.NamespaceTable) -> None:
"""
Clears the selected table.
:param table: Table or dynamic table
:return: Nothing
"""
self._database.execute(
f"DELETE FROM {table.__tablename__}"
)
self._database.commit()
def drop(self, table: Typing.NamespaceTable) -> None:
"""
Completely removes the table from the database.
:param table: Table or dynamic table
:return: Nothing
"""
self._database.execute(
f"DROP TABLE IF EXISTS {table.__tablename__}"
)
self._database.commit()
def insert(self, table: Table, replace: bool = False) -> None:
"""
Adds a new row to the table.
:param table: Initialized table object
:param replace: Will replace an existing row
:return: Nothing
"""
values = table.values
try:
self._database.execute(
f"INSERT {'OR REPLACE' if replace else ''} INTO {table.__tablename__} ({', '.join(values.keys())}) "
f"VALUES ({', '.join(['?'] * len(values))})", list(values.values())
)
self._database.commit()
return True
except Exception:
return False
def update(self, data: Typing.AnyTable, table: Table) -> None:
"""
Updates the selected rows in the table.
:param data: Initialized table object
:param table: Any type of table or magic filter
:return: Nothing
"""
if not isinstance(data, (MagicFilter, DynamicTable, Table, type(Table))): | raise SessionExecuteError("The data is not a successor of MagicFilterData or Table!") | 4 | 2023-11-16 08:26:02+00:00 | 8k |
IBM/oper8 | tests/test_session.py | [
{
"identifier": "STRATEGIC_MERGE_PATCH",
"path": "oper8/patch.py",
"snippet": "STRATEGIC_MERGE_PATCH = \"patchStrategicMerge\""
},
{
"identifier": "MAX_NAME_LEN",
"path": "oper8/session.py",
"snippet": "MAX_NAME_LEN = 63"
},
{
"identifier": "Session",
"path": "oper8/session.p... | import pytest
import aconfig
from oper8.patch import STRATEGIC_MERGE_PATCH
from oper8.session import MAX_NAME_LEN, Session
from oper8.status import make_application_status
from oper8.test_helpers.helpers import (
DummyNodeComponent,
MockDeployManager,
make_patch,
setup_cr,
) | 6,983 | api_version="foo.bar/v1",
name="foo",
namespace="testit",
):
return aconfig.Config(
{
"kind": kind,
"apiVersion": api_version,
"metadata": {
"name": name,
"namespace": namespace,
"labels": {"app": "test", "run": name},
},
},
override_env_vars=False,
)
## Tests #######################################################################
###############
## Prperties ##
###############
def test_constructed_properties():
"""Make sure all properties derived from the constructor args are populated
correctly
"""
rec_id = "1ab"
cr = setup_cr()
cfg = aconfig.Config({"foo": "bar"}, override_env_vars=False)
dm = MockDeployManager()
patches = [make_patch(STRATEGIC_MERGE_PATCH, {})]
session = Session(rec_id, cr, cfg, dm, patches)
assert session.id == rec_id
assert session.cr_manifest == cr
assert session.config == cfg
assert session.deploy_manager == dm
assert session.temporary_patches == patches
def test_cr_properties():
"""Make sure all properties derived from the CR manifest are populated
correctly
"""
version = "develop.1.2.3"
namespace = "wingbat"
name = "wombat"
api_version = "critters.bats/v23"
kind = "Critter"
spec = {"key": "value"}
cr = setup_cr(
api_version=api_version,
kind=kind,
namespace=namespace,
name=name,
version=version,
spec=spec,
)
session = Session("1ab", cr, {}, MockDeployManager())
assert session.version == version
assert session.namespace == namespace
assert session.name == name
assert session.kind == kind
assert session.api_version == api_version
assert session.spec == cr.spec
assert session.metadata == cr.metadata
@pytest.mark.parametrize(
"field",
["kind", "apiVersion", "metadata", "metadata.name", "metadata.namespace"],
)
def test_missing_cr_required_fields(field):
"""Make sure that required fields missing from the CR correctly raise
validation errors
"""
cr = setup_cr()
field_parts = field.split(".")
dct = cr
while len(field_parts) > 1:
dct = dct[field_parts[0]]
field_parts = field_parts[1:]
del dct[field_parts[0]]
with pytest.raises(AssertionError):
session = Session("1ab", cr, {}, MockDeployManager())
@pytest.mark.parametrize(
"field,expected",
[("spec", aconfig.Config({})), ("spec.version", None)],
)
def test_missing_cr_optional_fields(field, expected):
"""Make sure that optional fields in the CR that are accessed via properties
do not raise errors
"""
cr = setup_cr()
field_parts = field.split(".")
dct = cr
while len(field_parts) > 1:
dct = dct[field_parts[0]]
field_parts = field_parts[1:]
del dct[field_parts[0]]
session = Session("1ab", cr, {}, MockDeployManager())
assert getattr(session, field.split(".")[-1]) == expected
def test_current_version():
"""Make sure that retrieving the current_version works when it's present
in the deploy manager
"""
# Make sure that current_version is not set when it hasn't been deployed
cr = setup_cr()
dm = MockDeployManager()
session = Session("1ab", cr, {}, dm)
assert session.current_version is None
# Make sure that current_version is set when it's been deployed before
current_version = "some-version"
| """
Tests for all functionality of the Session object
"""
# Third Party
# First Party
# Local
## Helpers #####################################################################
def make_component_class(comp_name):
class DerivedComponent(DummyNodeComponent):
name = comp_name
return DerivedComponent
def make_api_obj(
kind="Foo",
api_version="foo.bar/v1",
name="foo",
namespace="testit",
):
return aconfig.Config(
{
"kind": kind,
"apiVersion": api_version,
"metadata": {
"name": name,
"namespace": namespace,
"labels": {"app": "test", "run": name},
},
},
override_env_vars=False,
)
## Tests #######################################################################
###############
## Prperties ##
###############
def test_constructed_properties():
"""Make sure all properties derived from the constructor args are populated
correctly
"""
rec_id = "1ab"
cr = setup_cr()
cfg = aconfig.Config({"foo": "bar"}, override_env_vars=False)
dm = MockDeployManager()
patches = [make_patch(STRATEGIC_MERGE_PATCH, {})]
session = Session(rec_id, cr, cfg, dm, patches)
assert session.id == rec_id
assert session.cr_manifest == cr
assert session.config == cfg
assert session.deploy_manager == dm
assert session.temporary_patches == patches
def test_cr_properties():
"""Make sure all properties derived from the CR manifest are populated
correctly
"""
version = "develop.1.2.3"
namespace = "wingbat"
name = "wombat"
api_version = "critters.bats/v23"
kind = "Critter"
spec = {"key": "value"}
cr = setup_cr(
api_version=api_version,
kind=kind,
namespace=namespace,
name=name,
version=version,
spec=spec,
)
session = Session("1ab", cr, {}, MockDeployManager())
assert session.version == version
assert session.namespace == namespace
assert session.name == name
assert session.kind == kind
assert session.api_version == api_version
assert session.spec == cr.spec
assert session.metadata == cr.metadata
@pytest.mark.parametrize(
"field",
["kind", "apiVersion", "metadata", "metadata.name", "metadata.namespace"],
)
def test_missing_cr_required_fields(field):
"""Make sure that required fields missing from the CR correctly raise
validation errors
"""
cr = setup_cr()
field_parts = field.split(".")
dct = cr
while len(field_parts) > 1:
dct = dct[field_parts[0]]
field_parts = field_parts[1:]
del dct[field_parts[0]]
with pytest.raises(AssertionError):
session = Session("1ab", cr, {}, MockDeployManager())
@pytest.mark.parametrize(
"field,expected",
[("spec", aconfig.Config({})), ("spec.version", None)],
)
def test_missing_cr_optional_fields(field, expected):
"""Make sure that optional fields in the CR that are accessed via properties
do not raise errors
"""
cr = setup_cr()
field_parts = field.split(".")
dct = cr
while len(field_parts) > 1:
dct = dct[field_parts[0]]
field_parts = field_parts[1:]
del dct[field_parts[0]]
session = Session("1ab", cr, {}, MockDeployManager())
assert getattr(session, field.split(".")[-1]) == expected
def test_current_version():
"""Make sure that retrieving the current_version works when it's present
in the deploy manager
"""
# Make sure that current_version is not set when it hasn't been deployed
cr = setup_cr()
dm = MockDeployManager()
session = Session("1ab", cr, {}, dm)
assert session.current_version is None
# Make sure that current_version is set when it's been deployed before
current_version = "some-version" | cr.status = make_application_status(version=current_version) | 3 | 2023-11-15 16:43:29+00:00 | 8k |
smrfeld/tsmixer-pytorch | main.py | [
{
"identifier": "plot_preds",
"path": "utils/plotting.py",
"snippet": "def plot_preds(preds: List[List[float]], preds_gt: List[List[float]], no_feats_plot: int, fname_save: Optional[str] = None, inputs: Optional[List[List[float]]] = None, show: bool = True):\n \"\"\"Plot predictions\n\n Args:\n ... | from utils import TSMixer, plot_preds, plot_loss, TSMixerConf, TSMixerGridSearch
import argparse
import yaml
import os | 6,955 |
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--command", type=str, required=True, choices=["train", "predict", "loss", "grid-search"], help="Command to run")
parser.add_argument("--conf", type=str, required=False, help="Path to the configuration file")
parser.add_argument("--no-feats-plot", type=int, required=False, default=6, help="Number of features to plot")
parser.add_argument("--show", action="store_true", required=False, help="Show plots")
args = parser.parse_args()
if args.command == "train":
# Load configuration
assert args.conf is not None, "Must provide a configuration file"
with open(args.conf, "r") as f:
|
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--command", type=str, required=True, choices=["train", "predict", "loss", "grid-search"], help="Command to run")
parser.add_argument("--conf", type=str, required=False, help="Path to the configuration file")
parser.add_argument("--no-feats-plot", type=int, required=False, default=6, help="Number of features to plot")
parser.add_argument("--show", action="store_true", required=False, help="Show plots")
args = parser.parse_args()
if args.command == "train":
# Load configuration
assert args.conf is not None, "Must provide a configuration file"
with open(args.conf, "r") as f: | conf = TSMixerConf.from_dict(yaml.safe_load(f)) | 2 | 2023-11-18 19:56:18+00:00 | 8k |
Jisencc/yolov5_dual_weighting | models/yolo.py | [
{
"identifier": "check_anchor_order",
"path": "utils/autoanchor.py",
"snippet": "def check_anchor_order(m):\n # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary\n a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer\n da = a... | import argparse
import contextlib
import os
import platform
import sys
import thop # for FLOPs computation
import yaml # for torch hub
from copy import deepcopy
from pathlib import Path
from models.common import * # noqa
from models.experimental import * # noqa
from utils.autoanchor import check_anchor_order
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
from utils.plots import feature_visualization
from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
time_sync) | 5,570 |
try:
except ImportError:
thop = None
class Detect(nn.Module):
# YOLOv5 Detect head for detection models
stride = None # strides computed during build
dynamic = False # force grid reconstruction
export = False # export mode
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
super().__init__()
self.nc = nc # number of classes
self.no = nc + 5 # number of outputs per anchor
self.nl = len(anchors) # number of detection layers
self.na = len(anchors[0]) // 2 # number of anchors
self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid
self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid
self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
self.inplace = inplace # use inplace ops (e.g. slice assignment)
def forward(self, x):
z = [] # inference output
for i in range(self.nl):
x[i] = self.m[i](x[i]) # conv
bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
if not self.training: # inference
if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
if isinstance(self, Segment): # (boxes + masks)
xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy
wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
else: # Detect (boxes only)
xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, conf), 4)
z.append(y.view(bs, self.na * nx * ny, self.no))
return x if self.training else (torch.cat(z, 1), ) if self.export else (torch.cat(z, 1), x)
def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')):
d = self.anchors[i].device
t = self.anchors[i].dtype
shape = 1, self.na, ny, nx, 2 # grid shape
y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility
grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
return grid, anchor_grid
class Segment(Detect):
# YOLOv5 Segment head for segmentation models
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
super().__init__(nc, anchors, ch, inplace)
self.nm = nm # number of masks
self.npr = npr # number of protos
self.no = 5 + nc + self.nm # number of outputs per anchor
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
self.proto = Proto(ch[0], self.npr, self.nm) # protos
self.detect = Detect.forward
def forward(self, x):
p = self.proto(x[0])
x = self.detect(self, x)
return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
class BaseModel(nn.Module):
# YOLOv5 base model
def forward(self, x, profile=False, visualize=False):
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_once(self, x, profile=False, visualize=False):
y, dt = [], [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
if profile:
self._profile_one_layer(m, x, dt)
x = m(x) # run
y.append(x if m.i in self.save else None) # save output
if visualize:
feature_visualization(x, m.type, m.i, save_dir=visualize)
return x
def _profile_one_layer(self, m, x, dt):
c = m == self.model[-1] # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x, ), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
t = time_sync()
for _ in range(10):
m(x.copy() if c else x)
dt.append((time_sync() - t) * 100)
if m == self.model[0]:
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
if c:
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
LOGGER.info('Fusing layers... ')
for m in self.model.modules():
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
delattr(m, 'bn') # remove batchnorm
m.forward = m.forward_fuse # update forward
self.info()
return self
def info(self, verbose=False, img_size=640): # print model information
| # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
"""
YOLO-specific modules
Usage:
$ python models/yolo.py --cfg yolov5s.yaml
"""
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
if platform.system() != 'Windows':
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
try:
except ImportError:
thop = None
class Detect(nn.Module):
# YOLOv5 Detect head for detection models
stride = None # strides computed during build
dynamic = False # force grid reconstruction
export = False # export mode
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
super().__init__()
self.nc = nc # number of classes
self.no = nc + 5 # number of outputs per anchor
self.nl = len(anchors) # number of detection layers
self.na = len(anchors[0]) // 2 # number of anchors
self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid
self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid
self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
self.inplace = inplace # use inplace ops (e.g. slice assignment)
def forward(self, x):
z = [] # inference output
for i in range(self.nl):
x[i] = self.m[i](x[i]) # conv
bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
if not self.training: # inference
if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
if isinstance(self, Segment): # (boxes + masks)
xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy
wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
else: # Detect (boxes only)
xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, conf), 4)
z.append(y.view(bs, self.na * nx * ny, self.no))
return x if self.training else (torch.cat(z, 1), ) if self.export else (torch.cat(z, 1), x)
def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')):
d = self.anchors[i].device
t = self.anchors[i].dtype
shape = 1, self.na, ny, nx, 2 # grid shape
y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility
grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
return grid, anchor_grid
class Segment(Detect):
# YOLOv5 Segment head for segmentation models
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
super().__init__(nc, anchors, ch, inplace)
self.nm = nm # number of masks
self.npr = npr # number of protos
self.no = 5 + nc + self.nm # number of outputs per anchor
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
self.proto = Proto(ch[0], self.npr, self.nm) # protos
self.detect = Detect.forward
def forward(self, x):
p = self.proto(x[0])
x = self.detect(self, x)
return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
class BaseModel(nn.Module):
# YOLOv5 base model
def forward(self, x, profile=False, visualize=False):
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_once(self, x, profile=False, visualize=False):
y, dt = [], [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
if profile:
self._profile_one_layer(m, x, dt)
x = m(x) # run
y.append(x if m.i in self.save else None) # save output
if visualize:
feature_visualization(x, m.type, m.i, save_dir=visualize)
return x
def _profile_one_layer(self, m, x, dt):
c = m == self.model[-1] # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x, ), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
t = time_sync()
for _ in range(10):
m(x.copy() if c else x)
dt.append((time_sync() - t) * 100)
if m == self.model[0]:
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
if c:
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
LOGGER.info('Fusing layers... ')
for m in self.model.modules():
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
delattr(m, 'bn') # remove batchnorm
m.forward = m.forward_fuse # update forward
self.info()
return self
def info(self, verbose=False, img_size=640): # print model information | model_info(self, verbose, img_size) | 9 | 2023-11-12 13:28:26+00:00 | 8k |
giu-guarino/PCA-Z-PNN | test.py | [
{
"identifier": "PCA_Z_PNN_model",
"path": "network.py",
"snippet": "class PCA_Z_PNN_model(nn.Module):\n def __init__(self, nbands, padding='same', padding_mode='reflect', bias=True) -> None:\n super(PCA_Z_PNN_model, self).__init__()\n self.conv1 = nn.Conv2d(nbands + 1, 48, 7, padding=p... | import argparse
import gc
import os
import numpy as np
import scipy.io as io
import torch
from tqdm import tqdm
from network import PCA_Z_PNN_model
from loss import SpectralLoss, StructuralLoss
from tools.spectral_tools import gen_mtf, normalize_prisma, denormalize_prisma
from dataset import open_mat
from config_dict import config
from tools.cross_correlation import local_corr_mask
from tools.pca_tools import pca, inverse_pca
from skimage.transform import rescale | 3,645 | gpu_number = args.gpu_number
use_cpu = args.use_cpu
# Training hyperparameters
if args.learning_rate != -1:
learning_rate = args.learning_rate
else:
learning_rate = config['learning_rate']
# Satellite configuration
sensor = config['satellite']
ratio = config['ratio']
num_blocks = config['num_blocks']
n_components = config['n_components']
last_wl = config['last_wl']
epochs = args.epochs
if epochs == -1:
epochs = config['epochs']
# Environment Configuration
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_number)
# Devices definition
device = torch.device("cuda:0" if torch.cuda.is_available() and not use_cpu else "cpu")
if sensor == 'PRISMA':
normalize = normalize_prisma
denormalize = denormalize_prisma
else:
raise 'Satellite not supported'
# Open the image
pan, ms_lr, ms, _, wl = open_mat(basepath)
pan = normalize(pan, nbits=16, nbands=1).to(device)
criterion_spec = SpectralLoss(gen_mtf(ratio, sensor, kernel_size=61, nbands=n_components), ratio, device).to(device)
criterion_struct = StructuralLoss(ratio).to(device)
history_loss_spec = []
history_loss_struct = []
alpha = config['alpha_1']
fused = []
band_blocks = []
band_rgb = 0
while wl[band_rgb] < last_wl:
band_rgb += 1
band_blocks.append(ms_lr[:, :band_rgb + 1, :, :])
band_blocks.append(ms_lr[:, band_rgb:, :, :])
for block_index in range(num_blocks):
net = PCA_Z_PNN_model(nbands=n_components).to(device)
optim = torch.optim.Adam(net.parameters(), lr=learning_rate, betas=(config['beta_1'], config['beta_2']))
net.train()
ms_lr_pca, W, mu = pca(band_blocks[block_index])
ms_pca = torch.tensor(rescale(torch.squeeze(ms_lr_pca).numpy(), ratio, order=3, channel_axis=0))[None, :, :, :]
spec_ref_exp = normalize(ms_pca[:, :n_components, :, :], nbands=ms_pca.shape[1], nbits=16).to(device)
spec_ref = normalize(ms_lr_pca[:, :n_components, :, :], nbands=ms_pca.shape[1], nbits=16).to(device)
min_loss = torch.inf
inp = torch.cat([spec_ref_exp, pan], dim=1)
threshold = local_corr_mask(inp, ratio, sensor, device, config['semi_width'])
if block_index == 1:
alpha = config['alpha_2']
print('Block index {} / {}'.format(block_index + 1, num_blocks))
pbar = tqdm(range(epochs))
for epoch in pbar:
pbar.set_description('Epoch %d/%d' % (epoch + 1, epochs))
net.train()
optim.zero_grad()
outputs = net(inp)
loss_spec = criterion_spec(outputs, spec_ref)
loss_struct, loss_struct_without_threshold = criterion_struct(outputs[:,:1,:,:], pan, threshold[:,:1,:,:])
loss = loss_spec + alpha * loss_struct
loss.backward()
optim.step()
running_loss_spec = loss_spec.item()
running_loss_struct = loss_struct_without_threshold
history_loss_spec.append(running_loss_spec)
history_loss_struct.append(running_loss_struct)
if loss.item() < min_loss:
min_loss = loss.item()
if not os.path.exists('temp'):
os.makedirs(os.path.join('temp'))
torch.save(net.state_dict(), os.path.join('temp', 'PCA-Z-PNN_best_model.tar'))
pbar.set_postfix(
{'Spec Loss': running_loss_spec, 'Struct Loss': running_loss_struct})
net.eval()
net.load_state_dict(torch.load(os.path.join('temp', 'PCA-Z-PNN_best_model.tar')))
ms_pca[:, :n_components, :, :] = denormalize(net(inp), nbands=ms_pca.shape[1], nbits=16)
|
def test_pca_z_pnn(args):
# Paths and env configuration
basepath = args.input
method = 'PCA-Z-PNN'
out_dir = os.path.join(args.out_dir, method)
gpu_number = args.gpu_number
use_cpu = args.use_cpu
# Training hyperparameters
if args.learning_rate != -1:
learning_rate = args.learning_rate
else:
learning_rate = config['learning_rate']
# Satellite configuration
sensor = config['satellite']
ratio = config['ratio']
num_blocks = config['num_blocks']
n_components = config['n_components']
last_wl = config['last_wl']
epochs = args.epochs
if epochs == -1:
epochs = config['epochs']
# Environment Configuration
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_number)
# Devices definition
device = torch.device("cuda:0" if torch.cuda.is_available() and not use_cpu else "cpu")
if sensor == 'PRISMA':
normalize = normalize_prisma
denormalize = denormalize_prisma
else:
raise 'Satellite not supported'
# Open the image
pan, ms_lr, ms, _, wl = open_mat(basepath)
pan = normalize(pan, nbits=16, nbands=1).to(device)
criterion_spec = SpectralLoss(gen_mtf(ratio, sensor, kernel_size=61, nbands=n_components), ratio, device).to(device)
criterion_struct = StructuralLoss(ratio).to(device)
history_loss_spec = []
history_loss_struct = []
alpha = config['alpha_1']
fused = []
band_blocks = []
band_rgb = 0
while wl[band_rgb] < last_wl:
band_rgb += 1
band_blocks.append(ms_lr[:, :band_rgb + 1, :, :])
band_blocks.append(ms_lr[:, band_rgb:, :, :])
for block_index in range(num_blocks):
net = PCA_Z_PNN_model(nbands=n_components).to(device)
optim = torch.optim.Adam(net.parameters(), lr=learning_rate, betas=(config['beta_1'], config['beta_2']))
net.train()
ms_lr_pca, W, mu = pca(band_blocks[block_index])
ms_pca = torch.tensor(rescale(torch.squeeze(ms_lr_pca).numpy(), ratio, order=3, channel_axis=0))[None, :, :, :]
spec_ref_exp = normalize(ms_pca[:, :n_components, :, :], nbands=ms_pca.shape[1], nbits=16).to(device)
spec_ref = normalize(ms_lr_pca[:, :n_components, :, :], nbands=ms_pca.shape[1], nbits=16).to(device)
min_loss = torch.inf
inp = torch.cat([spec_ref_exp, pan], dim=1)
threshold = local_corr_mask(inp, ratio, sensor, device, config['semi_width'])
if block_index == 1:
alpha = config['alpha_2']
print('Block index {} / {}'.format(block_index + 1, num_blocks))
pbar = tqdm(range(epochs))
for epoch in pbar:
pbar.set_description('Epoch %d/%d' % (epoch + 1, epochs))
net.train()
optim.zero_grad()
outputs = net(inp)
loss_spec = criterion_spec(outputs, spec_ref)
loss_struct, loss_struct_without_threshold = criterion_struct(outputs[:,:1,:,:], pan, threshold[:,:1,:,:])
loss = loss_spec + alpha * loss_struct
loss.backward()
optim.step()
running_loss_spec = loss_spec.item()
running_loss_struct = loss_struct_without_threshold
history_loss_spec.append(running_loss_spec)
history_loss_struct.append(running_loss_struct)
if loss.item() < min_loss:
min_loss = loss.item()
if not os.path.exists('temp'):
os.makedirs(os.path.join('temp'))
torch.save(net.state_dict(), os.path.join('temp', 'PCA-Z-PNN_best_model.tar'))
pbar.set_postfix(
{'Spec Loss': running_loss_spec, 'Struct Loss': running_loss_struct})
net.eval()
net.load_state_dict(torch.load(os.path.join('temp', 'PCA-Z-PNN_best_model.tar')))
ms_pca[:, :n_components, :, :] = denormalize(net(inp), nbands=ms_pca.shape[1], nbits=16) | fused_block = inverse_pca(ms_pca, W, mu) | 10 | 2023-11-13 10:26:11+00:00 | 8k |
airalcorn2/paved2paradise | train.py | [
{
"identifier": "config",
"path": "config.py",
"snippet": "(C, S) = (64, 1)"
},
{
"identifier": "KITTIDataset",
"path": "kitti_dataset.py",
"snippet": "class KITTIDataset(Dataset):\n def __init__(\n self,\n dataset,\n jsons_path,\n npys_path,\n label... | import os
import sys
import json
import random
import shutil
import torch
import wandb
from config import config
from kitti_dataset import KITTIDataset
from kitti_env import KITTIEnv
from pointpillars import PointPillars
from torch import nn, optim
from torch.utils.data import DataLoader | 5,640 | for idx, tensors_dict in enumerate(train_loader):
if idx % eval_every == 0:
if use_amp:
with torch.autocast(device_type="cuda", dtype=torch.float16):
total_valid_loss = validate(
model, valid_loader, device, criterion
)
else:
total_valid_loss = validate(model, valid_loader, device, criterion)
if total_valid_loss < best_valid_loss:
best_valid_loss = total_valid_loss
no_improvement = 0
lr_drops = 0
torch.save(
model.state_dict(), f"{wandb.run.dir}/{KITTIEnv.best_params_f}"
)
else:
no_improvement += 1
if no_improvement == patience:
lr_drops += 1
if lr_drops == max_lr_drops:
sys.exit()
no_improvement = 0
lr_reductions += 1
for g in optimizer.param_groups:
g["lr"] *= lr_reducer
if n_train > 0:
average_train_loss = total_train_loss / n_train
else:
average_train_loss = total_train_loss
wandb.log(
{
"average_train_loss": average_train_loss,
"average_valid_loss": total_valid_loss / n_valid,
"lr_reductions": lr_reductions,
}
)
total_train_loss = 0.0
n_train = 0
model.train()
optimizer.zero_grad()
if use_amp:
with torch.autocast(device_type="cuda", dtype=torch.float16):
loss = get_loss(model, tensors_dict, device, criterion)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
else:
loss = get_loss(model, tensors_dict, device, criterion)
loss.backward()
optimizer.step()
total_train_loss += loss.item()
n_train += len(tensors_dict["tgt"])
def main():
dataset = config["dataset"]
assert dataset in {"baseline", "paved2paradise"}
if dataset == "paved2paradise":
jsons_path = KITTIEnv.final_jsons_path
npys_path = KITTIEnv.final_npys_path
labels_path = KITTIEnv.final_labels_path
idxs_path = KITTIEnv.final_idxs_path
backgrounds_path = KITTIEnv.unlevel_background_npys_path
data_dict_f = KITTIEnv.data_dict_f
else:
jsons_path = KITTIEnv.jsons_path
npys_path = KITTIEnv.npys_path
labels_path = KITTIEnv.labels_path
idxs_path = None
backgrounds_path = None
data_dict_f = KITTIEnv.kitti_data_dict_f
# This should have been created when preparing the KITTI data.
assert os.path.isfile(data_dict_f)
if not os.path.isfile(data_dict_f):
init_data_dict(jsons_path, data_dict_f)
with open(data_dict_f) as f:
data_dict = json.load(f)
config["data_dict"] = data_dict
config["model_args"]["x_range"] = KITTIEnv.x_range
config["model_args"]["y_range"] = KITTIEnv.y_range
config["model_args"]["z_range"] = KITTIEnv.z_range
wandb.init(project=KITTIEnv.wandb_project, entity=KITTIEnv.entity, config=config)
shutil.copyfile(KITTIEnv.model_f, f"{wandb.run.dir}/{KITTIEnv.model_f}")
device = torch.device("cuda:0")
model = PointPillars(**config["model_args"]).to(device)
print(model)
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"Parameters: {n_params}")
print(repr(model))
dataset_args = {
"dataset": dataset,
"jsons_path": jsons_path,
"npys_path": npys_path,
"labels_path": labels_path,
"idxs_path": idxs_path,
"backgrounds_path": backgrounds_path,
"json_fs": data_dict["train"],
"prepare_pillars": model.prepare_pillars,
"augment": True,
"max_drop_p": config["max_drop_p"],
}
|
# See: https://github.com/pytorch/pytorch/issues/9158#issuecomment-402358096.
if len(sys.argv) > 1:
os.environ["CUDA_VISIBLE_DEVICES"] = sys.argv[1]
def init_data_dict(jsons_path, data_dict_f):
json_fs = os.listdir(jsons_path)
random.shuffle(json_fs)
train_p = config["train_p"]
train_n = int(train_p * len(json_fs))
train_val_fs = json_fs[:train_n]
test_fs = json_fs[train_n:]
data_dict = {"train": train_val_fs, "valid": test_fs}
with open(data_dict_f, "w") as f:
json.dump(data_dict, f)
def get_loss(model, tensors_dict, device, criterion):
pillar_buffers = tensors_dict["pillar_buffers"].to(device)
pillar_pixels = tensors_dict["pillar_pixels"].to(device)
pillar_avgs = tensors_dict["pillar_avgs"].to(device)
preds = model(pillar_buffers, pillar_avgs, pillar_pixels)
labels = tensors_dict["tgt"].to(device)
loss = criterion(preds, labels)
return loss
def validate(model, valid_loader, device, criterion):
model.eval()
total_valid_loss = 0.0
with torch.no_grad():
for tensors_dict in valid_loader:
loss = get_loss(model, tensors_dict, device, criterion)
total_valid_loss += loss.item()
return total_valid_loss
def train(config, model, valid_loader, train_loader, device):
lr = config["lr"]
optimizer = optim.AdamW(model.parameters(), lr=lr)
criterion = nn.BCEWithLogitsLoss(reduction="sum")
scaler = torch.cuda.amp.GradScaler()
# See: https://pytorch.org/tutorials/recipes/recipes/amp_recipe.html,
# and: https://pytorch.org/docs/stable/notes/amp_examples.html,
# and: https://pytorch.org/blog/what-every-user-should-know-about-mixed-precision-training-in-pytorch/.
use_amp = config["use_amp"]
best_valid_loss = float("inf")
patience = config["patience"]
max_lr_drops = config["max_lr_drops"]
lr_reducer = config["lr_reducer"]
eval_every = config["eval_every"]
no_improvement = 0
lr_drops = 0
lr_reductions = 0
total_train_loss = float("inf")
n_valid = len(valid_loader.dataset)
n_train = 0
for epoch in range(config["epochs"]):
model.train()
for idx, tensors_dict in enumerate(train_loader):
if idx % eval_every == 0:
if use_amp:
with torch.autocast(device_type="cuda", dtype=torch.float16):
total_valid_loss = validate(
model, valid_loader, device, criterion
)
else:
total_valid_loss = validate(model, valid_loader, device, criterion)
if total_valid_loss < best_valid_loss:
best_valid_loss = total_valid_loss
no_improvement = 0
lr_drops = 0
torch.save(
model.state_dict(), f"{wandb.run.dir}/{KITTIEnv.best_params_f}"
)
else:
no_improvement += 1
if no_improvement == patience:
lr_drops += 1
if lr_drops == max_lr_drops:
sys.exit()
no_improvement = 0
lr_reductions += 1
for g in optimizer.param_groups:
g["lr"] *= lr_reducer
if n_train > 0:
average_train_loss = total_train_loss / n_train
else:
average_train_loss = total_train_loss
wandb.log(
{
"average_train_loss": average_train_loss,
"average_valid_loss": total_valid_loss / n_valid,
"lr_reductions": lr_reductions,
}
)
total_train_loss = 0.0
n_train = 0
model.train()
optimizer.zero_grad()
if use_amp:
with torch.autocast(device_type="cuda", dtype=torch.float16):
loss = get_loss(model, tensors_dict, device, criterion)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
else:
loss = get_loss(model, tensors_dict, device, criterion)
loss.backward()
optimizer.step()
total_train_loss += loss.item()
n_train += len(tensors_dict["tgt"])
def main():
dataset = config["dataset"]
assert dataset in {"baseline", "paved2paradise"}
if dataset == "paved2paradise":
jsons_path = KITTIEnv.final_jsons_path
npys_path = KITTIEnv.final_npys_path
labels_path = KITTIEnv.final_labels_path
idxs_path = KITTIEnv.final_idxs_path
backgrounds_path = KITTIEnv.unlevel_background_npys_path
data_dict_f = KITTIEnv.data_dict_f
else:
jsons_path = KITTIEnv.jsons_path
npys_path = KITTIEnv.npys_path
labels_path = KITTIEnv.labels_path
idxs_path = None
backgrounds_path = None
data_dict_f = KITTIEnv.kitti_data_dict_f
# This should have been created when preparing the KITTI data.
assert os.path.isfile(data_dict_f)
if not os.path.isfile(data_dict_f):
init_data_dict(jsons_path, data_dict_f)
with open(data_dict_f) as f:
data_dict = json.load(f)
config["data_dict"] = data_dict
config["model_args"]["x_range"] = KITTIEnv.x_range
config["model_args"]["y_range"] = KITTIEnv.y_range
config["model_args"]["z_range"] = KITTIEnv.z_range
wandb.init(project=KITTIEnv.wandb_project, entity=KITTIEnv.entity, config=config)
shutil.copyfile(KITTIEnv.model_f, f"{wandb.run.dir}/{KITTIEnv.model_f}")
device = torch.device("cuda:0")
model = PointPillars(**config["model_args"]).to(device)
print(model)
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"Parameters: {n_params}")
print(repr(model))
dataset_args = {
"dataset": dataset,
"jsons_path": jsons_path,
"npys_path": npys_path,
"labels_path": labels_path,
"idxs_path": idxs_path,
"backgrounds_path": backgrounds_path,
"json_fs": data_dict["train"],
"prepare_pillars": model.prepare_pillars,
"augment": True,
"max_drop_p": config["max_drop_p"],
} | train_dataset = KITTIDataset(**dataset_args) | 1 | 2023-11-15 17:13:30+00:00 | 8k |
jbusecke/dynamic_chunks | dynamic_chunks/tests/test_algorithms.py | [
{
"identifier": "even_divisor_algo",
"path": "dynamic_chunks/algorithms.py",
"snippet": "@check_inputs\ndef even_divisor_algo(\n ds: xr.Dataset,\n target_chunk_size: int,\n target_chunks_aspect_ratio: Dict[str, int],\n size_tolerance: float,\n) -> Dict[str, int]:\n \"\"\"\n Algorithm t... | from typing import Dict
from dynamic_chunks.algorithms import (
even_divisor_algo,
iterative_ratio_increase_algo,
NoMatchingChunks
)
import dask.array as dsa
import pytest
import xarray as xr | 4,883 | # Test that a warning is raised
target_chunk_nbytes = 5e6
msg = "are not specified in target_chunks_aspect_ratio.Setting default value of"
with pytest.warns(UserWarning, match=msg):
chunks_from_default = algo(
ds,
target_chunk_nbytes,
target_chunks_aspect_ratio={"x": 1, "z": 10},
size_tolerance=0.2,
default_ratio=default_ratio,
)
chunks_explicit = algo(
ds,
target_chunk_nbytes,
target_chunks_aspect_ratio={"x": 1, "y": default_ratio, "z": 10},
size_tolerance=0.2,
)
assert chunks_from_default == chunks_explicit
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_permuted_dimensions(algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
size_tolerance = 0.6
target_chunk_size = 5e5
target_chunks = algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio={"x": 1, "y": 2, "z": 10},
size_tolerance=size_tolerance,
)
target_chunks_permuted = algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio={
"z": 10,
"y": 2,
"x": 1,
},
size_tolerance=size_tolerance,
)
assert target_chunks == target_chunks_permuted
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_error_extra_dimensions_not_allowed(algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
msg = "target_chunks_aspect_ratio contains dimensions not present in dataset."
with pytest.raises(ValueError, match=msg):
algo(
ds,
1e6,
target_chunks_aspect_ratio={"x": 1, "y_other_name": 1, "y": 1, "z": 10},
size_tolerance=0.2,
)
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_extra_dimensions_allowed(algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
with pytest.warns(UserWarning, match="Trimming dimensions"):
chunks_with_extra = algo(
ds,
5e5,
target_chunks_aspect_ratio={"x": 1, "y_other_name": 1, "y": 1, "z": 10},
size_tolerance=0.2,
allow_extra_dims=True,
)
chunks_without_extra = algo(
ds,
5e5,
target_chunks_aspect_ratio={"x": 1, "y": 1, "z": 10},
size_tolerance=0.2,
)
assert chunks_with_extra == chunks_without_extra
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_non_int_ratio_input(algo):
ds = _create_ds({"x": 1, "y": 2, "z": 3})
with pytest.raises(ValueError, match="Ratio value must be an integer. Got 1.5 for dimension y"):
algo(
ds,
1e6,
target_chunks_aspect_ratio={"x": 1, "y": 1.5, "z": 10},
size_tolerance=0.2,
)
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_large_negative_ratio_input(algo):
ds = _create_ds({"x": 1, "y": 2, "z": 3})
with pytest.raises(
ValueError, match="Ratio value can only be larger than 0 or -1. Got -100 for dimension y"
):
algo(
ds,
1e6,
target_chunks_aspect_ratio={"x": 1, "y": -100, "z": 10},
size_tolerance=0.2,
)
def test_algo_comparison():
"""test that we get the same result from both algorithms for a known simple case"""
ds = _create_ds({"x": 100, "y": 100, "z": 100})
target_chunk_size = 4e5
target_chunks_aspect_ratio = {"x": -1, "y": 2, "z": 10}
size_tolerance = 0.01
chunks_a = even_divisor_algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio=target_chunks_aspect_ratio,
size_tolerance=size_tolerance,
)
chunks_b = iterative_ratio_increase_algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio=target_chunks_aspect_ratio,
size_tolerance=size_tolerance,
)
assert chunks_a == chunks_b
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_algo_exception(algo):
"""Test that each of the algos raises our custom exception when we give some totally unsolvable parameters"""
|
def _create_ds(dims_shape: Dict[str, int]) -> xr.Dataset:
return xr.DataArray(
dsa.random.random(list(dims_shape.values())),
dims=list(dims_shape.keys()),
).to_dataset(name="data")
@pytest.mark.parametrize(
("dims_shape", "target_chunks_aspect_ratio", "expected_target_chunks"),
[
# make sure that for the same dataset we get smaller chunksize along
# a dimension if the ratio is larger
(
{"x": 300, "y": 300, "z": 300},
{"x": 1, "y": 1, "z": 10},
{"x": 100, "y": 100, "z": 12},
),
(
{"x": 300, "y": 300, "z": 300},
{"x": 10, "y": 1, "z": 1},
{"x": 12, "y": 100, "z": 100},
),
# test the special case where we want to just chunk along a single dimension
(
{"x": 100, "y": 300, "z": 400},
{"x": -1, "y": -1, "z": 1},
{"x": 100, "y": 300, "z": 4},
),
],
)
def test_dynamic_rechunking(dims_shape, target_chunks_aspect_ratio, expected_target_chunks):
ds = _create_ds(dims_shape)
target_chunks = even_divisor_algo(
ds, 1e6, target_chunks_aspect_ratio=target_chunks_aspect_ratio, size_tolerance=0.2
)
print(target_chunks)
print(expected_target_chunks)
for dim, chunks in expected_target_chunks.items():
assert target_chunks[dim] == chunks
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_nbytes_str_input(algo):
ds = _create_ds({"x": 100, "y": 100, "z": 100})
target_chunks_aspect_ratio = {"x": 1, "y": 1, "z": 1}
target_chunks_int = algo(
ds, 1e6, target_chunks_aspect_ratio=target_chunks_aspect_ratio, size_tolerance=0.2
)
target_chunks_str = algo(
ds, "1MB", target_chunks_aspect_ratio=target_chunks_aspect_ratio, size_tolerance=0.2
)
for dim in target_chunks_aspect_ratio.keys():
assert target_chunks_int[dim] == target_chunks_str[dim]
def test_maintain_ratio():
"""Confirm that for a given ratio with two differently sized datasets we
maintain a constant ratio between total number of chunks"""
ds_equal = _create_ds({"x": 64, "y": 64})
ds_long = _create_ds({"x": 64, "y": 256})
for ds in [ds_equal, ds_long]:
print(ds)
target_chunks = even_divisor_algo(
ds, 1e4, target_chunks_aspect_ratio={"x": 1, "y": 4}, size_tolerance=0.2
)
ds_rechunked = ds.chunk(target_chunks)
assert len(ds_rechunked.chunks["y"]) / len(ds_rechunked.chunks["x"]) == 4
@pytest.mark.parametrize(
"target_chunks_aspect_ratio", [{"x": 1, "y": -1, "z": 10}, {"x": 6, "y": -1, "z": 2}]
) # always keep y unchunked, and vary the others
@pytest.mark.parametrize("target_chunk_nbytes", [1e6, 5e6])
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_skip_dimension(target_chunks_aspect_ratio, target_chunk_nbytes, algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
# Mark dimension as 'not-to-chunk' with -1
target_chunks = algo(
ds,
target_chunk_nbytes,
target_chunks_aspect_ratio=target_chunks_aspect_ratio,
size_tolerance=0.2,
)
assert target_chunks["y"] == len(ds["y"])
@pytest.mark.parametrize("default_ratio", [-1, 1])
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_missing_dimensions(default_ratio, algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
# Test that a warning is raised
target_chunk_nbytes = 5e6
msg = "are not specified in target_chunks_aspect_ratio.Setting default value of"
with pytest.warns(UserWarning, match=msg):
chunks_from_default = algo(
ds,
target_chunk_nbytes,
target_chunks_aspect_ratio={"x": 1, "z": 10},
size_tolerance=0.2,
default_ratio=default_ratio,
)
chunks_explicit = algo(
ds,
target_chunk_nbytes,
target_chunks_aspect_ratio={"x": 1, "y": default_ratio, "z": 10},
size_tolerance=0.2,
)
assert chunks_from_default == chunks_explicit
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_permuted_dimensions(algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
size_tolerance = 0.6
target_chunk_size = 5e5
target_chunks = algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio={"x": 1, "y": 2, "z": 10},
size_tolerance=size_tolerance,
)
target_chunks_permuted = algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio={
"z": 10,
"y": 2,
"x": 1,
},
size_tolerance=size_tolerance,
)
assert target_chunks == target_chunks_permuted
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_error_extra_dimensions_not_allowed(algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
msg = "target_chunks_aspect_ratio contains dimensions not present in dataset."
with pytest.raises(ValueError, match=msg):
algo(
ds,
1e6,
target_chunks_aspect_ratio={"x": 1, "y_other_name": 1, "y": 1, "z": 10},
size_tolerance=0.2,
)
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_extra_dimensions_allowed(algo):
ds = _create_ds({"x": 100, "y": 200, "z": 300})
with pytest.warns(UserWarning, match="Trimming dimensions"):
chunks_with_extra = algo(
ds,
5e5,
target_chunks_aspect_ratio={"x": 1, "y_other_name": 1, "y": 1, "z": 10},
size_tolerance=0.2,
allow_extra_dims=True,
)
chunks_without_extra = algo(
ds,
5e5,
target_chunks_aspect_ratio={"x": 1, "y": 1, "z": 10},
size_tolerance=0.2,
)
assert chunks_with_extra == chunks_without_extra
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_non_int_ratio_input(algo):
ds = _create_ds({"x": 1, "y": 2, "z": 3})
with pytest.raises(ValueError, match="Ratio value must be an integer. Got 1.5 for dimension y"):
algo(
ds,
1e6,
target_chunks_aspect_ratio={"x": 1, "y": 1.5, "z": 10},
size_tolerance=0.2,
)
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_large_negative_ratio_input(algo):
ds = _create_ds({"x": 1, "y": 2, "z": 3})
with pytest.raises(
ValueError, match="Ratio value can only be larger than 0 or -1. Got -100 for dimension y"
):
algo(
ds,
1e6,
target_chunks_aspect_ratio={"x": 1, "y": -100, "z": 10},
size_tolerance=0.2,
)
def test_algo_comparison():
"""test that we get the same result from both algorithms for a known simple case"""
ds = _create_ds({"x": 100, "y": 100, "z": 100})
target_chunk_size = 4e5
target_chunks_aspect_ratio = {"x": -1, "y": 2, "z": 10}
size_tolerance = 0.01
chunks_a = even_divisor_algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio=target_chunks_aspect_ratio,
size_tolerance=size_tolerance,
)
chunks_b = iterative_ratio_increase_algo(
ds,
target_chunk_size,
target_chunks_aspect_ratio=target_chunks_aspect_ratio,
size_tolerance=size_tolerance,
)
assert chunks_a == chunks_b
@pytest.mark.parametrize("algo", [iterative_ratio_increase_algo, even_divisor_algo])
def test_algo_exception(algo):
"""Test that each of the algos raises our custom exception when we give some totally unsolvable parameters""" | with pytest.raises(NoMatchingChunks): | 2 | 2023-11-14 20:29:11+00:00 | 8k |
globality-corp/deboiler | deboiler/deboiler.py | [
{
"identifier": "DeboilerDataset",
"path": "deboiler/dataset/base.py",
"snippet": "class DeboilerDataset(ABC):\n \"\"\"\n Base dataset class.\n\n To create custom dataset, one needs to sub-class from this base class and\n implement `__getitem__` and `__len__` methods, as well as the `urls` p... | from collections import defaultdict
from contextlib import contextmanager
from enum import Enum
from functools import lru_cache, partial
from logging import Logger
from multiprocessing import Pool
from time import time
from typing import Iterable, Optional
from tqdm import tqdm
from deboiler.dataset.base import DeboilerDataset
from deboiler.logger import logger
from deboiler.lxml_query import get_candidate_nodes
from deboiler.models.lxml_node import LxmlTree
from deboiler.models.page import OutputPage, ParsedPage
import langdetect
import numpy as np | 3,614 |
# Make langdetect deterministic
langdetect.DetectorFactory.seed = 0
class OperationMode(Enum):
MEMORY = "MEMORY"
PERFORMANCE = "PERFORMANCE"
@contextmanager
def imap_with_parallel(n_processes, chunksize=None):
"""
Returns regular `map` if n_processes = 1 else multi-processing `imap`.
chunksize is only used in the parallel setting.
"""
if n_processes > 1:
with Pool(n_processes) as pool:
yield partial(pool.imap, chunksize=chunksize)
else:
yield map
@logger
class Deboiler:
"""
The main class that implements the boilerplate identification and removal logic.
"""
logger: Logger
def __init__(
self,
n_processes: int = 1,
operation_mode: str = "memory",
# If the iou (for a pair) is more than the given threshold, the two pages
# are considered almost identical and therefore, that pair is excluded from
# boilerplate identification.
iou_threshold: float = 0.95,
# The number of times a subtree must be shared between pairs to be counted
# as boilerplate. By default, we consider any shared subtree (min_occurrence_threshold = 1)
# a boilerplate subtree (as longs as the iou-threshold is not violated for the pair)
min_occurrence_threshold: int = 1,
domain: str = "",
verbose: bool = True,
):
self.domain = domain
self.operation_mode = OperationMode(operation_mode.upper())
self.iou_threshold = iou_threshold
self.min_occurrence_threshold = min_occurrence_threshold
self.boilerplate_elements: set[str] = set()
self.n_processes = n_processes
self.verbose = verbose
# multi-processing is only available for the memory-optimized mode
assert self.n_processes >= 1 and (
self.operation_mode == OperationMode.MEMORY or self.n_processes == 1
), "`n_processes` can only be larger than 1 for the `memory` operation mode."
def fit_parsed_pair(
self,
page_pair: tuple[ParsedPage, ParsedPage],
) -> tuple[set[str], bool]:
"""
Finds nodes (i.e. subtrees) that are shared between the input pair (of parsed pages).
Makes sure the IOU (no of shared nodes over union of nodes) is not above the given
threshold, in which case does not return any shared nodes. That is a safeguard to
avoid removing all content in case near-duplicate pages are being compared.
"""
primary_page, secondary_page = page_pair
pair_is_too_similar = False
shared_nodes = primary_page.nodes & secondary_page.nodes
n_total_nodes = len(primary_page.nodes | secondary_page.nodes)
iou = len(shared_nodes) / (n_total_nodes if n_total_nodes else 1)
"""
We process pairs of sorted pages, like the following:
('www.globality.com/page-1.html', 'www.globality.com/page-2.html')
('www.globality.com/page-2.html', 'www.globality.com/page-3.html')
('www.globality.com/page-3.html', 'www.globality.com/page-4.html')
...
Let's assume the input pair to this method is
('www.globality.com/page-2.html', 'www.globality.com/page-3.html')
from the above.
At this point, the `nodes` cache of the primary page (i.e. page-2) can be emptied,
since `nodes` is only used during fit and both of the pairs that include page-2
have already been processed. And that is regardless of the operation mode.
Whether or not we empty individual LxmlNode caches depends on the operation mode.
In performance-optimized mode, we intend to keep the parsed object of the page to
avoid a re-parsing during `transform`.
In the memory-optimized mode, however, we empty that cache to preserve memory and
re-parse pages during `transform`.
"""
if self.operation_mode == OperationMode.MEMORY:
primary_page.clear_cache(clear_lxml_nodes_cache=True)
else:
primary_page.clear_cache(clear_lxml_nodes_cache=False)
if iou >= self.iou_threshold:
self.logger.debug(
f"iou = {iou:.2f} >= {self.iou_threshold:.2f} for urls {primary_page.url}, {secondary_page.url}"
)
shared_nodes, pair_is_too_similar = set(), True
return shared_nodes, pair_is_too_similar
@lru_cache(maxsize=1)
|
# Make langdetect deterministic
langdetect.DetectorFactory.seed = 0
class OperationMode(Enum):
MEMORY = "MEMORY"
PERFORMANCE = "PERFORMANCE"
@contextmanager
def imap_with_parallel(n_processes, chunksize=None):
"""
Returns regular `map` if n_processes = 1 else multi-processing `imap`.
chunksize is only used in the parallel setting.
"""
if n_processes > 1:
with Pool(n_processes) as pool:
yield partial(pool.imap, chunksize=chunksize)
else:
yield map
@logger
class Deboiler:
"""
The main class that implements the boilerplate identification and removal logic.
"""
logger: Logger
def __init__(
self,
n_processes: int = 1,
operation_mode: str = "memory",
# If the iou (for a pair) is more than the given threshold, the two pages
# are considered almost identical and therefore, that pair is excluded from
# boilerplate identification.
iou_threshold: float = 0.95,
# The number of times a subtree must be shared between pairs to be counted
# as boilerplate. By default, we consider any shared subtree (min_occurrence_threshold = 1)
# a boilerplate subtree (as longs as the iou-threshold is not violated for the pair)
min_occurrence_threshold: int = 1,
domain: str = "",
verbose: bool = True,
):
self.domain = domain
self.operation_mode = OperationMode(operation_mode.upper())
self.iou_threshold = iou_threshold
self.min_occurrence_threshold = min_occurrence_threshold
self.boilerplate_elements: set[str] = set()
self.n_processes = n_processes
self.verbose = verbose
# multi-processing is only available for the memory-optimized mode
assert self.n_processes >= 1 and (
self.operation_mode == OperationMode.MEMORY or self.n_processes == 1
), "`n_processes` can only be larger than 1 for the `memory` operation mode."
def fit_parsed_pair(
self,
page_pair: tuple[ParsedPage, ParsedPage],
) -> tuple[set[str], bool]:
"""
Finds nodes (i.e. subtrees) that are shared between the input pair (of parsed pages).
Makes sure the IOU (no of shared nodes over union of nodes) is not above the given
threshold, in which case does not return any shared nodes. That is a safeguard to
avoid removing all content in case near-duplicate pages are being compared.
"""
primary_page, secondary_page = page_pair
pair_is_too_similar = False
shared_nodes = primary_page.nodes & secondary_page.nodes
n_total_nodes = len(primary_page.nodes | secondary_page.nodes)
iou = len(shared_nodes) / (n_total_nodes if n_total_nodes else 1)
"""
We process pairs of sorted pages, like the following:
('www.globality.com/page-1.html', 'www.globality.com/page-2.html')
('www.globality.com/page-2.html', 'www.globality.com/page-3.html')
('www.globality.com/page-3.html', 'www.globality.com/page-4.html')
...
Let's assume the input pair to this method is
('www.globality.com/page-2.html', 'www.globality.com/page-3.html')
from the above.
At this point, the `nodes` cache of the primary page (i.e. page-2) can be emptied,
since `nodes` is only used during fit and both of the pairs that include page-2
have already been processed. And that is regardless of the operation mode.
Whether or not we empty individual LxmlNode caches depends on the operation mode.
In performance-optimized mode, we intend to keep the parsed object of the page to
avoid a re-parsing during `transform`.
In the memory-optimized mode, however, we empty that cache to preserve memory and
re-parse pages during `transform`.
"""
if self.operation_mode == OperationMode.MEMORY:
primary_page.clear_cache(clear_lxml_nodes_cache=True)
else:
primary_page.clear_cache(clear_lxml_nodes_cache=False)
if iou >= self.iou_threshold:
self.logger.debug(
f"iou = {iou:.2f} >= {self.iou_threshold:.2f} for urls {primary_page.url}, {secondary_page.url}"
)
shared_nodes, pair_is_too_similar = set(), True
return shared_nodes, pair_is_too_similar
@lru_cache(maxsize=1) | def get_parsed_page(self, dataset: DeboilerDataset, url: str) -> ParsedPage: | 0 | 2023-11-17 23:11:45+00:00 | 8k |
solovieff/kibernikto | kibernikto/telegram/single_group_dispatcher.py | [
{
"identifier": "InteractorOpenAI",
"path": "kibernikto/interactors/interactor_openai.py",
"snippet": "class InteractorOpenAI:\n MAX_WORD_COUNT = 3000\n \"\"\"\n Basic Entity on the OpenAI library level.\n Sends requests and receives responses. Can store chat summary.\n Can process group ... | import asyncio
import logging
import os
import random
import html
from random import choice
from typing import List, BinaryIO
from aiogram import Bot, Dispatcher, types, enums, F
from aiogram.enums import ParseMode
from aiogram.types import User
from kibernikto.interactors import InteractorOpenAI
from kibernikto import constants
from kibernikto.utils.text import split_text, MAX_MESSAGE_LENGTH
from kibernikto.plugins import YoutubePlugin, WeblinkSummaryPlugin, ImageSummaryPlugin
from kibernikto.utils.image import publish_image_file
from kibernikto.telegram.channel.gnews.publisher import scheduler | 6,382 | if bot_me is None:
bot_me = await bot.get_me()
FRIEND_GROUP_BOT = smart_bot_class(max_messages=constants.TG_BOT_MAX_HISTORY,
master_id=constants.TG_MASTER_ID,
name=bot_me.first_name,
who_am_i=constants.OPENAI_WHO_AM_I,
reaction_calls=constants.TG_REACTION_CALLS)
PRIVATE_BOT = smart_bot_class(max_messages=constants.TG_BOT_MAX_HISTORY,
master_id=constants.TG_MASTER_ID,
name=bot_me.first_name,
who_am_i=constants.OPENAI_WHO_AM_I,
reaction_calls=constants.TG_REACTION_CALLS)
# Initialize message processing plugins
_apply_plugins([FRIEND_GROUP_BOT, PRIVATE_BOT])
FRIEND_GROUP_BOT.defaults.reaction_calls.append(bot_me.username)
FRIEND_GROUP_BOT.defaults.reaction_calls.append(bot_me.first_name)
#await send_random_sticker(chat_id=constants.TG_FRIEND_GROUP_ID)
#hi_message = await FRIEND_GROUP_BOT.heed_and_reply("Поприветствуй участников чата!")
#await tg_bot.send_message(chat_id=constants.TG_FRIEND_GROUP_ID, text=hi_message)
if constants.TG_CHANNEL_ID:
asyncio.create_task(scheduler(load_news_minutes=constants.TG_CHANNEL_NEWS_UPDATE_PERIOD_MINUTES,
publish_item_minutes=constants.TG_CHANNEL_PUBLICATION_PERIOD_MINUTES,
publish_func=publish_to_channel,
base_url=constants.TG_CHANNEL_API_BASE_URL,
api_key=constants.TG_CHANNEL_SUMMARIZATION_KEY,
model=constants.TG_CHANNEL_API_MODEL
))
except Exception as e:
logging.error(f"failed to send hello message! {str(e)}")
if FRIEND_GROUP_BOT.client is not None:
await FRIEND_GROUP_BOT.client.close()
if PRIVATE_BOT.client is not None:
await PRIVATE_BOT.client.close()
await dp.stop_polling()
exit(os.EX_CONFIG)
async def publish_to_channel(text: str):
if constants.TG_CHANNEL_ID:
await tg_bot.send_message(text=text,
chat_id=constants.TG_CHANNEL_ID,
parse_mode=ParseMode.HTML,
disable_web_page_preview=True)
async def send_random_sticker(chat_id):
sticker_id = choice(constants.TG_STICKER_LIST)
# say hi to everyone
await tg_bot.send_sticker(
sticker=sticker_id,
chat_id=chat_id)
@dp.message(F.chat.type == enums.ChatType.PRIVATE)
async def private_message(message: types.Message):
if not PRIVATE_BOT.check_master(message.from_user.id, message.md_text):
reply_text = f"Я не отвечаю на вопросы в личных беседах с незакомыми людьми (если это конечно не мой Господин " \
f"Создатель снизошёл до меня). Я передам ваше соообщение мастеру."
await tg_bot.send_message(constants.TG_MASTER_ID, f"{message.from_user.id}: {message.md_text}")
else:
await tg_bot.send_chat_action(message.chat.id, 'typing')
user_text = await _get_message_text(message)
await tg_bot.send_chat_action(message.chat.id, 'typing')
reply_text = await PRIVATE_BOT.heed_and_reply(message=user_text)
chunks = split_text(reply_text, MAX_MESSAGE_LENGTH)
for chunk in chunks:
await message.reply(text=chunk)
@dp.message(F.chat.id == constants.TG_FRIEND_GROUP_ID)
async def group_message(message: types.Message):
if is_reply(message) or FRIEND_GROUP_BOT.should_react(message.md_text):
await tg_bot.send_chat_action(message.chat.id, 'typing')
user_text = await _get_message_text(message)
logging.getLogger().info(f"group_message: from {message.from_user.full_name} in {message.chat.title} processed")
await tg_bot.send_chat_action(message.chat.id, 'typing')
# not using author not to send usernames to openai :)
reply_text = await FRIEND_GROUP_BOT.heed_and_reply(user_text) # author=message.from_user.full_name
chunks = split_text(reply_text, MAX_MESSAGE_LENGTH)
for chunk in chunks:
await message.reply(text=chunk)
if random.random() < 0.1:
await send_random_sticker(chat_id=message.chat.id)
else:
pass
# for now we just ignore all non-related messages, even not putting them into history
# await FRIEND_GROUP_BOT.heed(message=message.text, author=message.from_user.full_name)
def is_reply(message: types.Message):
if message.reply_to_message and message.reply_to_message.from_user.id == tg_bot.id:
return True
def _apply_plugins(bots: List):
def apply_plugin(plugin):
for bot in bots:
bot.plugins.append(plugin)
if constants.IMAGE_SUMMARIZATION_KEY:
image_url_plugin = ImageSummaryPlugin(model=constants.IMAGE_SUMMARIZATION_MODEL,
base_url=constants.IMAGE_SUMMARIZATION_API_BASE_URL,
api_key=constants.IMAGE_SUMMARIZATION_KEY,
summarization_request=constants.IMAGE_SUMMARIZATION_REQUEST)
apply_plugin(image_url_plugin)
if constants.SUMMARIZATION_KEY:
sum_youtube_plugin = YoutubePlugin(model=constants.SUMMARIZATION_MODEL,
base_url=constants.SUMMARIZATION_API_BASE_URL,
api_key=constants.SUMMARIZATION_KEY,
summarization_request=constants.SUMMARIZATION_REQUEST)
apply_plugin(sum_youtube_plugin)
|
smart_bot_class = None
# Telegram bot
tg_bot: Bot = None
bot_me: User = None
dp = Dispatcher()
# Open AI bot instances.
# TODO: upper level class to create
FRIEND_GROUP_BOT: InteractorOpenAI = None
PRIVATE_BOT: InteractorOpenAI = None
MAX_TG_MESSAGE_LEN = 4096
commands = {}
def start(bot_class):
"""
runs the executor polling the dispatcher for incoming messages
:param bot_class: the bot class to use
:return:
"""
global smart_bot_class
global tg_bot
smart_bot_class = bot_class
dp.startup.register(on_startup)
tg_bot = Bot(token=constants.TG_BOT_KEY)
dp.run_polling(tg_bot, skip_updates=True)
async def on_startup(bot: Bot):
try:
global bot_me
global FRIEND_GROUP_BOT
global PRIVATE_BOT
if bot_me is None:
bot_me = await bot.get_me()
FRIEND_GROUP_BOT = smart_bot_class(max_messages=constants.TG_BOT_MAX_HISTORY,
master_id=constants.TG_MASTER_ID,
name=bot_me.first_name,
who_am_i=constants.OPENAI_WHO_AM_I,
reaction_calls=constants.TG_REACTION_CALLS)
PRIVATE_BOT = smart_bot_class(max_messages=constants.TG_BOT_MAX_HISTORY,
master_id=constants.TG_MASTER_ID,
name=bot_me.first_name,
who_am_i=constants.OPENAI_WHO_AM_I,
reaction_calls=constants.TG_REACTION_CALLS)
# Initialize message processing plugins
_apply_plugins([FRIEND_GROUP_BOT, PRIVATE_BOT])
FRIEND_GROUP_BOT.defaults.reaction_calls.append(bot_me.username)
FRIEND_GROUP_BOT.defaults.reaction_calls.append(bot_me.first_name)
#await send_random_sticker(chat_id=constants.TG_FRIEND_GROUP_ID)
#hi_message = await FRIEND_GROUP_BOT.heed_and_reply("Поприветствуй участников чата!")
#await tg_bot.send_message(chat_id=constants.TG_FRIEND_GROUP_ID, text=hi_message)
if constants.TG_CHANNEL_ID:
asyncio.create_task(scheduler(load_news_minutes=constants.TG_CHANNEL_NEWS_UPDATE_PERIOD_MINUTES,
publish_item_minutes=constants.TG_CHANNEL_PUBLICATION_PERIOD_MINUTES,
publish_func=publish_to_channel,
base_url=constants.TG_CHANNEL_API_BASE_URL,
api_key=constants.TG_CHANNEL_SUMMARIZATION_KEY,
model=constants.TG_CHANNEL_API_MODEL
))
except Exception as e:
logging.error(f"failed to send hello message! {str(e)}")
if FRIEND_GROUP_BOT.client is not None:
await FRIEND_GROUP_BOT.client.close()
if PRIVATE_BOT.client is not None:
await PRIVATE_BOT.client.close()
await dp.stop_polling()
exit(os.EX_CONFIG)
async def publish_to_channel(text: str):
if constants.TG_CHANNEL_ID:
await tg_bot.send_message(text=text,
chat_id=constants.TG_CHANNEL_ID,
parse_mode=ParseMode.HTML,
disable_web_page_preview=True)
async def send_random_sticker(chat_id):
sticker_id = choice(constants.TG_STICKER_LIST)
# say hi to everyone
await tg_bot.send_sticker(
sticker=sticker_id,
chat_id=chat_id)
@dp.message(F.chat.type == enums.ChatType.PRIVATE)
async def private_message(message: types.Message):
if not PRIVATE_BOT.check_master(message.from_user.id, message.md_text):
reply_text = f"Я не отвечаю на вопросы в личных беседах с незакомыми людьми (если это конечно не мой Господин " \
f"Создатель снизошёл до меня). Я передам ваше соообщение мастеру."
await tg_bot.send_message(constants.TG_MASTER_ID, f"{message.from_user.id}: {message.md_text}")
else:
await tg_bot.send_chat_action(message.chat.id, 'typing')
user_text = await _get_message_text(message)
await tg_bot.send_chat_action(message.chat.id, 'typing')
reply_text = await PRIVATE_BOT.heed_and_reply(message=user_text)
chunks = split_text(reply_text, MAX_MESSAGE_LENGTH)
for chunk in chunks:
await message.reply(text=chunk)
@dp.message(F.chat.id == constants.TG_FRIEND_GROUP_ID)
async def group_message(message: types.Message):
if is_reply(message) or FRIEND_GROUP_BOT.should_react(message.md_text):
await tg_bot.send_chat_action(message.chat.id, 'typing')
user_text = await _get_message_text(message)
logging.getLogger().info(f"group_message: from {message.from_user.full_name} in {message.chat.title} processed")
await tg_bot.send_chat_action(message.chat.id, 'typing')
# not using author not to send usernames to openai :)
reply_text = await FRIEND_GROUP_BOT.heed_and_reply(user_text) # author=message.from_user.full_name
chunks = split_text(reply_text, MAX_MESSAGE_LENGTH)
for chunk in chunks:
await message.reply(text=chunk)
if random.random() < 0.1:
await send_random_sticker(chat_id=message.chat.id)
else:
pass
# for now we just ignore all non-related messages, even not putting them into history
# await FRIEND_GROUP_BOT.heed(message=message.text, author=message.from_user.full_name)
def is_reply(message: types.Message):
if message.reply_to_message and message.reply_to_message.from_user.id == tg_bot.id:
return True
def _apply_plugins(bots: List):
def apply_plugin(plugin):
for bot in bots:
bot.plugins.append(plugin)
if constants.IMAGE_SUMMARIZATION_KEY:
image_url_plugin = ImageSummaryPlugin(model=constants.IMAGE_SUMMARIZATION_MODEL,
base_url=constants.IMAGE_SUMMARIZATION_API_BASE_URL,
api_key=constants.IMAGE_SUMMARIZATION_KEY,
summarization_request=constants.IMAGE_SUMMARIZATION_REQUEST)
apply_plugin(image_url_plugin)
if constants.SUMMARIZATION_KEY:
sum_youtube_plugin = YoutubePlugin(model=constants.SUMMARIZATION_MODEL,
base_url=constants.SUMMARIZATION_API_BASE_URL,
api_key=constants.SUMMARIZATION_KEY,
summarization_request=constants.SUMMARIZATION_REQUEST)
apply_plugin(sum_youtube_plugin)
| sum_web_plugin = WeblinkSummaryPlugin(model=constants.SUMMARIZATION_MODEL, | 5 | 2023-11-11 18:39:28+00:00 | 8k |
bytedance/LapNet | lapnet/networks/lapnet.py | [
{
"identifier": "envelopes",
"path": "lapnet/envelopes.py",
"snippet": "_MAX_POLY_ORDER = 5 # highest polynomial used in envelopes\n PRE_ORBITAL = enum.auto()\n PRE_DETERMINANT = enum.auto()\n POST_DETERMINANT = enum.auto()\n ISOTROPIC = enum.auto()\n ABS_ISOTROPIC = enum.auto()\n DIAGONAL = enum... | import functools
import attr
import chex
import jax
import lapjax.numpy as jnp
from typing import Sequence, Tuple
from lapnet import envelopes
from lapnet.networks import network_blocks
from .protocol import *
from .transformer_blocks import (
CrossAttentionLayer,
LayerNormBlock,
MultiheadCrossAttention,
)
from .utils import construct_input_features, init_jastrow_weights | 4,845 | Args:
key (chex.PRNGKey): JAX RNG state.
atoms (jnp.ndarray): (natom, ndim) array of atom positions.
nspins (Tuple[int, ...]): A tuple representing the number of spin-up and spin-down electrons. Should have length 2.
options (LapNetOptions): Network options.
"""
if not isinstance(options, LapNetOptions):
raise ValueError("options should be LapNetOptions")
if options.envelope.apply_type != envelopes.EnvelopeType.PRE_DETERMINANT:
raise ValueError('In LapNet, the envelope type must be `PRE_DETERMINANT`.')
if not options.full_det:
raise ValueError('In LapNet, the full_det option must be true.')
natom, ndim = atoms.shape
params = {} # The dict of all parameters to be optimized.
# num_features_in and num_features_out represent
# the dimension of initial array as well as the Transformer input dimension.
# params['input'] is a linear layer weights.
num_features_in, num_features_out = natom * (ndim + 1) + 1, options.hidden_dims[0][0]
key, subkey = jax.random.split(key)
params['input'] = network_blocks.init_linear_layer(
subkey, num_features_in, num_features_out, include_bias=True
)
# The input dimension of each layer
dims_in = [num_features_out] + [w[0] for w in options.hidden_dims[:-1]]
# Initialize the parameters for transformer backbone.
params['transformer'] = []
for dim_in, layer in zip(dims_in, options.atten_layers):
dic = {}
input_example = jnp.ones((sum(nspins), dim_in))
output_example = jnp.ones((sum(nspins), layer.attention.output_dim))
key, attkey, mlpkey, sparskey, lnkey = jax.random.split(key, num = 5)
dic['attention'] = layer.attention.init(attkey, [input_example, input_example])
dic['MLP'] = network_blocks.init_linear_layer(
key=mlpkey,
in_dim=layer.attention.output_dim,
out_dim=layer.attention.output_dim,
include_bias=True
)
dic['spars'] = [network_blocks.init_linear_layer(
key=key,
in_dim=layer.attention.output_dim,
out_dim=layer.attention.output_dim,
include_bias=True
) for key in jax.random.split(sparskey, num=2)]
ln1key, ln2key, ln3key = jax.random.split(lnkey, num=3)
dic['ln1'] = layer.layernorm1.init(ln1key, input_example)
dic['ln2'] = layer.layernorm2.init(ln2key, input_example)
dic['ln3'] = layer.layernorm3.init(ln3key, output_example)
params['transformer'].append(dic)
# Construct Orbital Projection
output_dim = sum(nspins) * options.determinants
if not options.orbitals_spin_split:
# Construct Orbital Projection
key, subkey = jax.random.split(key, num=2)
params['orbital'] = network_blocks.init_linear_layer(
key=subkey,
in_dim=options.hidden_dims[-1][0],
out_dim=output_dim,
include_bias=options.bias_orbitals)
# Construct Envelope
params['envelope'] = options.envelope.init(
natom=natom, output_dims=[output_dim], hf=None, ndim=ndim)[0]
else:
params['orbital'] = []
params['envelope'] = []
for i in range(len(nspins)):
# Construct Orbital Projection
key, subkey = jax.random.split(key, num=2)
params['orbital'].append(network_blocks.init_linear_layer(
key=subkey,
in_dim=options.hidden_dims[-1][0],
out_dim=output_dim,
include_bias=options.bias_orbitals))
# Construct Envelope
params['envelope'].append(options.envelope.init(
natom=natom, output_dims=[output_dim], hf=None, ndim=ndim)[0])
# Construct Jastrow factor
params['jastrow'] = init_jastrow_weights(key, options.jas_w_init)
return params
def lapnet_orbitals(
params,
pos: jnp.ndarray,
atoms: jnp.ndarray,
nspins: Tuple[int, ...],
options: LapNetOptions=LapNetOptions(),
):
"""Forward evaluation of the LapNet up to the orbitals.
Args:
params: A dictionary of parameters, contain fileds:
`input`: linear layer mapping initial array to transformer inputs.
`transformer`: parameters used in transformer backbones.
`orbital`: linear layer mapping transformer outputs to orbitals.
`envelope`: parameters used in the envelope function.
`jastrow`: parameters used in the Jastrow factor.
pos (jnp.ndarray): The electron positions, with shape (3N,).
atoms (jnp.ndarray): The atom positions.
nspins (Tuple[int, ...]): Tuple with number of spin up and spin down electrons. Should have length 2.
options (LapNetOptions): Network options.
Returns:
Binary tuple containg:
One matrix with shape (K, N, N), where the second dimension is equivariant equivariant to the input.
(ae, r_ae, r_ee), representing the atom-electron vectors, distrances and e-e distrances.
"""
| # Copyright 2023 Bytedance Ltd. and/or its affiliate
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
@attr.s(auto_attribs=True, kw_only=True)
class LapNetOptions:
"""Options controlling the LapNet architecture.
Attributes:
ndim: dimension of system. Change only with caution.
hidden_dims: Tuple of pairs, where each pair contains the number of hidden
units and number of MultiheadCrossAttention. The number of layers is given
by the length of the tuple.
determinants: Number of determinants to use.
full_det: WARNING: please keep true for lapnet
bias_orbitals: If true, include a bias in the final linear layer to shape
the outputs into orbitals.
envelope_label: Envelope to use to impose orbitals go to zero at infinity.
See envelopes module.
envelope: Envelope object to create and apply the multiplicative envelope.
attn_layer: Transformer layers used by lapnet
use_layernorm: If True, use layernorm in the attention block
jas_w_init: Initialization Value of jastrow factor
orbitals_spin_split: If true, use different parameters for alpha and beta
electrons in the orbital and envelope function.
"""
ndim: int = 3
hidden_dims: Tuple = ((256, 4), (256, 4), (256, 4), (256, 4))
determinants: int = 16
full_det: bool = True
bias_orbitals: bool = False
envelope_label: envelopes.EnvelopeLabel = envelopes.EnvelopeLabel.ABS_ISOTROPIC
envelope: envelopes.Envelope = attr.ib(
default=attr.Factory(
lambda self: envelopes.get_envelope(self.envelope_label),
takes_self=True))
atten_layers: Sequence[CrossAttentionLayer] = []
use_layernorm: bool = False
jas_w_init: float = 0.0
orbitals_spin_split: bool = True
def get_multihead_list(hidden_dims: LayerArgs,
layernorm: bool = False) -> Sequence[CrossAttentionLayer]:
"""Return the backbone of transformer as a list of multihead layers.
Args:
hidden_dims (LayerArgs): Each elecment is a tuple decribing (output_dim, num_heads).
layernorm (bool): Whether to use laryorm in the attention block
Returns:
list: Sequence of MultiheadCrossAttention.
"""
atten_layers = [MultiheadCrossAttention(
output_dim=output_dim,
num_heads=num_heads,)
for (output_dim, num_heads) in hidden_dims]
ln1 = [LayerNormBlock(use_layernorm=layernorm) for _ in hidden_dims]
ln2 = [LayerNormBlock(use_layernorm=layernorm) for _ in hidden_dims]
ln3 = [LayerNormBlock(use_layernorm=layernorm) for _ in hidden_dims]
return [CrossAttentionLayer(
attention=u, layernorm1=v, layernorm2=w, layernorm3=x)
for u, v, w, x in zip(atten_layers, ln1, ln2, ln3)]
def init_lapnet_params(
key: chex.PRNGKey,
atoms: jnp.ndarray,
nspins: Tuple[int, ...],
options: LapNetOptions = LapNetOptions(),
) -> ParamTree:
"""Initializes parameters for the LapNet Neural Network.
Args:
key (chex.PRNGKey): JAX RNG state.
atoms (jnp.ndarray): (natom, ndim) array of atom positions.
nspins (Tuple[int, ...]): A tuple representing the number of spin-up and spin-down electrons. Should have length 2.
options (LapNetOptions): Network options.
"""
if not isinstance(options, LapNetOptions):
raise ValueError("options should be LapNetOptions")
if options.envelope.apply_type != envelopes.EnvelopeType.PRE_DETERMINANT:
raise ValueError('In LapNet, the envelope type must be `PRE_DETERMINANT`.')
if not options.full_det:
raise ValueError('In LapNet, the full_det option must be true.')
natom, ndim = atoms.shape
params = {} # The dict of all parameters to be optimized.
# num_features_in and num_features_out represent
# the dimension of initial array as well as the Transformer input dimension.
# params['input'] is a linear layer weights.
num_features_in, num_features_out = natom * (ndim + 1) + 1, options.hidden_dims[0][0]
key, subkey = jax.random.split(key)
params['input'] = network_blocks.init_linear_layer(
subkey, num_features_in, num_features_out, include_bias=True
)
# The input dimension of each layer
dims_in = [num_features_out] + [w[0] for w in options.hidden_dims[:-1]]
# Initialize the parameters for transformer backbone.
params['transformer'] = []
for dim_in, layer in zip(dims_in, options.atten_layers):
dic = {}
input_example = jnp.ones((sum(nspins), dim_in))
output_example = jnp.ones((sum(nspins), layer.attention.output_dim))
key, attkey, mlpkey, sparskey, lnkey = jax.random.split(key, num = 5)
dic['attention'] = layer.attention.init(attkey, [input_example, input_example])
dic['MLP'] = network_blocks.init_linear_layer(
key=mlpkey,
in_dim=layer.attention.output_dim,
out_dim=layer.attention.output_dim,
include_bias=True
)
dic['spars'] = [network_blocks.init_linear_layer(
key=key,
in_dim=layer.attention.output_dim,
out_dim=layer.attention.output_dim,
include_bias=True
) for key in jax.random.split(sparskey, num=2)]
ln1key, ln2key, ln3key = jax.random.split(lnkey, num=3)
dic['ln1'] = layer.layernorm1.init(ln1key, input_example)
dic['ln2'] = layer.layernorm2.init(ln2key, input_example)
dic['ln3'] = layer.layernorm3.init(ln3key, output_example)
params['transformer'].append(dic)
# Construct Orbital Projection
output_dim = sum(nspins) * options.determinants
if not options.orbitals_spin_split:
# Construct Orbital Projection
key, subkey = jax.random.split(key, num=2)
params['orbital'] = network_blocks.init_linear_layer(
key=subkey,
in_dim=options.hidden_dims[-1][0],
out_dim=output_dim,
include_bias=options.bias_orbitals)
# Construct Envelope
params['envelope'] = options.envelope.init(
natom=natom, output_dims=[output_dim], hf=None, ndim=ndim)[0]
else:
params['orbital'] = []
params['envelope'] = []
for i in range(len(nspins)):
# Construct Orbital Projection
key, subkey = jax.random.split(key, num=2)
params['orbital'].append(network_blocks.init_linear_layer(
key=subkey,
in_dim=options.hidden_dims[-1][0],
out_dim=output_dim,
include_bias=options.bias_orbitals))
# Construct Envelope
params['envelope'].append(options.envelope.init(
natom=natom, output_dims=[output_dim], hf=None, ndim=ndim)[0])
# Construct Jastrow factor
params['jastrow'] = init_jastrow_weights(key, options.jas_w_init)
return params
def lapnet_orbitals(
params,
pos: jnp.ndarray,
atoms: jnp.ndarray,
nspins: Tuple[int, ...],
options: LapNetOptions=LapNetOptions(),
):
"""Forward evaluation of the LapNet up to the orbitals.
Args:
params: A dictionary of parameters, contain fileds:
`input`: linear layer mapping initial array to transformer inputs.
`transformer`: parameters used in transformer backbones.
`orbital`: linear layer mapping transformer outputs to orbitals.
`envelope`: parameters used in the envelope function.
`jastrow`: parameters used in the Jastrow factor.
pos (jnp.ndarray): The electron positions, with shape (3N,).
atoms (jnp.ndarray): The atom positions.
nspins (Tuple[int, ...]): Tuple with number of spin up and spin down electrons. Should have length 2.
options (LapNetOptions): Network options.
Returns:
Binary tuple containg:
One matrix with shape (K, N, N), where the second dimension is equivariant equivariant to the input.
(ae, r_ae, r_ee), representing the atom-electron vectors, distrances and e-e distrances.
""" | ae, ee, r_ae, r_ee = construct_input_features(pos, atoms) | 5 | 2023-11-13 08:19:53+00:00 | 8k |
civrealm/civrealm | src/civrealm/envs/freeciv_wrapper/action_wrapper.py | [
{
"identifier": "PersistentCityProduction",
"path": "src/civrealm/envs/freeciv_wrapper/city_wrapper.py",
"snippet": "class PersistentCityProduction(Wrapper):\n def __init__(self, env):\n super().__init__(env)\n self.__turn = -1\n\n def info(self, info, observation):\n for city... | from copy import deepcopy
from typing import Any, Dict, Optional
from gymnasium import spaces
from civrealm.configs import fc_args
from civrealm.envs.freeciv_wrapper.tensor_base_wrapper import TensorBase
from civrealm.freeciv.utils.fc_types import (ACTIVITY_FORTIFIED,
ACTIVITY_FORTIFYING,
ACTIVITY_IDLE, ACTIVITY_SENTRY)
from .city_wrapper import PersistentCityProduction
from .core import Wrapper
from .dipl_wrapper import DiplomacyLoop, TruncateDiplCity
from .embark_wrapper import EmbarkWrapper
from .tech_wrapper import CombineTechResearchGoal
from .utils import update
import numpy as np | 3,940 |
tensor_debug = fc_args["debug.tensor_debug"]
class TensorAction(Wrapper):
"""
A wrapper that defines tensor action spaces, transforms tensor actions into
actions that could be handeled by FreecivBaseEnv instance, and adds masks to
observations.
TensorAction wrapper is composed of five wrappers, including `TruncateDiplCity`,
`DiplomacyLoop`, `CombineTechResearchGoal`, `PersistentCityProduction`, and `EmbarkWrapper`.
Parameters
----------
env: TensorBase
A FreecivBaseEnv instance that has been wrapped by TensorBase.
Attributes
----------
aciton_config: dict
a dict that configs that specify sizes of mutable entities and action layout.
mask: dict
a dict of masks of type numpy ndarray indicating available actions and entities. 0-> unavilalbe, 1->availble.
available_actions: dict
cached info['available_actions'], a dict that indicates available actions.
action_space: gymnasium.spaces.Dict
a gymnasium.spaces.Dict with keys `['actor_type','city_id','unit_id',
'dipl_id','city_action_type','unit_action_type','dipl_action_type',
'gov_action_type','tech_action_type']`
"""
def __init__(self, env: TensorBase):
self.action_config = env.get_wrapper_attr("config")
self.action_config["resize"]["dipl"] = self.action_config["resize"][
"others_player"
]
self.actor_type_list = self.action_config["actor_type_list"]
self.available_actions = {}
self.mask = {}
self.__turn = -1
self.__dealing_with_incoming = False
super().__init__(
TruncateDiplCity(
DiplomacyLoop(
|
tensor_debug = fc_args["debug.tensor_debug"]
class TensorAction(Wrapper):
"""
A wrapper that defines tensor action spaces, transforms tensor actions into
actions that could be handeled by FreecivBaseEnv instance, and adds masks to
observations.
TensorAction wrapper is composed of five wrappers, including `TruncateDiplCity`,
`DiplomacyLoop`, `CombineTechResearchGoal`, `PersistentCityProduction`, and `EmbarkWrapper`.
Parameters
----------
env: TensorBase
A FreecivBaseEnv instance that has been wrapped by TensorBase.
Attributes
----------
aciton_config: dict
a dict that configs that specify sizes of mutable entities and action layout.
mask: dict
a dict of masks of type numpy ndarray indicating available actions and entities. 0-> unavilalbe, 1->availble.
available_actions: dict
cached info['available_actions'], a dict that indicates available actions.
action_space: gymnasium.spaces.Dict
a gymnasium.spaces.Dict with keys `['actor_type','city_id','unit_id',
'dipl_id','city_action_type','unit_action_type','dipl_action_type',
'gov_action_type','tech_action_type']`
"""
def __init__(self, env: TensorBase):
self.action_config = env.get_wrapper_attr("config")
self.action_config["resize"]["dipl"] = self.action_config["resize"][
"others_player"
]
self.actor_type_list = self.action_config["actor_type_list"]
self.available_actions = {}
self.mask = {}
self.__turn = -1
self.__dealing_with_incoming = False
super().__init__(
TruncateDiplCity(
DiplomacyLoop( | CombineTechResearchGoal( | 5 | 2023-11-18 19:35:50+00:00 | 8k |
RAIVNLab/MatFormer-OLMo | conftest.py | [
{
"identifier": "DataConfig",
"path": "olmo/config.py",
"snippet": "class DataConfig(BaseConfig):\n paths: Optional[List[str]] = None\n datasets: Optional[Dict[str, List[str]]] = None\n pad_direction: PaddingDirection = PaddingDirection.right\n num_workers: int = 0\n drop_last: bool = Fal... | from typing import List
from olmo.config import (
DataConfig,
ModelConfig,
OptimizerConfig,
PaddingDirection,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
)
from olmo.tokenizer import Tokenizer
import pytest | 5,178 |
TEST_MODEL = "gpt2"
LOREM_IPSUM_1 = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
LOREM_IPSUM_2 = """
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque
laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores
eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem
ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius
modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.
Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit
laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure
reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur,
vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
"""
@pytest.fixture(scope="function")
def model_config() -> ModelConfig:
return ModelConfig(
vocab_size=50257,
eos_token_id=50256,
pad_token_id=50256,
d_model=128,
n_heads=2,
n_layers=3,
max_sequence_length=512,
)
@pytest.fixture(scope="function")
def tokenizer() -> Tokenizer:
return Tokenizer.from_pretrained(TEST_MODEL)
@pytest.fixture(scope="function")
def train_config(tmp_path, model_config) -> TrainConfig:
return TrainConfig(
model=model_config,
optimizer=OptimizerConfig(),
scheduler=SchedulerConfig(),
|
TEST_MODEL = "gpt2"
LOREM_IPSUM_1 = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
LOREM_IPSUM_2 = """
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque
laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores
eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem
ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius
modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.
Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit
laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure
reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur,
vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
"""
@pytest.fixture(scope="function")
def model_config() -> ModelConfig:
return ModelConfig(
vocab_size=50257,
eos_token_id=50256,
pad_token_id=50256,
d_model=128,
n_heads=2,
n_layers=3,
max_sequence_length=512,
)
@pytest.fixture(scope="function")
def tokenizer() -> Tokenizer:
return Tokenizer.from_pretrained(TEST_MODEL)
@pytest.fixture(scope="function")
def train_config(tmp_path, model_config) -> TrainConfig:
return TrainConfig(
model=model_config,
optimizer=OptimizerConfig(),
scheduler=SchedulerConfig(), | data=DataConfig( | 0 | 2023-11-14 02:24:07+00:00 | 8k |
1in-oos/ccplus | caringcaribou/tests/test_iso_14229_1.py | [
{
"identifier": "DEFAULT_INTERFACE",
"path": "caringcaribou/utils/can_actions.py",
"snippet": "DEFAULT_INTERFACE = None"
},
{
"identifier": "MockEcuIso14229",
"path": "caringcaribou/tests/mock/mock_ecu_uds.py",
"snippet": "class MockEcuIso14229(MockEcuIsoTp, MockEcu):\n \"\"\"ISO-1422... | from caringcaribou.utils.can_actions import DEFAULT_INTERFACE
from caringcaribou.tests.mock.mock_ecu_uds import MockEcuIso14229
from caringcaribou.utils import iso14229_1
from caringcaribou.utils import iso15765_2
import can
import unittest | 4,991 | from __future__ import print_function
class DiagnosticsOverIsoTpTestCase(unittest.TestCase):
ARB_ID_REQUEST = 0x200C
ARB_ID_RESPONSE = 0x200D
def setUp(self):
# Initialize mock ECU
self.ecu = MockEcuIso14229(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE)
self.ecu.start_server()
# Initialize virtual CAN bus
can_bus = can.Bus(DEFAULT_INTERFACE)
# Setup diagnostics on top of ISO-TP layer
| from __future__ import print_function
class DiagnosticsOverIsoTpTestCase(unittest.TestCase):
ARB_ID_REQUEST = 0x200C
ARB_ID_RESPONSE = 0x200D
def setUp(self):
# Initialize mock ECU
self.ecu = MockEcuIso14229(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE)
self.ecu.start_server()
# Initialize virtual CAN bus
can_bus = can.Bus(DEFAULT_INTERFACE)
# Setup diagnostics on top of ISO-TP layer | self.tp = iso15765_2.IsoTp(self.ARB_ID_REQUEST, self.ARB_ID_RESPONSE, bus=can_bus) | 3 | 2023-11-13 05:05:46+00:00 | 8k |
L1bra1/WeakMotion | gen_data/gen_weak_waymo_utils.py | [
{
"identifier": "Box",
"path": "gen_data/nuscenes/utils/data_classes.py",
"snippet": "class Box:\n \"\"\" Simple data class representing a 3d box including, label, score and velocity. \"\"\"\n\n def __init__(self,\n center: List[float],\n size: List[float],\n ... | import numpy as np
from pathlib import Path
from functools import reduce
from gen_data.nuscenes.utils.data_classes import Box
from pyquaternion import Quaternion
from gen_data.waymo_data_utils import load_waymo_points, point_in_hull_fast | 3,973 | """
Prepare the Foreground/Background information for Waymo data.
"""
obj_class_map = {
"Vehicle": 1, "Pedestrian":2, "Cyclist": 3, "Others": 4
} # take sign as others
def gen_weak_supervision(scene_name, lidar_path, ann_data, i, pc_random_index_dict, pc_down_sample_dict, num_down_sample = 50000):
''' get current info'''
ann_i = ann_data[i]
# extract info about reference key
lidar_pc_path = lidar_path / "{:04d}.npy".format(i)
cur_xyz = load_waymo_points(lidar_pc_path)
ref_pose = ann_i["pose"]
ref_token = "{}_{:04d}".format(scene_name, i)
ref_ts = ann_i["time_stamp"]
save_weak_dict = dict()
id_list = [-5, 0, 5]
for j in range(3):
sweep_index = i + id_list[j]
sweep_ann = ann_data[sweep_index]
sweep_lidar_pc_path = lidar_path / "{:04d}.npy".format(sweep_index)
sweep_pose = sweep_ann["pose"]
sweep_pc = load_waymo_points(sweep_lidar_pc_path)
sweep_token = "{}_{:04d}".format(scene_name, sweep_index)
sweep_ts = sweep_ann["time_stamp"]
time_lag = sweep_ts - ref_ts
# ref_from_global * global_from_current = ref_from_current
tm = reduce(np.dot, [np.linalg.inv(ref_pose), sweep_pose])
sweep_pc = sweep_pc.T
sweep_pc[:3, :] = tm.dot(np.vstack((sweep_pc[:3, :], np.ones(sweep_pc.shape[1]))))[:3, :]
points_label = get_label_info(sweep_ann, lidar_path, sweep_index)
# down-sample
down_sample_idx, pc_down_sample_dict = gen_random_index_for_pc(sweep_pc, sweep_token, pc_down_sample_dict)
sweep_pc_t = sweep_pc.transpose((1, 0))
# We only preserve a fixed number of points for each point cloud
if down_sample_idx.shape[0] > num_down_sample:
sampled_sweep_pc_t = sweep_pc_t[down_sample_idx[:num_down_sample]]
sampled_points_label = points_label[down_sample_idx[:num_down_sample]].astype(np.int32)
else:
sampled_sweep_pc_t = sweep_pc_t[down_sample_idx]
sampled_points_label = points_label[down_sample_idx].astype(np.int32)
sampled_sweep_pc = sampled_sweep_pc_t.transpose((1, 0))
save_weak_dict['synchronized_pc_' + str(j)] = sampled_sweep_pc
save_weak_dict['frame_id_' + str(j)] = sweep_token
save_weak_dict['ts_' + str(j)] = time_lag
save_weak_dict['points_label_' + str(j)] = sampled_points_label
sample_idx, pc_random_index_dict = gen_random_index_for_pc(sampled_sweep_pc, sweep_token, pc_random_index_dict)
save_weak_dict['sample_idx_' + str(j)] = sample_idx.astype(np.int32)
return save_weak_dict, pc_random_index_dict, pc_down_sample_dict
def get_label_info(sweep_ann, lidar_path, sweep_index):
sweep_nusc_box_dict = {}
for obj_idx, obj_id in enumerate(sweep_ann["annos"]['obj_ids']):
# vehicle system
lwh = sweep_ann["annos"]["dimensions"][obj_idx] # c_x, c_y, c_z
ctr = sweep_ann["annos"]["location"][obj_idx] # l, w, h
yaw = sweep_ann["annos"]["heading_angles"][obj_idx]
name = sweep_ann["annos"]["name"][obj_idx]
nusc_box = Box(
ctr, [lwh[1], lwh[0], lwh[2]],
Quaternion(axis=[0, 0, 1], angle=yaw), name=name, token=obj_idx
)
sweep_nusc_box_dict[obj_id] = nusc_box
# # ----------init-------------------
lidar_pc_path = lidar_path / "{:04d}.npy".format(sweep_index)
sweep_xyz = load_waymo_points(lidar_pc_path)
sweep_cls_mask = np.zeros([len(sweep_xyz), 1], dtype=np.int64)
inbox_idx_dict = {}
for box_token, sweep_box in sweep_nusc_box_dict.items():
| """
Prepare the Foreground/Background information for Waymo data.
"""
obj_class_map = {
"Vehicle": 1, "Pedestrian":2, "Cyclist": 3, "Others": 4
} # take sign as others
def gen_weak_supervision(scene_name, lidar_path, ann_data, i, pc_random_index_dict, pc_down_sample_dict, num_down_sample = 50000):
''' get current info'''
ann_i = ann_data[i]
# extract info about reference key
lidar_pc_path = lidar_path / "{:04d}.npy".format(i)
cur_xyz = load_waymo_points(lidar_pc_path)
ref_pose = ann_i["pose"]
ref_token = "{}_{:04d}".format(scene_name, i)
ref_ts = ann_i["time_stamp"]
save_weak_dict = dict()
id_list = [-5, 0, 5]
for j in range(3):
sweep_index = i + id_list[j]
sweep_ann = ann_data[sweep_index]
sweep_lidar_pc_path = lidar_path / "{:04d}.npy".format(sweep_index)
sweep_pose = sweep_ann["pose"]
sweep_pc = load_waymo_points(sweep_lidar_pc_path)
sweep_token = "{}_{:04d}".format(scene_name, sweep_index)
sweep_ts = sweep_ann["time_stamp"]
time_lag = sweep_ts - ref_ts
# ref_from_global * global_from_current = ref_from_current
tm = reduce(np.dot, [np.linalg.inv(ref_pose), sweep_pose])
sweep_pc = sweep_pc.T
sweep_pc[:3, :] = tm.dot(np.vstack((sweep_pc[:3, :], np.ones(sweep_pc.shape[1]))))[:3, :]
points_label = get_label_info(sweep_ann, lidar_path, sweep_index)
# down-sample
down_sample_idx, pc_down_sample_dict = gen_random_index_for_pc(sweep_pc, sweep_token, pc_down_sample_dict)
sweep_pc_t = sweep_pc.transpose((1, 0))
# We only preserve a fixed number of points for each point cloud
if down_sample_idx.shape[0] > num_down_sample:
sampled_sweep_pc_t = sweep_pc_t[down_sample_idx[:num_down_sample]]
sampled_points_label = points_label[down_sample_idx[:num_down_sample]].astype(np.int32)
else:
sampled_sweep_pc_t = sweep_pc_t[down_sample_idx]
sampled_points_label = points_label[down_sample_idx].astype(np.int32)
sampled_sweep_pc = sampled_sweep_pc_t.transpose((1, 0))
save_weak_dict['synchronized_pc_' + str(j)] = sampled_sweep_pc
save_weak_dict['frame_id_' + str(j)] = sweep_token
save_weak_dict['ts_' + str(j)] = time_lag
save_weak_dict['points_label_' + str(j)] = sampled_points_label
sample_idx, pc_random_index_dict = gen_random_index_for_pc(sampled_sweep_pc, sweep_token, pc_random_index_dict)
save_weak_dict['sample_idx_' + str(j)] = sample_idx.astype(np.int32)
return save_weak_dict, pc_random_index_dict, pc_down_sample_dict
def get_label_info(sweep_ann, lidar_path, sweep_index):
sweep_nusc_box_dict = {}
for obj_idx, obj_id in enumerate(sweep_ann["annos"]['obj_ids']):
# vehicle system
lwh = sweep_ann["annos"]["dimensions"][obj_idx] # c_x, c_y, c_z
ctr = sweep_ann["annos"]["location"][obj_idx] # l, w, h
yaw = sweep_ann["annos"]["heading_angles"][obj_idx]
name = sweep_ann["annos"]["name"][obj_idx]
nusc_box = Box(
ctr, [lwh[1], lwh[0], lwh[2]],
Quaternion(axis=[0, 0, 1], angle=yaw), name=name, token=obj_idx
)
sweep_nusc_box_dict[obj_id] = nusc_box
# # ----------init-------------------
lidar_pc_path = lidar_path / "{:04d}.npy".format(sweep_index)
sweep_xyz = load_waymo_points(lidar_pc_path)
sweep_cls_mask = np.zeros([len(sweep_xyz), 1], dtype=np.int64)
inbox_idx_dict = {}
for box_token, sweep_box in sweep_nusc_box_dict.items(): | inbox_idx = point_in_hull_fast(sweep_xyz, sweep_box) | 2 | 2023-11-12 07:03:29+00:00 | 8k |
c3exchange/c3-smartcontracts-v1 | contracts_unified/core/methods/update_instrument.py | [
{
"identifier": "perform_pool_move",
"path": "contracts_unified/core/internal/perform_pool_move.py",
"snippet": "@ABIReturnSubroutine\ndef perform_pool_move(\n account: AccountAddress,\n instrument_id: InstrumentId,\n transfer_amount: SignedAmount,\n) -> Expr:\n \"\"\"\n Transfers from th... | from typing import cast
from pyteal import (
ABIReturnSubroutine,
Assert,
Expr,
Global,
If,
InnerTxnBuilder,
Int,
Seq,
Txn,
TxnField,
TxnType,
abi,
)
from contracts_unified.core.internal.perform_pool_move import perform_pool_move
from contracts_unified.core.internal.setup import setup
from contracts_unified.core.state_handler.global_handler import GlobalStateHandler
from contracts_unified.library.c3types import (
Amount,
AssetId,
InstrumentId,
InstrumentListElement,
InterestRate,
Ratio,
RelativeTimestamp,
)
from contracts_unified.library.c3types_server import UpdateInstrumentInfo
from contracts_unified.library.constants import RATE_ONE | 5,686 | """
Implements Core contract method for adding an instrument.
"""
def inner_asset_opt_in(asset_id: AssetId) -> Expr:
"""Inner transaction that opts in to an ASA"""
return InnerTxnBuilder.Execute(
{
TxnField.type_enum: TxnType.AssetTransfer,
TxnField.xfer_asset: asset_id.get(),
TxnField.asset_receiver: Global.current_application_address(),
TxnField.asset_amount: Int(0),
TxnField.fee: Int(0),
}
)
@ABIReturnSubroutine
def update_instrument(
info: UpdateInstrumentInfo,
opup_budget: Amount,
) -> Expr:
"""Implements the method that adds an instrument to the Core contract storage box.
Arguments:
info (UpdateInstrumentInfo): Instrument information to add or update.
opup_budget (Amount): Additional computation budget to allocate to this transaction.
"""
abi_zero = abi.Uint64()
abi_rate_one = abi.Uint64()
abi_zero_address = abi.Address()
timestamp = RelativeTimestamp()
asset_id = AssetId()
initial_haircut = Ratio()
initial_margin = Ratio()
maintenance_haircut = Ratio()
maintenance_margin = Ratio()
optimal_utilization = Ratio()
| """
Implements Core contract method for adding an instrument.
"""
def inner_asset_opt_in(asset_id: AssetId) -> Expr:
"""Inner transaction that opts in to an ASA"""
return InnerTxnBuilder.Execute(
{
TxnField.type_enum: TxnType.AssetTransfer,
TxnField.xfer_asset: asset_id.get(),
TxnField.asset_receiver: Global.current_application_address(),
TxnField.asset_amount: Int(0),
TxnField.fee: Int(0),
}
)
@ABIReturnSubroutine
def update_instrument(
info: UpdateInstrumentInfo,
opup_budget: Amount,
) -> Expr:
"""Implements the method that adds an instrument to the Core contract storage box.
Arguments:
info (UpdateInstrumentInfo): Instrument information to add or update.
opup_budget (Amount): Additional computation budget to allocate to this transaction.
"""
abi_zero = abi.Uint64()
abi_rate_one = abi.Uint64()
abi_zero_address = abi.Address()
timestamp = RelativeTimestamp()
asset_id = AssetId()
initial_haircut = Ratio()
initial_margin = Ratio()
maintenance_haircut = Ratio()
maintenance_margin = Ratio()
optimal_utilization = Ratio() | min_rate = InterestRate() | 3 | 2023-11-17 20:54:15+00:00 | 8k |
gunderson-dettmer/CE2OCF | CE2OCF/ce/mocks/objects.py | [
{
"identifier": "convert_ce_answers_xml_to_json_string",
"path": "CE2OCF/ce/transforms/json.py",
"snippet": "def convert_ce_answers_xml_to_json_string(xml_data: str | ET.ElementTree) -> str:\n \"\"\"\n Given CE XML answer export, convert it to JSON format that the API generates.\n\n :param xml_... | import itertools
import random
import xml.etree.ElementTree as ET
from CE2OCF.ce.transforms.json import (
convert_ce_answers_xml_to_json_string,
)
from CE2OCF.ce.transforms.xml import (
convert_pydantic_to_xml_elem,
xml_elements_to_ce_xml_tree,
)
from CE2OCF.ocf.mocks.company import mock_company
from CE2OCF.ocf.mocks.officers import mock_director
from CE2OCF.ocf.mocks.stockholders import mock_stockholder, sum_shares
from CE2OCF.ocf.postprocessors import (
GD_HUMAN_REPEAT_SELECTIONS_TO_VAR_NAMES,
)
from CE2OCF.types.enums import RepeatableFields, TransferRestrictionEnum
from CE2OCF.types.models import (
BylawVars,
Company,
Director,
FormVars,
Stockholder,
)
from CE2OCF.utils.log_utils import logger | 4,036 | from __future__ import annotations
def mock_formvars(
override_repeated_fields: list[RepeatableFields] | None = None, use_gunderson_repeat_names: bool = True
) -> FormVars:
"""
Args:
override_repeated_fields:
use_gunderson_repeat_names: Our repeat variable values in the CE jsons are different than the actual variable
names that are repeated, so you need a mapping dict
Returns:
"""
logger.debug(f"mock_formvars started with override_repeated_fields: {override_repeated_fields}")
if override_repeated_fields is None:
logger.debug("unique_repeatable_fields is None... prepare random sample...")
unique_repeatable_fields = random.sample(
[el.value for el in RepeatableFields],
k=random.randint(0, len(RepeatableFields)),
)
else:
logger.debug("unique_repeatable_fields is NOT None...")
unique_repeatable_fields = [el.value for el in override_repeated_fields]
if use_gunderson_repeat_names:
var_name_to_template_val_lookup = {v: k for k, v in GD_HUMAN_REPEAT_SELECTIONS_TO_VAR_NAMES.items()}
unique_repeatable_fields = [var_name_to_template_val_lookup[v] for v in unique_repeatable_fields]
logger.debug(f"unique_repeatable_fields: {unique_repeatable_fields} {[type(v) for v in unique_repeatable_fields]}")
return FormVars(
StockholderInfoSame=unique_repeatable_fields,
BroadDescriptionAssignedTechnology_S1="Some Technology",
UsingTopTemplateFlag=True,
UsingTopTemplateFlagFO_IAL="Yes",
UsingTopTemplateFlag_IA="Yes",
Waiver220=True,
IndemnificationAgrIncluded=True,
EmployeeNoncompete=True,
)
def mock_bylawvars() -> BylawVars:
return BylawVars(
RoFR=True,
QuasiCA=True,
TransferRestrictions=True,
TransferRestrictionsLanguage=True,
TransferRestrictionDate=True,
| from __future__ import annotations
def mock_formvars(
override_repeated_fields: list[RepeatableFields] | None = None, use_gunderson_repeat_names: bool = True
) -> FormVars:
"""
Args:
override_repeated_fields:
use_gunderson_repeat_names: Our repeat variable values in the CE jsons are different than the actual variable
names that are repeated, so you need a mapping dict
Returns:
"""
logger.debug(f"mock_formvars started with override_repeated_fields: {override_repeated_fields}")
if override_repeated_fields is None:
logger.debug("unique_repeatable_fields is None... prepare random sample...")
unique_repeatable_fields = random.sample(
[el.value for el in RepeatableFields],
k=random.randint(0, len(RepeatableFields)),
)
else:
logger.debug("unique_repeatable_fields is NOT None...")
unique_repeatable_fields = [el.value for el in override_repeated_fields]
if use_gunderson_repeat_names:
var_name_to_template_val_lookup = {v: k for k, v in GD_HUMAN_REPEAT_SELECTIONS_TO_VAR_NAMES.items()}
unique_repeatable_fields = [var_name_to_template_val_lookup[v] for v in unique_repeatable_fields]
logger.debug(f"unique_repeatable_fields: {unique_repeatable_fields} {[type(v) for v in unique_repeatable_fields]}")
return FormVars(
StockholderInfoSame=unique_repeatable_fields,
BroadDescriptionAssignedTechnology_S1="Some Technology",
UsingTopTemplateFlag=True,
UsingTopTemplateFlagFO_IAL="Yes",
UsingTopTemplateFlag_IA="Yes",
Waiver220=True,
IndemnificationAgrIncluded=True,
EmployeeNoncompete=True,
)
def mock_bylawvars() -> BylawVars:
return BylawVars(
RoFR=True,
QuasiCA=True,
TransferRestrictions=True,
TransferRestrictionsLanguage=True,
TransferRestrictionDate=True, | TransferRestrictionStock=TransferRestrictionEnum.ALL_STOCK, | 9 | 2023-11-13 15:50:53+00:00 | 8k |
ehennenfent/live_illustrate | live_illustrate/__main__.py | [
{
"identifier": "ImageRenderer",
"path": "live_illustrate/render.py",
"snippet": "class ImageRenderer(AsyncThread):\n def __init__(self, model: str, image_size: str, image_quality: str, image_style: str) -> None:\n super().__init__(\"ImageRenderer\")\n self.openai_client: OpenAI = OpenA... | import argparse
import logging
from pathlib import Path
from threading import Thread
from time import sleep
from webbrowser import open_new_tab
from dotenv import load_dotenv
from .render import ImageRenderer
from .serve import ImageServer
from .session_data import SessionData
from .summarize import TextSummarizer
from .text_buffer import TextBuffer
from .transcribe import AudioTranscriber
from .util import Image, Summary, Transcription, is_transcription_interesting | 3,680 |
load_dotenv()
DEFAULT_DATA_DIR = Path(__file__).parent.parent.joinpath("data")
def get_args() -> argparse.Namespace:
parser = argparse.ArgumentParser("Automatic live illustration for table-top RPGs")
parser.add_argument(
"--audio_model",
default="medium.en",
help="Whisper model to use for audio transcription",
choices=["tiny.en", "base.en", "small.en", "medium.en", "large", "large-v2", "large-v3"],
)
parser.add_argument(
"--wait_minutes",
default=7.5,
type=float,
help="How frequently to summarize the conversation and generate an image",
)
parser.add_argument(
"--max_context",
default=2000, # very roughly ten minutes or so?
type=int,
help="Maximum number of tokens to summarize from the conversations",
)
parser.add_argument(
"--summarize_model",
default="gpt-3.5-turbo",
help="LLM to use for summarizing transcription",
choices=["gpt-3.5-turbo", "gpt-4"],
)
parser.add_argument(
"--image_model",
default="dall-e-3",
help="Diffusion model to use for generating image",
choices=["dall-e-3", "dall-e-2"],
)
parser.add_argument(
"--image_size",
default="1792x1024",
help="Size of image to render (smaller is cheaper)",
choices=["1792x1024", "1024x1792", "1024x1024", "512x512", "256x256"],
)
parser.add_argument(
"--image_quality",
default="standard",
help="How fancy of an image to render",
choices=["standard", "hd"],
)
parser.add_argument(
"--image_style",
default="vivid",
help="How stylized of an image to render",
choices=["vivid", "natural"],
)
parser.add_argument(
"--server_host",
default="0.0.0.0",
help="Address to bind web server",
)
parser.add_argument(
"--server_port",
default=8080,
type=int,
help="Port to serve HTML viewer on",
)
parser.add_argument(
"--open",
action="store_true",
help="Automatically open a browser tab for the rendered images",
)
parser.add_argument(
"--persistence_of_memory",
default=0.2, # Expressed as a fraction of the total buffered transcription
type=float,
help="How much of the previous transcription to retain after generating each summary. 0 - 1.0",
)
parser.add_argument(
"-v",
"--verbose",
action="count",
default=0,
)
return parser.parse_args()
def main() -> None:
args = get_args()
logging.basicConfig(format="%(name)s: %(message)s", level=logging.DEBUG if args.verbose > 0 else logging.INFO)
# tweak loggers for client libraries
logging.getLogger("httpx").setLevel(logging.INFO if args.verbose > 0 else logging.WARNING) # used by OpenAI
logging.getLogger("requests").setLevel(logging.INFO if args.verbose > 0 else logging.WARNING)
logging.getLogger("werkzeug").setLevel(logging.INFO if args.verbose > 0 else logging.WARNING) # flask
# create each of our thread objects with the apppropriate command line args
transcriber = AudioTranscriber(model=args.audio_model)
buffer = TextBuffer(
wait_minutes=args.wait_minutes, max_context=args.max_context, persistence=args.persistence_of_memory
)
summarizer = TextSummarizer(model=args.summarize_model)
renderer = ImageRenderer(
model=args.image_model,
image_size=args.image_size,
image_quality=args.image_quality,
image_style=args.image_style,
)
server = ImageServer(
host=args.server_host, port=args.server_port, default_image=f"https://placehold.co/{args.image_size}/png"
)
with SessionData(DEFAULT_DATA_DIR, echo=True) as session_data:
# wire up some callbacks to save the intermediate data and forward it along
|
load_dotenv()
DEFAULT_DATA_DIR = Path(__file__).parent.parent.joinpath("data")
def get_args() -> argparse.Namespace:
parser = argparse.ArgumentParser("Automatic live illustration for table-top RPGs")
parser.add_argument(
"--audio_model",
default="medium.en",
help="Whisper model to use for audio transcription",
choices=["tiny.en", "base.en", "small.en", "medium.en", "large", "large-v2", "large-v3"],
)
parser.add_argument(
"--wait_minutes",
default=7.5,
type=float,
help="How frequently to summarize the conversation and generate an image",
)
parser.add_argument(
"--max_context",
default=2000, # very roughly ten minutes or so?
type=int,
help="Maximum number of tokens to summarize from the conversations",
)
parser.add_argument(
"--summarize_model",
default="gpt-3.5-turbo",
help="LLM to use for summarizing transcription",
choices=["gpt-3.5-turbo", "gpt-4"],
)
parser.add_argument(
"--image_model",
default="dall-e-3",
help="Diffusion model to use for generating image",
choices=["dall-e-3", "dall-e-2"],
)
parser.add_argument(
"--image_size",
default="1792x1024",
help="Size of image to render (smaller is cheaper)",
choices=["1792x1024", "1024x1792", "1024x1024", "512x512", "256x256"],
)
parser.add_argument(
"--image_quality",
default="standard",
help="How fancy of an image to render",
choices=["standard", "hd"],
)
parser.add_argument(
"--image_style",
default="vivid",
help="How stylized of an image to render",
choices=["vivid", "natural"],
)
parser.add_argument(
"--server_host",
default="0.0.0.0",
help="Address to bind web server",
)
parser.add_argument(
"--server_port",
default=8080,
type=int,
help="Port to serve HTML viewer on",
)
parser.add_argument(
"--open",
action="store_true",
help="Automatically open a browser tab for the rendered images",
)
parser.add_argument(
"--persistence_of_memory",
default=0.2, # Expressed as a fraction of the total buffered transcription
type=float,
help="How much of the previous transcription to retain after generating each summary. 0 - 1.0",
)
parser.add_argument(
"-v",
"--verbose",
action="count",
default=0,
)
return parser.parse_args()
def main() -> None:
args = get_args()
logging.basicConfig(format="%(name)s: %(message)s", level=logging.DEBUG if args.verbose > 0 else logging.INFO)
# tweak loggers for client libraries
logging.getLogger("httpx").setLevel(logging.INFO if args.verbose > 0 else logging.WARNING) # used by OpenAI
logging.getLogger("requests").setLevel(logging.INFO if args.verbose > 0 else logging.WARNING)
logging.getLogger("werkzeug").setLevel(logging.INFO if args.verbose > 0 else logging.WARNING) # flask
# create each of our thread objects with the apppropriate command line args
transcriber = AudioTranscriber(model=args.audio_model)
buffer = TextBuffer(
wait_minutes=args.wait_minutes, max_context=args.max_context, persistence=args.persistence_of_memory
)
summarizer = TextSummarizer(model=args.summarize_model)
renderer = ImageRenderer(
model=args.image_model,
image_size=args.image_size,
image_quality=args.image_quality,
image_style=args.image_style,
)
server = ImageServer(
host=args.server_host, port=args.server_port, default_image=f"https://placehold.co/{args.image_size}/png"
)
with SessionData(DEFAULT_DATA_DIR, echo=True) as session_data:
# wire up some callbacks to save the intermediate data and forward it along | def on_text_transcribed(transcription: Transcription) -> None: | 8 | 2023-11-18 05:42:54+00:00 | 8k |
cyberark/ark-sdk-python | ark_sdk_python/models/actions/services/ark_dpa_exec_action_consts.py | [
{
"identifier": "ArkModel",
"path": "ark_sdk_python/models/ark_model.py",
"snippet": "class ArkModel(BaseModel):\n class Config:\n allow_population_by_field_name = True"
},
{
"identifier": "ArkServiceActionDefinition",
"path": "ark_sdk_python/models/actions/ark_service_action_defin... | from typing import Dict, Final, Optional, Type
from ark_sdk_python.models import ArkModel
from ark_sdk_python.models.actions.ark_service_action_definition import ArkServiceActionDefinition
from ark_sdk_python.models.cli_services.dpa.policies_editor.common import (
ArkDPACommitPolicies,
ArkDPAEditPolicies,
ArkDPAGetPoliciesStatus,
ArkDPALoadPolicies,
ArkDPAPoliciesDiff,
ArkDPARemovePolicies,
ArkDPAResetPolicies,
ArkDPAViewPolicies,
)
from ark_sdk_python.models.cli_services.dpa.policies_editor.db import ArkDPADBGeneratePolicy
from ark_sdk_python.models.cli_services.dpa.policies_editor.vm import ArkDPAVMGeneratePolicy
from ark_sdk_python.models.services.dpa.certificates import (
ArkDPACertificatesFilter,
ArkDPACreateCertificate,
ArkDPADeleteCertificate,
ArkDPAGetCertificate,
ArkDPAUpdateCertificate,
)
from ark_sdk_python.models.services.dpa.db import ArkDPADBMysqlExecution, ArkDPADBOracleGenerateAssets, ArkDPADBPsqlExecution
from ark_sdk_python.models.services.dpa.k8s.ark_dpa_k8s_generate_kubeconfig import ArkDPAK8SGenerateKubeConfig
from ark_sdk_python.models.services.dpa.policies.common import ArkDPADeletePolicy, ArkDPAGetPolicy, ArkDPAUpdatePolicyStatus
from ark_sdk_python.models.services.dpa.policies.db import ArkDPADBAddPolicy, ArkDPADBPoliciesFilter, ArkDPADBUpdatePolicy
from ark_sdk_python.models.services.dpa.policies.vm import ArkDPAVMAddPolicy, ArkDPAVMPoliciesFilter, ArkDPAVMUpdatePolicy
from ark_sdk_python.models.services.dpa.secrets.db import (
ArkDPADBAddSecret,
ArkDPADBDeleteSecret,
ArkDPADBDisableSecret,
ArkDPADBEnableSecret,
ArkDPADBGetSecret,
ArkDPADBSecretsFilter,
ArkDPADBUpdateSecret,
)
from ark_sdk_python.models.services.dpa.sso import (
ArkDPASSOGetShortLivedClientCertificate,
ArkDPASSOGetShortLivedOracleWallet,
ArkDPASSOGetShortLivedPassword,
ArkDPASSOGetShortLivedRDPFile,
)
from ark_sdk_python.models.services.dpa.workspaces.db import (
ArkDPADBAddDatabase,
ArkDPADBDatabasesFilter,
ArkDPADBDeleteDatabase,
ArkDPADBGetDatabase,
ArkDPADBUpdateDatabase,
) | 7,196 |
WORKSPACES_DB_ACTION_TO_SCHEMA_MAP: Final[Dict[(str, Optional[Type[ArkModel]])]] = {
'add-database': ArkDPADBAddDatabase,
'delete-database': ArkDPADBDeleteDatabase,
'update-database': ArkDPADBUpdateDatabase,
'list-databases': None,
'list-databases-by': ArkDPADBDatabasesFilter,
'database': ArkDPADBGetDatabase,
'databases-stats': None,
}
WORKSPACES_DB_ACTION: Final[ArkServiceActionDefinition] = ArkServiceActionDefinition(
action_name='db', schemas=WORKSPACES_DB_ACTION_TO_SCHEMA_MAP
)
WORKSPACES_ACTION: Final[ArkServiceActionDefinition] = ArkServiceActionDefinition(
action_name='workspaces', subactions=[WORKSPACES_DB_ACTION]
)
POLICIES_VM_ACTION_TO_SCHEMA_MAP: Final[Dict[(str, Optional[Type[ArkModel]])]] = {
'add-policy': ArkDPAVMAddPolicy,
|
WORKSPACES_DB_ACTION_TO_SCHEMA_MAP: Final[Dict[(str, Optional[Type[ArkModel]])]] = {
'add-database': ArkDPADBAddDatabase,
'delete-database': ArkDPADBDeleteDatabase,
'update-database': ArkDPADBUpdateDatabase,
'list-databases': None,
'list-databases-by': ArkDPADBDatabasesFilter,
'database': ArkDPADBGetDatabase,
'databases-stats': None,
}
WORKSPACES_DB_ACTION: Final[ArkServiceActionDefinition] = ArkServiceActionDefinition(
action_name='db', schemas=WORKSPACES_DB_ACTION_TO_SCHEMA_MAP
)
WORKSPACES_ACTION: Final[ArkServiceActionDefinition] = ArkServiceActionDefinition(
action_name='workspaces', subactions=[WORKSPACES_DB_ACTION]
)
POLICIES_VM_ACTION_TO_SCHEMA_MAP: Final[Dict[(str, Optional[Type[ArkModel]])]] = {
'add-policy': ArkDPAVMAddPolicy, | 'delete-policy': ArkDPADeletePolicy, | 21 | 2023-11-13 09:24:31+00:00 | 8k |
CorentinJ/transcription-diff | transcription_diff/text_normalization.py | [
{
"identifier": "normalize_numbers",
"path": "transcription_diff/number_normalization.py",
"snippet": "def normalize_numbers(text: str):\n words = re.split(\"(\\s+)\", text)\n mapping = list(zip(words, [SliceMap.identity(len(word)) for word in words]))\n\n text, mapping = _remove_commas(text, m... | import inspect
import logging
import re
import unicodedata
from typing import Tuple, Callable, List
from langcodes import Language
from transcription_diff.number_normalization import normalize_numbers
from transcription_diff.slice_map import SliceMap | 4,620 |
logger = logging.getLogger(__name__)
# Regular expressions matching whitespace. When using with re.split(), the second one will keep whitespaces in the
# output because all captured groups are kept.
_whitespace_excl_re = re.compile(r'\s+')
_whitespace_incl_re = re.compile(r'(\s+)')
# List of (regular expression, replacement) pairs for abbreviations:
_abbreviations = [
(re.compile('\\b%s\\.' % abbrev, re.IGNORECASE), expanded)
for abbrev, expanded in [
('mrs', 'misess'),
('mr', 'mister'),
('dr', 'doctor'),
('st', 'saint'),
('co', 'company'),
('jr', 'junior'),
('maj', 'major'),
('gen', 'general'),
('drs', 'doctors'),
('rev', 'reverend'),
('lt', 'lieutenant'),
('hon', 'honorable'),
('sgt', 'sergeant'),
('capt', 'captain'),
('esq', 'esquire'),
('ltd', 'limited'),
('col', 'colonel'),
('ft', 'feet'),
('abbrev', 'abbreviation'),
('ave', 'avenue'),
('abstr', 'abstract'),
('addr', 'address'),
('jan', 'january'),
('feb', 'february'),
('mar', 'march'),
('apr', 'april'),
('jul', 'july'),
('aug', 'august'),
('sep', 'september'),
('sept', 'september'),
('oct', 'october'),
('nov', 'november'),
('dec', 'december'),
('mon', 'monday'),
('tue', 'tuesday'),
('wed', 'wednesday'),
('thur', 'thursday'),
('fri', 'friday'),
('sec', 'second'),
('min', 'minute'),
('mo', 'month'),
('yr', 'year'),
('cal', 'calorie'),
('dept', 'department'),
('gal', 'gallon'),
('kg', 'kilogram'),
('km', 'kilometer'),
('mt', 'mount'),
('oz', 'ounce'),
('vol', 'volume'),
('vs', 'versus'),
('yd', 'yard'),
('e\\.g', 'eg'),
('i\\.e', 'ie'),
('etc', 'etc'),
]
]
def expand_abbreviations(text: str):
|
logger = logging.getLogger(__name__)
# Regular expressions matching whitespace. When using with re.split(), the second one will keep whitespaces in the
# output because all captured groups are kept.
_whitespace_excl_re = re.compile(r'\s+')
_whitespace_incl_re = re.compile(r'(\s+)')
# List of (regular expression, replacement) pairs for abbreviations:
_abbreviations = [
(re.compile('\\b%s\\.' % abbrev, re.IGNORECASE), expanded)
for abbrev, expanded in [
('mrs', 'misess'),
('mr', 'mister'),
('dr', 'doctor'),
('st', 'saint'),
('co', 'company'),
('jr', 'junior'),
('maj', 'major'),
('gen', 'general'),
('drs', 'doctors'),
('rev', 'reverend'),
('lt', 'lieutenant'),
('hon', 'honorable'),
('sgt', 'sergeant'),
('capt', 'captain'),
('esq', 'esquire'),
('ltd', 'limited'),
('col', 'colonel'),
('ft', 'feet'),
('abbrev', 'abbreviation'),
('ave', 'avenue'),
('abstr', 'abstract'),
('addr', 'address'),
('jan', 'january'),
('feb', 'february'),
('mar', 'march'),
('apr', 'april'),
('jul', 'july'),
('aug', 'august'),
('sep', 'september'),
('sept', 'september'),
('oct', 'october'),
('nov', 'november'),
('dec', 'december'),
('mon', 'monday'),
('tue', 'tuesday'),
('wed', 'wednesday'),
('thur', 'thursday'),
('fri', 'friday'),
('sec', 'second'),
('min', 'minute'),
('mo', 'month'),
('yr', 'year'),
('cal', 'calorie'),
('dept', 'department'),
('gal', 'gallon'),
('kg', 'kilogram'),
('km', 'kilometer'),
('mt', 'mount'),
('oz', 'ounce'),
('vol', 'volume'),
('vs', 'versus'),
('yd', 'yard'),
('e\\.g', 'eg'),
('i\\.e', 'ie'),
('etc', 'etc'),
]
]
def expand_abbreviations(text: str): | orig2new = SliceMap.identity(len(text)) | 1 | 2023-11-11 20:51:54+00:00 | 8k |
mohenghui/detectAuto_v8 | ultralytics/nn/modules/head.py | [
{
"identifier": "TORCH_1_10",
"path": "ultralytics/utils/tal.py",
"snippet": "TORCH_1_10 = check_version(torch.__version__, '1.10.0')"
},
{
"identifier": "dist2bbox",
"path": "ultralytics/utils/tal.py",
"snippet": "def dist2bbox(distance, anchor_points, xywh=True, dim=-1):\n \"\"\"Tra... | import math
import torch
import torch.nn as nn
from torch.nn.init import constant_, xavier_uniform_
from ultralytics.utils.tal import TORCH_1_10, dist2bbox, make_anchors
from .block import DFL, Proto
from .conv import Conv
from .transformer import MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer
from .utils import bias_init_with_prob, linear_init_
from ultralytics.models.utils.ops import get_cdn_group | 4,079 | # Ultralytics YOLO 🚀, AGPL-3.0 license
"""Model head modules."""
__all__ = 'Detect', 'Segment', 'Pose', 'Classify', 'RTDETRDecoder'
class Detect(nn.Module):
"""YOLOv8 Detect head for detection models."""
dynamic = False # force grid reconstruction
export = False # export mode
shape = None
anchors = torch.empty(0) # init
strides = torch.empty(0) # init
def __init__(self, nc=80, ch=()):
"""Initializes the YOLOv8 detection layer with specified number of classes and channels."""
super().__init__()
self.nc = nc # number of classes
self.nl = len(ch) # number of detection layers
self.reg_max = 16 # DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x)
self.no = nc + self.reg_max * 4 # number of outputs per anchor
self.stride = torch.zeros(self.nl) # strides computed during build
c2, c3 = max((16, ch[0] // 4, self.reg_max * 4)), max(ch[0], min(self.nc, 100)) # channels
self.cv2 = nn.ModuleList(
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch)
self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)
self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()
def forward(self, x):
"""Concatenates and returns predicted bounding boxes and class probabilities."""
shape = x[0].shape # BCHW
for i in range(self.nl):
x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
if self.training:
return x
elif self.dynamic or self.shape != shape:
self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))
self.shape = shape
x_cat = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2)
if self.export and self.format in ('saved_model', 'pb', 'tflite', 'edgetpu', 'tfjs'): # avoid TF FlexSplitV ops
box = x_cat[:, :self.reg_max * 4]
cls = x_cat[:, self.reg_max * 4:]
else:
box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
if self.export and self.format in ('tflite', 'edgetpu'):
# Normalize xywh with image size to mitigate quantization error of TFLite integer models as done in YOLOv5:
# https://github.com/ultralytics/yolov5/blob/0c8de3fca4a702f8ff5c435e67f378d1fce70243/models/tf.py#L307-L309
# See this PR for details: https://github.com/ultralytics/ultralytics/pull/1695
img_h = shape[2] * self.stride[0]
img_w = shape[3] * self.stride[0]
img_size = torch.tensor([img_w, img_h, img_w, img_h], device=dbox.device).reshape(1, 4, 1)
dbox /= img_size
y = torch.cat((dbox, cls.sigmoid()), 1)
return y if self.export else (y, x)
def bias_init(self):
"""Initialize Detect() biases, WARNING: requires stride availability."""
m = self # self.model[-1] # Detect() module
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
a[-1].bias.data[:] = 1.0 # box
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
class Segment(Detect):
"""YOLOv8 Segment head for segmentation models."""
def __init__(self, nc=80, nm=32, npr=256, ch=()):
"""Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers."""
super().__init__(nc, ch)
self.nm = nm # number of masks
self.npr = npr # number of protos
| # Ultralytics YOLO 🚀, AGPL-3.0 license
"""Model head modules."""
__all__ = 'Detect', 'Segment', 'Pose', 'Classify', 'RTDETRDecoder'
class Detect(nn.Module):
"""YOLOv8 Detect head for detection models."""
dynamic = False # force grid reconstruction
export = False # export mode
shape = None
anchors = torch.empty(0) # init
strides = torch.empty(0) # init
def __init__(self, nc=80, ch=()):
"""Initializes the YOLOv8 detection layer with specified number of classes and channels."""
super().__init__()
self.nc = nc # number of classes
self.nl = len(ch) # number of detection layers
self.reg_max = 16 # DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x)
self.no = nc + self.reg_max * 4 # number of outputs per anchor
self.stride = torch.zeros(self.nl) # strides computed during build
c2, c3 = max((16, ch[0] // 4, self.reg_max * 4)), max(ch[0], min(self.nc, 100)) # channels
self.cv2 = nn.ModuleList(
nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch)
self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)
self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()
def forward(self, x):
"""Concatenates and returns predicted bounding boxes and class probabilities."""
shape = x[0].shape # BCHW
for i in range(self.nl):
x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
if self.training:
return x
elif self.dynamic or self.shape != shape:
self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))
self.shape = shape
x_cat = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2)
if self.export and self.format in ('saved_model', 'pb', 'tflite', 'edgetpu', 'tfjs'): # avoid TF FlexSplitV ops
box = x_cat[:, :self.reg_max * 4]
cls = x_cat[:, self.reg_max * 4:]
else:
box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)
dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides
if self.export and self.format in ('tflite', 'edgetpu'):
# Normalize xywh with image size to mitigate quantization error of TFLite integer models as done in YOLOv5:
# https://github.com/ultralytics/yolov5/blob/0c8de3fca4a702f8ff5c435e67f378d1fce70243/models/tf.py#L307-L309
# See this PR for details: https://github.com/ultralytics/ultralytics/pull/1695
img_h = shape[2] * self.stride[0]
img_w = shape[3] * self.stride[0]
img_size = torch.tensor([img_w, img_h, img_w, img_h], device=dbox.device).reshape(1, 4, 1)
dbox /= img_size
y = torch.cat((dbox, cls.sigmoid()), 1)
return y if self.export else (y, x)
def bias_init(self):
"""Initialize Detect() biases, WARNING: requires stride availability."""
m = self # self.model[-1] # Detect() module
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1
# ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # nominal class frequency
for a, b, s in zip(m.cv2, m.cv3, m.stride): # from
a[-1].bias.data[:] = 1.0 # box
b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2) # cls (.01 objects, 80 classes, 640 img)
class Segment(Detect):
"""YOLOv8 Segment head for segmentation models."""
def __init__(self, nc=80, nm=32, npr=256, ch=()):
"""Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers."""
super().__init__(nc, ch)
self.nm = nm # number of masks
self.npr = npr # number of protos | self.proto = Proto(ch[0], self.npr, self.nm) # protos | 4 | 2023-11-16 12:49:59+00:00 | 8k |
i-super/Saleor | saleor/plugins/openid_connect/tests/test_utils.py | [
{
"identifier": "Group",
"path": "saleor/account/models.py",
"snippet": "class Group(models.Model):\n \"\"\"The system provides a way to group users.\n\n Groups are a generic way of categorizing users to apply permissions, or\n some other label, to those users. A user can belong to any number o... | import json
import time
import warnings
import pytest
import pytz
import requests
from datetime import datetime, timedelta
from unittest import mock
from unittest.mock import MagicMock, Mock, call, patch
from authlib.jose import JWTClaims
from django.core.exceptions import ValidationError
from django.utils import timezone
from freezegun import freeze_time
from requests import Response
from requests_hardened import HTTPSession
from ....account.models import Group, User
from ....core.jwt import (
JWT_REFRESH_TYPE,
PERMISSIONS_FIELD,
jwt_decode,
jwt_encode,
jwt_user_payload,
)
from ....permission.models import Permission
from ..exceptions import AuthenticationError
from ..utils import (
JWKS_CACHE_TIME,
JWKS_KEY,
OIDC_DEFAULT_CACHE_TIME,
_update_user_details,
assign_staff_to_default_group_and_update_permissions,
create_jwt_refresh_token,
create_jwt_token,
create_tokens_from_oauth_payload,
fetch_jwks,
get_domain_from_email,
get_or_create_user_from_payload,
get_saleor_permission_names,
get_saleor_permissions_qs_from_scope,
get_user_from_oauth_access_token_in_jwt_format,
get_user_from_token,
get_user_info,
validate_refresh_token,
) | 7,196 |
OIDC_CACHE_TIMEOUT = min(JWKS_CACHE_TIME, OIDC_DEFAULT_CACHE_TIME)
@pytest.mark.parametrize(
"error",
[
json.JSONDecodeError(msg="", doc="", pos=0),
requests.exceptions.RequestException(),
],
)
def test_fetch_jwks_raises_error(monkeypatch, error):
mocked_get = Mock()
mocked_get.side_effect = error
jwks_url = "http://localhost:3000/"
monkeypatch.setattr(HTTPSession, "request", mocked_get)
with pytest.raises(AuthenticationError):
fetch_jwks(jwks_url)
@pytest.mark.vcr
@mock.patch("saleor.plugins.openid_connect.utils.cache.set")
def test_fetch_jwks(mocked_cache_set):
jwks_url = "https://saleor.io/.well-known/jwks.json"
keys = fetch_jwks(jwks_url)
assert len(keys) == 2
mocked_cache_set.assert_called_once_with(JWKS_KEY, keys, JWKS_CACHE_TIME)
def test_get_or_create_user_from_token_missing_email(id_payload):
del id_payload["email"]
with pytest.raises(AuthenticationError):
get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
def test_get_or_create_user_from_token_user_not_active(id_payload, admin_user):
admin_user.is_active = False
admin_user.save()
with pytest.raises(AuthenticationError):
get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
def test_get_user_from_token_missing_email(id_payload):
del id_payload["email"]
with pytest.raises(AuthenticationError):
get_user_from_token(id_payload)
def test_get_user_from_token_missing_user(id_payload):
User.objects.all().delete()
with pytest.raises(AuthenticationError):
get_user_from_token(id_payload)
def test_get_user_from_token_user_not_active(id_payload, admin_user):
admin_user.is_active = False
admin_user.save()
with pytest.raises(AuthenticationError):
get_user_from_token(id_payload)
@freeze_time("2019-03-18 12:00:00")
def test_create_tokens_from_oauth_payload(monkeypatch, id_token, id_payload):
mocked_jwt_validator = MagicMock()
mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
monkeypatch.setattr(
"saleor.plugins.openid_connect.utils.get_decoded_token",
Mock(return_value=mocked_jwt_validator),
)
permissions_from_scope = [
"MANAGE_ORDERS",
]
auth_payload = {
"access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
"refresh_token": "refresh",
"id_token": id_token,
"scope": (
"openid profile email offline_access saleor:manage_orders saleor:staff"
),
"expires_in": 86400,
"token_type": "Bearer",
"expires_at": 1600851112,
}
user = get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
permissions = get_saleor_permissions_qs_from_scope(auth_payload.get("scope"))
perms = get_saleor_permission_names(permissions)
tokens = create_tokens_from_oauth_payload(
auth_payload, user, id_payload, perms, "PluginID"
)
created_user = User.objects.get()
|
OIDC_CACHE_TIMEOUT = min(JWKS_CACHE_TIME, OIDC_DEFAULT_CACHE_TIME)
@pytest.mark.parametrize(
"error",
[
json.JSONDecodeError(msg="", doc="", pos=0),
requests.exceptions.RequestException(),
],
)
def test_fetch_jwks_raises_error(monkeypatch, error):
mocked_get = Mock()
mocked_get.side_effect = error
jwks_url = "http://localhost:3000/"
monkeypatch.setattr(HTTPSession, "request", mocked_get)
with pytest.raises(AuthenticationError):
fetch_jwks(jwks_url)
@pytest.mark.vcr
@mock.patch("saleor.plugins.openid_connect.utils.cache.set")
def test_fetch_jwks(mocked_cache_set):
jwks_url = "https://saleor.io/.well-known/jwks.json"
keys = fetch_jwks(jwks_url)
assert len(keys) == 2
mocked_cache_set.assert_called_once_with(JWKS_KEY, keys, JWKS_CACHE_TIME)
def test_get_or_create_user_from_token_missing_email(id_payload):
del id_payload["email"]
with pytest.raises(AuthenticationError):
get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
def test_get_or_create_user_from_token_user_not_active(id_payload, admin_user):
admin_user.is_active = False
admin_user.save()
with pytest.raises(AuthenticationError):
get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
def test_get_user_from_token_missing_email(id_payload):
del id_payload["email"]
with pytest.raises(AuthenticationError):
get_user_from_token(id_payload)
def test_get_user_from_token_missing_user(id_payload):
User.objects.all().delete()
with pytest.raises(AuthenticationError):
get_user_from_token(id_payload)
def test_get_user_from_token_user_not_active(id_payload, admin_user):
admin_user.is_active = False
admin_user.save()
with pytest.raises(AuthenticationError):
get_user_from_token(id_payload)
@freeze_time("2019-03-18 12:00:00")
def test_create_tokens_from_oauth_payload(monkeypatch, id_token, id_payload):
mocked_jwt_validator = MagicMock()
mocked_jwt_validator.__getitem__.side_effect = id_payload.__getitem__
monkeypatch.setattr(
"saleor.plugins.openid_connect.utils.get_decoded_token",
Mock(return_value=mocked_jwt_validator),
)
permissions_from_scope = [
"MANAGE_ORDERS",
]
auth_payload = {
"access_token": "FeHkE_QbuU3cYy1a1eQUrCE5jRcUnBK3",
"refresh_token": "refresh",
"id_token": id_token,
"scope": (
"openid profile email offline_access saleor:manage_orders saleor:staff"
),
"expires_in": 86400,
"token_type": "Bearer",
"expires_at": 1600851112,
}
user = get_or_create_user_from_payload(id_payload, "https://saleor.io/oauth")
permissions = get_saleor_permissions_qs_from_scope(auth_payload.get("scope"))
perms = get_saleor_permission_names(permissions)
tokens = create_tokens_from_oauth_payload(
auth_payload, user, id_payload, perms, "PluginID"
)
created_user = User.objects.get()
| token = create_jwt_token( | 15 | 2023-11-13 05:00:35+00:00 | 8k |
Aues6uen11Z/Zafkiel | zafkiel/ocr/ocr.py | [
{
"identifier": "logger",
"path": "zafkiel/logger.py",
"snippet": ""
},
{
"identifier": "Config",
"path": "zafkiel/config.py",
"snippet": "class Config:\n ST = Settings\n ST.CVSTRATEGY = [\"mstpl\", \"sift\"]\n ST.THRESHOLD = 0.8\n\n GAME_PATH = None\n SERVER_LANG = 'cn'\n... | import re
import time
from datetime import timedelta
from difflib import SequenceMatcher
from typing import Optional
from pponnxcr.predict_system import BoxedResult
from zafkiel.logger import logger
from zafkiel.config import Config
from zafkiel.decorator import cached_property
from zafkiel.device.template import ImageTemplate
from zafkiel.exception import ScriptError
from zafkiel.ocr.keyword import Keyword
from zafkiel.ocr.models import TextSystem, OCR_MODEL
from zafkiel.ocr.utils import merge_buttons, corner2area, area_pad
from zafkiel.utils import crop | 3,845 |
OCR_EQUAL = 0
OCR_CONTAINS = 1
OCR_SIMILAR = 2
class OcrResultButton:
def __init__(self, boxed_result: BoxedResult, matched_keyword: Optional[Keyword]):
"""
Args:
boxed_result: BoxedResult from ppocr-onnx
matched_keyword: Keyword object or None
"""
self.area = boxed_result.box
self.search = area_pad(self.area, pad=-20)
# self.button = boxed_result.box
if matched_keyword is not None:
self.matched_keyword = matched_keyword
self.name = str(matched_keyword)
else:
self.matched_keyword = None
self.name = boxed_result.ocr_text
self.text = boxed_result.ocr_text
self.score = boxed_result.score
@property
def is_keyword_matched(self) -> bool:
return self.matched_keyword is not None
def __str__(self):
return self.name
__repr__ = __str__
def __eq__(self, other):
return str(self) == str(other)
def __hash__(self):
return hash(self.name)
def __bool__(self):
return True
class Ocr:
# Merge results with box distance <= thres
merge_thres_x = 0
merge_thres_y = 0
def __init__(self, button: ImageTemplate, lang=None, name=None):
"""
Args:
button:
lang: If None, use in-game language
name: If None, use button.name
"""
if lang is None:
lang = Config.SERVER_LANG
if name is None:
name = button.name
self.button: ImageTemplate = button
self.lang: str = lang
self.name: str = name
|
OCR_EQUAL = 0
OCR_CONTAINS = 1
OCR_SIMILAR = 2
class OcrResultButton:
def __init__(self, boxed_result: BoxedResult, matched_keyword: Optional[Keyword]):
"""
Args:
boxed_result: BoxedResult from ppocr-onnx
matched_keyword: Keyword object or None
"""
self.area = boxed_result.box
self.search = area_pad(self.area, pad=-20)
# self.button = boxed_result.box
if matched_keyword is not None:
self.matched_keyword = matched_keyword
self.name = str(matched_keyword)
else:
self.matched_keyword = None
self.name = boxed_result.ocr_text
self.text = boxed_result.ocr_text
self.score = boxed_result.score
@property
def is_keyword_matched(self) -> bool:
return self.matched_keyword is not None
def __str__(self):
return self.name
__repr__ = __str__
def __eq__(self, other):
return str(self) == str(other)
def __hash__(self):
return hash(self.name)
def __bool__(self):
return True
class Ocr:
# Merge results with box distance <= thres
merge_thres_x = 0
merge_thres_y = 0
def __init__(self, button: ImageTemplate, lang=None, name=None):
"""
Args:
button:
lang: If None, use in-game language
name: If None, use button.name
"""
if lang is None:
lang = Config.SERVER_LANG
if name is None:
name = button.name
self.button: ImageTemplate = button
self.lang: str = lang
self.name: str = name
| @cached_property | 2 | 2023-11-12 09:33:35+00:00 | 8k |
medkit-lib/medkit | medkit/core/text/document.py | [
{
"identifier": "dict_conv",
"path": "medkit/core/dict_conv.py",
"snippet": "_CLASS_NAME_KEY: str = \"_class_name\"\ndef get_class_name(class_: Type) -> str:\ndef add_class_name_to_data_dict(instance: object, data_dict: Dict[str, Any]):\ndef get_class_name_from_data_dict(data_dict: Dict[str, Any]):\n ... | import dataclasses
import os
from pathlib import Path
from typing import Any, ClassVar, Dict, List, Optional, Sequence
from typing_extensions import Self
from medkit.core import Attribute, AttributeContainer, dict_conv
from medkit.core.id import generate_deterministic_id, generate_id
from medkit.core.text import span_utils
from medkit.core.text.annotation import Segment, TextAnnotation
from medkit.core.text.annotation_container import TextAnnotationContainer
from medkit.core.text.span import Span | 5,534 | from __future__ import annotations
__all__ = ["TextDocument"]
@dataclasses.dataclass(init=False)
class TextDocument(dict_conv.SubclassMapping):
"""
Document holding text annotations
Annotations must be subclasses of `TextAnnotation`.
Attributes
----------
uid:
Unique identifier of the document.
text:
Full document text.
anns:
Annotations of the document. Stored in an
:class:`~.text.TextAnnotationContainer` but can be passed as a list at init.
attrs:
Attributes of the document. Stored in an
:class:`~.core.AttributeContainer` but can be passed as a list at init
metadata:
Document metadata.
raw_segment:
Auto-generated segment containing the full unprocessed document text. To
get the raw text as an annotation to pass to processing operations:
>>> doc = TextDocument(text="hello")
>>> raw_text = doc.anns.get(label=TextDocument.RAW_LABEL)[0]
"""
RAW_LABEL: ClassVar[str] = "RAW_TEXT"
uid: str
anns: TextAnnotationContainer
attrs: AttributeContainer
metadata: Dict[str, Any]
raw_segment: Segment
def __init__(
self,
text: str,
| from __future__ import annotations
__all__ = ["TextDocument"]
@dataclasses.dataclass(init=False)
class TextDocument(dict_conv.SubclassMapping):
"""
Document holding text annotations
Annotations must be subclasses of `TextAnnotation`.
Attributes
----------
uid:
Unique identifier of the document.
text:
Full document text.
anns:
Annotations of the document. Stored in an
:class:`~.text.TextAnnotationContainer` but can be passed as a list at init.
attrs:
Attributes of the document. Stored in an
:class:`~.core.AttributeContainer` but can be passed as a list at init
metadata:
Document metadata.
raw_segment:
Auto-generated segment containing the full unprocessed document text. To
get the raw text as an annotation to pass to processing operations:
>>> doc = TextDocument(text="hello")
>>> raw_text = doc.anns.get(label=TextDocument.RAW_LABEL)[0]
"""
RAW_LABEL: ClassVar[str] = "RAW_TEXT"
uid: str
anns: TextAnnotationContainer
attrs: AttributeContainer
metadata: Dict[str, Any]
raw_segment: Segment
def __init__(
self,
text: str, | anns: Optional[Sequence[TextAnnotation]] = None, | 7 | 2023-11-13 16:28:56+00:00 | 8k |
eidolon-ai/eidOS | sdk/eidos_sdk/system/agent_machine.py | [
{
"identifier": "AgentController",
"path": "sdk/eidos_sdk/system/agent_controller.py",
"snippet": "class AgentController:\n name: str\n agent: object\n programs: typing.Dict[str, EidosHandler]\n actions: typing.Dict[str, EidosHandler]\n\n def __init__(self, name, agent):\n self.nam... | from contextlib import contextmanager
from fastapi import FastAPI
from pydantic import BaseModel, Field
from typing import List, Optional
from eidos_sdk.memory.agent_memory import AgentMemory
from .agent_controller import AgentController
from .reference_model import AnnotatedReference, Specable
from .resources.agent_resource import AgentResource
from .resources.resources_base import Resource
from ..agent_os import AgentOS
from ..memory.file_memory import FileMemory
from ..memory.semantic_memory import SymbolicMemory
from ..memory.similarity_memory import SimilarityMemory
from ..security.security_manager import SecurityManager | 5,803 |
class MachineSpec(BaseModel):
symbolic_memory: AnnotatedReference[SymbolicMemory] = Field(description="The Symbolic Memory implementation.")
file_memory: AnnotatedReference[FileMemory] = Field(desciption="The File Memory implementation.")
similarity_memory: AnnotatedReference[SimilarityMemory] = Field(description="The Vector Memory implementation.")
security_manager: AnnotatedReference[SecurityManager] = Field(description="The Security Manager implementation.")
def get_agent_memory(self):
file_memory = self.file_memory.instantiate()
symbolic_memory = self.symbolic_memory.instantiate()
vector_memory = self.similarity_memory.instantiate()
return AgentMemory(
file_memory=file_memory,
symbolic_memory=symbolic_memory,
similarity_memory=vector_memory,
)
class AgentMachine(Specable[MachineSpec]):
memory: AgentMemory
security_manager: SecurityManager
agent_controllers: List[AgentController]
app: Optional[FastAPI]
def __init__(self, spec: MachineSpec):
super().__init__(spec)
agents = {}
|
class MachineSpec(BaseModel):
symbolic_memory: AnnotatedReference[SymbolicMemory] = Field(description="The Symbolic Memory implementation.")
file_memory: AnnotatedReference[FileMemory] = Field(desciption="The File Memory implementation.")
similarity_memory: AnnotatedReference[SimilarityMemory] = Field(description="The Vector Memory implementation.")
security_manager: AnnotatedReference[SecurityManager] = Field(description="The Security Manager implementation.")
def get_agent_memory(self):
file_memory = self.file_memory.instantiate()
symbolic_memory = self.symbolic_memory.instantiate()
vector_memory = self.similarity_memory.instantiate()
return AgentMemory(
file_memory=file_memory,
symbolic_memory=symbolic_memory,
similarity_memory=vector_memory,
)
class AgentMachine(Specable[MachineSpec]):
memory: AgentMemory
security_manager: SecurityManager
agent_controllers: List[AgentController]
app: Optional[FastAPI]
def __init__(self, spec: MachineSpec):
super().__init__(spec)
agents = {} | for name, r in AgentOS.get_resources(AgentResource).items(): | 5 | 2023-11-10 20:42:00+00:00 | 8k |
interpretml/LLM-Tabular-Memorization-Checker | tabmemcheck/functions.py | [
{
"identifier": "LLM_Interface",
"path": "tabmemcheck/llm.py",
"snippet": "class LLM_Interface:\n \"\"\"The interface to the language model.\"\"\"\n\n # if true, the tests use the chat_completion function, otherwise the completion function\n chat_mode = False\n\n def completion(self, prompt,... | import os
import numpy as np
import pandas as pd
import tabmemcheck as tabmem
import tabmemcheck.analysis as analysis
import tabmemcheck.utils as utils
from typing import Any, Union
from difflib import SequenceMatcher
from tabmemcheck.llm import (
LLM_Interface,
ChatWrappedLLM,
send_chat_completion,
send_completion,
bcolors,
)
from tabmemcheck.row_independence import statistical_feature_prediction_test
from tabmemcheck.chat_completion import (
prefix_suffix_chat_completion,
row_chat_completion,
row_completion,
feature_values_chat_completion,
) | 5,933 |
DEFAULT_FEW_SHOT_CSV_FILES = [
"iris.csv",
"adult-train.csv",
"titanic-train.csv",
"uci-wine.csv",
"california-housing.csv",
]
def __difflib_similar(csv_file_1, csv_file_2):
sm = SequenceMatcher(
None, utils.load_csv_string(csv_file_1), utils.load_csv_string(csv_file_2)
)
if sm.quick_ratio() > 0.9:
return sm.ratio() > 0.9
return False
def __validate_few_shot_files(csv_file, few_shot_csv_files):
"""check if the csv_file is contained in the few_shot_csv_files."""
dataset_name = utils.get_dataset_name(csv_file)
few_shot_names = [utils.get_dataset_name(x) for x in few_shot_csv_files]
if dataset_name in few_shot_names:
# replace the dataset_name with open-ml diabetes
few_shot_csv_files = [
x for x in few_shot_csv_files if utils.get_dataset_name(x) != dataset_name
]
few_shot_csv_files.append("openml-diabetes.csv")
# now test with difflib if the dataset contents are very similar
for fs_file in few_shot_csv_files:
if __difflib_similar(csv_file, fs_file):
print(
|
DEFAULT_FEW_SHOT_CSV_FILES = [
"iris.csv",
"adult-train.csv",
"titanic-train.csv",
"uci-wine.csv",
"california-housing.csv",
]
def __difflib_similar(csv_file_1, csv_file_2):
sm = SequenceMatcher(
None, utils.load_csv_string(csv_file_1), utils.load_csv_string(csv_file_2)
)
if sm.quick_ratio() > 0.9:
return sm.ratio() > 0.9
return False
def __validate_few_shot_files(csv_file, few_shot_csv_files):
"""check if the csv_file is contained in the few_shot_csv_files."""
dataset_name = utils.get_dataset_name(csv_file)
few_shot_names = [utils.get_dataset_name(x) for x in few_shot_csv_files]
if dataset_name in few_shot_names:
# replace the dataset_name with open-ml diabetes
few_shot_csv_files = [
x for x in few_shot_csv_files if utils.get_dataset_name(x) != dataset_name
]
few_shot_csv_files.append("openml-diabetes.csv")
# now test with difflib if the dataset contents are very similar
for fs_file in few_shot_csv_files:
if __difflib_similar(csv_file, fs_file):
print( | bcolors.BOLD | 4 | 2023-11-14 18:34:51+00:00 | 8k |
WindowsSov8forUs/bestdori_api | bestdori/events.py | [
{
"identifier": "get_list",
"path": "bestdori/post.py",
"snippet": "@overload\ndef get_list(\n proxy: Optional[str]=None,\n *,\n search: str='',\n category_name: Literal['SELF_POST']='SELF_POST',\n category_id: Literal['chart']='chart',\n tags: list[Tag]=[],\n order: Literal['TIME_D... | from typing import Optional, Literal, Any
from .post import get_list
from .utils.utils import API, ASSETS
from .utils.network import Api, Assets
from .eventarchives import EventArchive
from .exceptions import (
ServerNotAvailableError,
EventHasNoStampError,
AssetsNotExistError,
EventNotExistError
) | 5,543 | '''`bestdori.events`
BanG Dream! 活动相关操作'''
# 获取总活动信息
def get_all(index: Literal[0, 5, 6]=5, proxy: Optional[str]=None) -> dict[str, dict[str, Any]]:
'''获取总活动信息
参数:
index (Literal[0, 5, 6], optional): 指定获取哪种 `all.json`
`0`: 仅获取所有已有活动 ID `all.0.json`
`5`: 获取所有已有活动的简洁信息 `all.5.json`
`6`: 获取所有已有活动的简洁信息 `all.6.json`
proxy (Optional[str], optional): 代理服务器
返回:
dict[str, dict[str, Any]]: 获取到的总活动信息
'''
return Api(API['events']['all'].format(index), proxy=proxy).request('get').json()
# 活动类
class Event:
'''活动类
参数:
id_ (int): 活动 ID
proxy (Optional[str], optional): 代理服务器
'''
# 初始化
def __init__(self, id_: int, proxy: Optional[str]=None) -> None:
'''活动类
参数:
id_ (int): 活动 ID
proxy (Optional[str], optional): 代理服务器
'''
self.id: int = id_
'''活动 ID'''
| '''`bestdori.events`
BanG Dream! 活动相关操作'''
# 获取总活动信息
def get_all(index: Literal[0, 5, 6]=5, proxy: Optional[str]=None) -> dict[str, dict[str, Any]]:
'''获取总活动信息
参数:
index (Literal[0, 5, 6], optional): 指定获取哪种 `all.json`
`0`: 仅获取所有已有活动 ID `all.0.json`
`5`: 获取所有已有活动的简洁信息 `all.5.json`
`6`: 获取所有已有活动的简洁信息 `all.6.json`
proxy (Optional[str], optional): 代理服务器
返回:
dict[str, dict[str, Any]]: 获取到的总活动信息
'''
return Api(API['events']['all'].format(index), proxy=proxy).request('get').json()
# 活动类
class Event:
'''活动类
参数:
id_ (int): 活动 ID
proxy (Optional[str], optional): 代理服务器
'''
# 初始化
def __init__(self, id_: int, proxy: Optional[str]=None) -> None:
'''活动类
参数:
id_ (int): 活动 ID
proxy (Optional[str], optional): 代理服务器
'''
self.id: int = id_
'''活动 ID''' | self.archive: EventArchive = EventArchive(self.id, self.proxy) | 5 | 2023-11-16 13:09:20+00:00 | 8k |
kampta/asic | commons/logger.py | [
{
"identifier": "images2grid",
"path": "commons/utils.py",
"snippet": "def images2grid(images, **grid_kwargs):\n # images should be (N, C, H, W)\n grid = make_grid(images, **grid_kwargs)\n out = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()\n return o... | from torch.utils.tensorboard.writer import SummaryWriter
from PIL import Image
from commons.utils import images2grid, map_minmax, compute_pck, sample_tuples, \
pck_loop
from commons.draw import splat_points, load_fg_points, \
concat_v, get_colors, get_dense_colors, load_text_points
from thirdparty.colormap.colormap_flow import color_wheel_fast_smooth
import torch
import torch.nn.functional as F
import wandb
import numpy as np | 4,335 |
@torch.inference_mode()
def log_visuals(canon, stn, dset, train_idx, writer, vis_sample=2,
vis_denseres=32):
device = 'cuda' if torch.cuda.is_available() else 'cpu'
pseudo_kps = dset.pseudo_kps
parts = dset.parts
vis_sample = min(vis_sample, len(dset))
res = dset.img_size
has_gt_kp = dset.kps is not None
has_fixed_pairs = dset.fixed_pairs is not None # SPair
# Run full test dataloader (assuming small dataset)
all_imgs = dset.imgs
all_masks = dset.masks
all_kps = dset.kps
all_flows, _ = stn(all_imgs)
if has_gt_kp:
|
@torch.inference_mode()
def log_visuals(canon, stn, dset, train_idx, writer, vis_sample=2,
vis_denseres=32):
device = 'cuda' if torch.cuda.is_available() else 'cpu'
pseudo_kps = dset.pseudo_kps
parts = dset.parts
vis_sample = min(vis_sample, len(dset))
res = dset.img_size
has_gt_kp = dset.kps is not None
has_fixed_pairs = dset.fixed_pairs is not None # SPair
# Run full test dataloader (assuming small dataset)
all_imgs = dset.imgs
all_masks = dset.masks
all_kps = dset.kps
all_flows, _ = stn(all_imgs)
if has_gt_kp: | kps_cols = torch.from_numpy(get_colors(all_kps.size(1))).float() | 8 | 2023-11-14 16:43:16+00:00 | 8k |
AnonymGiant/ViLaM | lavis/runners/runner_iter.py | [
{
"identifier": "download_cached_file",
"path": "lavis/common/dist_utils.py",
"snippet": "def download_cached_file(url, check_hash=True, progress=False):\n \"\"\"\n Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again.\n If distributed, only th... | import datetime
import logging
import os
import time
import torch
import torch.distributed as dist
import webdataset as wds
from lavis.common.dist_utils import download_cached_file, is_main_process, main_process
from lavis.common.registry import registry
from lavis.common.utils import is_url
from lavis.datasets.data_utils import concat_datasets, reorg_datasets_by_split
from lavis.runners.runner_base import RunnerBase
from torch.utils.data.dataset import ChainDataset | 7,109 | """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
@registry.register_runner("runner_iter")
class RunnerIter(RunnerBase):
"""
Run training based on the number of iterations. This is common when
the training dataset size is large. Underhood logic is similar to
epoch-based training by considering every #iters_per_inner_epoch as an
inner epoch.
In iter-based runner, after every #iters_per_inner_epoch steps, we
1) do a validation epoch;
2) schedule the learning rate;
3) save the checkpoint.
We refer every #iters_per_inner_epoch steps as an inner epoch.
"""
def __init__(self, cfg, task, model, datasets, job_id):
super().__init__(cfg, task, model, datasets, job_id)
self.start_iters = 0
self.max_iters = int(self.config.run_cfg.get("max_iters", -1))
assert self.max_iters > 0, "max_iters must be greater than 0."
self.iters_per_inner_epoch = int(
self.config.run_cfg.get("iters_per_inner_epoch", -1)
)
assert (
self.iters_per_inner_epoch > 0
), "iters_per_inner_epoch must be greater than 0."
@property
def max_epoch(self):
return int(self.max_iters / self.iters_per_inner_epoch)
@property
def cur_epoch(self):
try:
return self.train_loader.epoch
except AttributeError:
# pipeline data (e.g. LAION) is streaming, have no concept of epoch
return 0
def _progress(self, cur_iters):
return "{}_iters={}".format(self.cur_epoch, cur_iters)
def train(self):
start_time = time.time()
best_agg_metric = 0
best_iters = 0
self.log_config()
# resume from checkpoint if specified
if not self.evaluate_only and self.resume_ckpt_path is not None:
self._load_checkpoint(self.resume_ckpt_path)
for start_iters in range(
self.start_iters, self.max_iters, self.iters_per_inner_epoch
):
end_iters = start_iters + self.iters_per_inner_epoch
# training phase
if not self.evaluate_only:
logging.info(
"Start training, max_iters={}, in total {} inner epochs.".format(
self.max_iters, int(self.max_iters / self.iters_per_inner_epoch)
)
)
train_stats = self.train_iters(self.cur_epoch, start_iters)
self.log_stats(split_name="train", stats=train_stats)
self._save_checkpoint(end_iters, is_best=False)
# evaluation phase
if len(self.valid_splits) > 0:
for split_name in self.valid_splits:
logging.info("Evaluating on {}.".format(split_name))
val_log = self.eval_epoch(
split_name=split_name, cur_epoch=self._progress(end_iters)
)
if val_log is not None:
| """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
@registry.register_runner("runner_iter")
class RunnerIter(RunnerBase):
"""
Run training based on the number of iterations. This is common when
the training dataset size is large. Underhood logic is similar to
epoch-based training by considering every #iters_per_inner_epoch as an
inner epoch.
In iter-based runner, after every #iters_per_inner_epoch steps, we
1) do a validation epoch;
2) schedule the learning rate;
3) save the checkpoint.
We refer every #iters_per_inner_epoch steps as an inner epoch.
"""
def __init__(self, cfg, task, model, datasets, job_id):
super().__init__(cfg, task, model, datasets, job_id)
self.start_iters = 0
self.max_iters = int(self.config.run_cfg.get("max_iters", -1))
assert self.max_iters > 0, "max_iters must be greater than 0."
self.iters_per_inner_epoch = int(
self.config.run_cfg.get("iters_per_inner_epoch", -1)
)
assert (
self.iters_per_inner_epoch > 0
), "iters_per_inner_epoch must be greater than 0."
@property
def max_epoch(self):
return int(self.max_iters / self.iters_per_inner_epoch)
@property
def cur_epoch(self):
try:
return self.train_loader.epoch
except AttributeError:
# pipeline data (e.g. LAION) is streaming, have no concept of epoch
return 0
def _progress(self, cur_iters):
return "{}_iters={}".format(self.cur_epoch, cur_iters)
def train(self):
start_time = time.time()
best_agg_metric = 0
best_iters = 0
self.log_config()
# resume from checkpoint if specified
if not self.evaluate_only and self.resume_ckpt_path is not None:
self._load_checkpoint(self.resume_ckpt_path)
for start_iters in range(
self.start_iters, self.max_iters, self.iters_per_inner_epoch
):
end_iters = start_iters + self.iters_per_inner_epoch
# training phase
if not self.evaluate_only:
logging.info(
"Start training, max_iters={}, in total {} inner epochs.".format(
self.max_iters, int(self.max_iters / self.iters_per_inner_epoch)
)
)
train_stats = self.train_iters(self.cur_epoch, start_iters)
self.log_stats(split_name="train", stats=train_stats)
self._save_checkpoint(end_iters, is_best=False)
# evaluation phase
if len(self.valid_splits) > 0:
for split_name in self.valid_splits:
logging.info("Evaluating on {}.".format(split_name))
val_log = self.eval_epoch(
split_name=split_name, cur_epoch=self._progress(end_iters)
)
if val_log is not None: | if is_main_process(): | 1 | 2023-11-14 08:57:59+00:00 | 8k |
MorrisNein/pecapiku | tests/unit/interface/test_cache_classes.py | [
{
"identifier": "CacheDict",
"path": "pecapiku/cache_dict.py",
"snippet": "class CacheDict(BaseCache, Generic[DecoratedCallable]):\n \"\"\" Decorator/context manager for caching of evaluation results.\n Creates a \"pickle\" file at disk space on a specified path.\n\n If used as a context, provi... | from functools import wraps
from itertools import product
from time import sleep, time
from typing import Any
from pecapiku import CacheDict, SingleValueCache
from tests.conftest import get_cache_dir, set_cache_dir # noqa
import pytest | 3,998 |
class TestObject:
def __init__(self, foo: Any):
self.foo = foo
def sleep(self, time_: float) -> float:
sleep(time_)
return time_
class TestObjectWithCounter:
def __init__(self, foo: Any):
self.foo = foo
self.counter = 0
def sleep(self, time_: float) -> float:
self.counter += 1
sleep(time_)
return time_
def sleep_(time_: float):
sleep(time_)
return time_
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
t1 = time()
res = func(*args, **kwargs)
t2 = time()
t = t2 - t1
return res, t
return wrapper
@pytest.mark.parametrize('sleep_func', [sleep_, TestObject(1).sleep])
@pytest.mark.parametrize('cache_decorator, cache_kwargs',
[
|
class TestObject:
def __init__(self, foo: Any):
self.foo = foo
def sleep(self, time_: float) -> float:
sleep(time_)
return time_
class TestObjectWithCounter:
def __init__(self, foo: Any):
self.foo = foo
self.counter = 0
def sleep(self, time_: float) -> float:
self.counter += 1
sleep(time_)
return time_
def sleep_(time_: float):
sleep(time_)
return time_
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
t1 = time()
res = func(*args, **kwargs)
t2 = time()
t = t2 - t1
return res, t
return wrapper
@pytest.mark.parametrize('sleep_func', [sleep_, TestObject(1).sleep])
@pytest.mark.parametrize('cache_decorator, cache_kwargs',
[ | *product([SingleValueCache(), SingleValueCache.decorate], [dict(file_path='some.pkl')]), | 1 | 2023-11-17 12:10:01+00:00 | 8k |
mmjing/BalancedOSDA | utils2.py | [
{
"identifier": "VonMisesFisher",
"path": "hyperspherical_vae/distributions/von_mises_fisher.py",
"snippet": "class VonMisesFisher(torch.distributions.Distribution):\n\n arg_constraints = {'loc': torch.distributions.constraints.real,\n 'scale': torch.distributions.constraints.po... | import torch.optim as opt
import torch
import gc
import os
import libmr
from basenet import *
from copy import copy, deepcopy
from hyperspherical_vae.distributions import VonMisesFisher
from hyperspherical_vae.distributions import HypersphericalUniform
from utils import angular_dist | 5,037 | data_outlier_probs (list): List of outlier probabilities for an entire dataset, categorized by class.
num_classes (int): Number of classes.
num_outlier_threshs (int): Number of outlier rejection priors (evenly spread over the interval (0,1)).
Returns:
dict: Dictionary containing outlier percentages and corresponding rejection prior values.
"""
dataset_outliers = []
threshs = []
# loop through each rejection prior value and evaluate the percentage of the dataset being considered as
# statistical outliers, i.e. each data point's outlier probability > rejection prior.
for i in range(num_outlier_threshs - 1):
outlier_threshold = (i + 1) * (1.0 / num_outlier_threshs)
threshs.append(outlier_threshold)
dataset_outliers.append(0)
total_dataset = 0
for j in range(num_classes):
total_dataset += len(data_outlier_probs[j])
for k in range(len(data_outlier_probs[j])):
if data_outlier_probs[j][k] > outlier_threshold:
dataset_outliers[i] += 1
dataset_outliers[i] = dataset_outliers[i] / float(total_dataset)
return {"thresholds": threshs, "outlier_percentage": dataset_outliers}
def calc_mean_class_acc(data_outlier_probs,label_pred_class_list_t, num_class):
threshs = [0.98]
num_outlier_threshs = len(threshs)
label_pred_class_list_t = np.array(label_pred_class_list_t,dtype=object)
best_OS_star_acc = 0
best_unk = 0
best_H = 0
for i in range(num_outlier_threshs):
total_dataset = 0
label_pred_class_list_t_copy = deepcopy(label_pred_class_list_t)
for j in range(num_class-1):
total_dataset += len(data_outlier_probs[j])
for k in range(len(data_outlier_probs[j])):
if data_outlier_probs[j][k] > threshs[i]:
label_pred_class_list_t_copy[1][j][k] = num_class-1
all_pred = np.concatenate(np.array(label_pred_class_list_t_copy[1]),axis=0)
all_label = np.concatenate(np.array(label_pred_class_list_t_copy[0]),axis=0)
per_class_num = np.zeros((num_class))
per_class_correct1 = np.zeros((num_class)).astype(np.float32)
for t in range(num_class):
ind = np.where(all_label==t)[0]
if len(ind) == 0:
continue
correct_ind = np.where(all_pred[ind] == t)[0]
per_class_correct1[t] += float(len(correct_ind))
per_class_num[t] += float(len(ind))
per_class_acc1 = per_class_correct1 / per_class_num
OS_acc1 = float(per_class_acc1.mean())
OS_star_acc1 = float(per_class_acc1[:-1].mean())
unk_acc1 = float(per_class_acc1[-1])
H_acc = 0
if OS_star_acc1 > 0 and unk_acc1 > 0:
H_acc = 2*OS_star_acc1*unk_acc1/(OS_star_acc1+unk_acc1)
if H_acc > best_H:
best_H = H_acc
best_OS_star_acc = OS_star_acc1
best_unk = unk_acc1
return best_OS_star_acc, best_unk, best_H
def correct_dist(distances_to_z_means_threshset,centroid_distance):
num_class = centroid_distance.shape[0]
for i in range(num_class-1):
len_class = len(distances_to_z_means_threshset[i])
if len_class>0:
distances_to_z_means_threshset[i] = torch.clamp(distances_to_z_means_threshset[i] - 1.0*centroid_distance[i].expand(len_class),min=0.0)
return distances_to_z_means_threshset
def inverseDecaySheduler(step, initial_lr, gamma=10, power=0.75, max_iter=1000):
return initial_lr * ((1 + gamma * min(1.0, step / float(max_iter))) ** (- power))
class OptimWithSheduler:
def __init__(self, optimizer, scheduler_func):
self.optimizer = optimizer
self.scheduler_func = scheduler_func
self.global_step = 0.0
for g in self.optimizer.param_groups:
g['initial_lr'] = g['lr']
def zero_grad(self):
self.optimizer.zero_grad()
def step(self):
for g in self.optimizer.param_groups:
g['lr'] = self.scheduler_func(step=self.global_step, initial_lr = g['initial_lr'])
self.optimizer.step()
self.global_step += 1
def reparameterize(z_mean, z_var, distribution='vmf'):
if distribution == 'normal':
q_z = torch.distributions.normal.Normal(z_mean, z_var)
elif distribution == 'vmf':
q_z = VonMisesFisher(z_mean, z_var)
else:
raise NotImplemented
return q_z
def reparameterize2(z_mean, z_var, z_dim, distribution='vmf'):
if distribution == 'normal':
q_z = torch.distributions.normal.Normal(z_mean, z_var)
p_z = torch.distributions.normal.Normal(torch.zeros_like(z_mean), torch.ones_like(z_var))
elif distribution == 'vmf':
q_z = VonMisesFisher(z_mean, z_var)
| from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# os.system('file ./libmr.so')
def get_model(net, num_class=13, feat_size=100, d_hid_size=2048):
if net == 'vgg1':
model_g = VGGBase(feat_size=feat_size)
model_c1 = Classifier(num_classes=num_class,feat_size=feat_size)
model_d = AdversarialNetwork(in_feature=feat_size, hidden_size=d_hid_size)
if net == 'vgg2':
model_g = VGGFc(vgg_name='VGG19BN',bottleneck_dim=feat_size)
model_c1 = Classifier(num_classes=num_class,feat_size=feat_size)
model_d = AdversarialNetwork(in_feature=feat_size, hidden_size=d_hid_size)
if net == 'vgg3':
model_g = VGGFc(vgg_name='VGG19',bottleneck_dim=feat_size)
model_c1 = Classifier(num_classes=num_class,feat_size=feat_size)
model_d = AdversarialNetwork(in_feature=feat_size, hidden_size=d_hid_size)
if net == 'resnet1':
model_g = ResBase(option='resnet50', pret=True, feat_size=feat_size)
model_c1 = ResClassifier(num_classes=num_class, feat_size=feat_size)
model_d = AdversarialNetwork(in_feature=feat_size, hidden_size=d_hid_size)
if net == 'resnet2':
model_g = ResNetFc(resnet_name='ResNet50', bottleneck_dim=feat_size)
model_c1 = ResClassifier(num_classes=num_class, feat_size=feat_size)
model_d = AdversarialNetwork(in_feature=feat_size, hidden_size=d_hid_size)
return model_g, model_c1, model_d
def get_optimizer_visda(args, G, C1, C2, D):
update_lower=args.update_lower
if not update_lower:
print('NOT update lower!')
params = list(list(G.linear1.parameters()) + list(G.linear2.parameters()) + list(
G.bn1.parameters()) + list(G.bn2.parameters())) #+ list(G.bn4.parameters()) + list(
#G.bn3.parameters()) + list(G.linear3.parameters()) + list(G.linear4.parameters()))
else:
print('update lower!')
params = G.parameters()
optimizer_g = opt.SGD(params, lr=args.lr_g, momentum=0.9, weight_decay=0.0005,nesterov=True)
optimizer_c1 = opt.SGD(list(C1.parameters()), momentum=0.9, lr=args.lr_c1,weight_decay=0.0005, nesterov=True)
optimizer_c2 = opt.SGD(list(C2.parameters()), momentum=0.9, lr=args.lr_c2,weight_decay=0.0005, nesterov=True)
optimizerD = opt.Adam(D.parameters(), lr=args.lr_d)
return optimizer_g, optimizer_c1, optimizer_c2, optimizerD
def bce_loss(output, target):
output_neg = 1 - output
target_neg = 1 - target
result = torch.mean(target * torch.log(output + 1e-6))
result += torch.mean(target_neg * torch.log(output_neg + 1e-6))
return -torch.mean(result)
def Entropy(input_):
bs = input_.size(0)
epsilon = 1e-5
entropy = -input_ * torch.log(input_ + epsilon)
entropy = torch.sum(entropy, dim=1)
return entropy
def DiscrepancyLoss(input_1, input_2, m = 2.0):
soft_1 = nn.functional.softmax(input_1, dim=1)
soft_2 = nn.functional.softmax(input_2, dim=1)
entropy_1 = - soft_1 * nn.functional.log_softmax(input_1, dim=1)
entropy_2 = - soft_2 * nn.functional.log_softmax(input_2, dim=1)
entropy_1 = torch.sum(entropy_1, dim=1)
entropy_2 = torch.sum(entropy_2, dim=1)
loss = torch.nn.ReLU()(m - torch.mean(entropy_1 - entropy_2))
return loss
def EntropyLoss(input_1):
soft_1 = nn.functional.softmax(input_1, dim=1)
entropy_1 = - soft_1 * nn.functional.log_softmax(input_1, dim=1)
entropy_1 = torch.sum(entropy_1, dim=1)
# loss = torch.nn.ReLU()(m - torch.mean(entropy_1))
loss = -torch.mean(entropy_1)
return loss
def calc_entropy(input_1):
soft_1 = nn.functional.softmax(input_1, dim=1)
entropy_1 = - soft_1 * nn.functional.log_softmax(input_1, dim=1)
entropy_1 = torch.sum(entropy_1, dim=1)
return entropy_1
def save_model(encoder, classifier, centroid_distance, save_path):
save_dic = {
'encoder': encoder.state_dict(),
'classifier': classifier.state_dict(),
'centroid_distance':centroid_distance
}
torch.save(save_dic, save_path)
def load_model(encoder, classifier, load_path):
checkpoint = torch.load(load_path)
encoder.load_state_dict(checkpoint['encoder'])
classifier.load_state_dict(checkpoint['classifier'])
centroid_distance = checkpoint['centroid_distance']
return encoder, classifier,centroid_distance
def adjust_learning_rate(optimizer, lr, batch_id, max_id, epoch, max_epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
beta = 0.75
alpha = 10
p = min(1, (batch_id + max_id * epoch) / float(max_id * max_epoch))
lr = lr / (1 + alpha * p) ** (beta) # min(1, 2 - epoch/float(20))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.01)
m.bias.data.normal_(0.0, 0.01)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.01)
m.bias.data.fill_(0)
def segment_sum(data, segment_ids):
"""
Analogous to tf.segment_sum (https://www.tensorflow.org/api_docs/python/tf/math/segment_sum).
:param data: A pytorch tensor of the data for segmented summation.
:param segment_ids: A 1-D tensor containing the indices for the segmentation.
:return: a tensor of the same type as data containing the results of the segmented summation.
"""
if not all(segment_ids[i] <= segment_ids[i + 1] for i in range(len(segment_ids) - 1)):
raise AssertionError("elements of segment_ids must be sorted")
if len(segment_ids.shape) != 1:
raise AssertionError("segment_ids have be a 1-D tensor")
if data.shape[0] != segment_ids.shape[0]:
raise AssertionError("segment_ids should be the same size as dimension 0 of input.")
num_segments = len(torch.unique(segment_ids))
return unsorted_segment_sum(data, segment_ids, num_segments)
def unsorted_segment_sum(data, segment_ids, num_segments):
"""
Computes the sum along segments of a tensor. Analogous to tf.unsorted_segment_sum.
:param data: A tensor whose segments are to be summed.
:param segment_ids: The segment indices tensor.
:param num_segments: The number of segments.
:return: A tensor of same data type as the data argument.
"""
assert all([i in data.shape for i in segment_ids.shape]), "segment_ids.shape should be a prefix of data.shape"
# segment_ids is a 1-D tensor repeat it to have the same shape as data
if len(segment_ids.shape) == 1:
s = torch.prod(torch.tensor(data.shape[1:])).long().cuda()
segment_ids = segment_ids.repeat_interleave(s).view(segment_ids.shape[0], *data.shape[1:])
assert data.shape == segment_ids.shape, "data.shape and segment_ids.shape should be equal"
shape = [num_segments] + list(data.shape[1:])
centroid = torch.zeros(*shape).cuda().scatter_add(0, segment_ids, data.float())
centroid = centroid.type(data.dtype)
return centroid
def unsorted_segment_sum_cpu(data, segment_ids, num_segments):
"""
Computes the sum along segments of a tensor. Analogous to tf.unsorted_segment_sum.
:param data: A tensor whose segments are to be summed.
:param segment_ids: The segment indices tensor.
:param num_segments: The number of segments.
:return: A tensor of same data type as the data argument.
"""
assert all([i in data.shape for i in segment_ids.shape]), "segment_ids.shape should be a prefix of data.shape"
# segment_ids is a 1-D tensor repeat it to have the same shape as data
if len(segment_ids.shape) == 1:
s = torch.prod(torch.tensor(data.shape[1:])).long()
segment_ids = segment_ids.repeat_interleave(s).view(segment_ids.shape[0], *data.shape[1:])
assert data.shape == segment_ids.shape, "data.shape and segment_ids.shape should be equal"
shape = [num_segments] + list(data.shape[1:])
centroid = torch.zeros(*shape).scatter_add(0, segment_ids, data.float())
centroid = centroid.type(data.dtype)
return centroid
def get_means(tensors_list):
"""
Calculate the mean of a list of tensors for each tensor in the list. In our case the list typically contains
a tensor for each class, such as the per class z values.
Parameters:
tensors_list (list): List of Tensors
Returns:
list: List of Tensors containing mean vectors
"""
means = []
for i in range(len(tensors_list)):
if isinstance(tensors_list[i], torch.Tensor):
means.append(torch.mean(tensors_list[i], dim=0))
else:
means.append([])
return means
def calc_distances_to_means(means, tensors, distance_function='angular'):
"""
Function to calculate distances between tensors, in our case the mean zs per class and z for each input.
Wrapper around torch.nn.functonal distances with specification of which distance function to choose.
Parameters:
means (list): List of length corresponding to number of classes containing torch tensors (typically mean zs).
tensors (list): List of length corresponding to number of classes containing tensors (typically zs).
distance_function (str): Specification of distance function. Choice of cosine|euclidean|mix.
Returns:
list: List of length corresponding to number of classes containing tensors with distance values
"""
def distance_func(a, b, distance_function):
if distance_function == 'euclidean':
d = torch.nn.functional.pairwise_distance(a.view(1, -1), b, p=2)
elif distance_function == 'cosine':
d = (1 - torch.nn.functional.cosine_similarity(a.view(1, -1), b))
elif distance_function == 'angular':
eps = 1e-6
d = angular_dist(b,a.unsqueeze(0)).squeeze()
# a = F.normalize(a.unsqueeze(0))
# b = F.normalize(a.unsqueeze(0))
# d = torch.acos(torch.clamp(torch.matmul(a,b.transpose(0,1)), -1.+eps, 1-eps))
return d
distances = []
# loop through each class in means and calculate the distances with the respective tensor.
for i in range(len(means)):
# check for tensor type, e.g. list could be empty
if isinstance(tensors[i], torch.Tensor) and isinstance(means[i], torch.Tensor):
dist_tensor = distance_func(means[i], tensors[i], distance_function)
if torch.numel(dist_tensor) == 1:
dist_tensor = dist_tensor.unsqueeze(0)
distances.append(dist_tensor)
else:
distances.append([])
return distances
def fit_weibull_models(distribution_values, tailsizes, num_max_fits=5):
"""
Function to fit weibull models on distribution values per class. The distribution values in our case are the
distances of an inputs approximate posterior value to the per class mean latent z, i.e. The Weibull model fits
regions of high density and gives credible intervals.
The tailsize specifies how many outliers are expected in the dataset for which the model has been trained.
We use libmr https://github.com/Vastlab/libMR (installable through e.g. pip) for the Weibull model fitting.
Parameters:
distribution_values (list): Values on which the fit is conducted. In our case latent space distances.
tailsizes (list): List of integers, specifying tailsizes per class. For a balanced dataset typically the same.
num_max_fits (int): Number of attempts to fit the Weibull models before timing out and returning unsuccessfully.
Returns:
list: List of Weibull models with their respective parameters (stored in libmr class instances).
"""
weibull_models = []
# loop through the list containing distance values per class
for i in range(len(distribution_values)):
# for each class set the initial success to False and number of attempts to 0
is_valid = False
count = 0
# If the list contains distance values conduct a fit. If it is empty, e.g. because there is not a single
# prediction for the corresponding class, continue with the next class. Note that the latter isn't expected for
# a model that has been trained for even just a short while.
if isinstance(distribution_values[i], torch.Tensor):
distribution_values[i] = distribution_values[i].cpu().numpy().astype(np.double)
# weibull model per class
weibull_models.append(libmr.MR(verbose=False,alpha=10.0))
# attempt num_max_fits many fits before aborting
while is_valid is False and count < num_max_fits:
# conduct the fit with libmr
weibull_models[i].fit_high(distribution_values[i], tailsizes[i])
is_valid = weibull_models[i].is_valid
count += 1
if not is_valid:
# print("Weibull fit for class " + str(i) + " not successful after " + str(num_max_fits) + " attempts")
weibull_models[i] = []
else:
weibull_models.append([])
return weibull_models, True
def calc_outlier_probs(weibull_models, distances):
"""
Calculates statistical outlier probability using the weibull models' CDF.
Note that we have coded this function to loop over each class because we have previously categorized the distances
into their respective classes already.
Parameters:
weibull_models (list): List of libmr class instances containing the Weibull model parameters and functions.
distances (list): List of per class torch tensors or numpy arrays with latent space distance values.
Returns:
list: List of length corresponding to number of classes with outlier probabilities for each respective input.
"""
outlier_probs = []
# loop through all classes, i.e. all available weibull models as there is one weibull model per class.
for i in range(len(weibull_models)):
# optionally convert the type of the distance vectors
if isinstance(weibull_models[i],list):
outlier_probs.append([])
continue
if isinstance(distances[i], torch.Tensor):
distances[i] = distances[i].cpu().numpy().astype(np.double)
elif isinstance(distances[i], list):
# empty list
outlier_probs.append([])
continue
else:
distances[i] = distances[i].astype(np.double)
# use the Weibull models' CDF to evaluate statistical outlier rejection probabilities.
outlier_probs.append(weibull_models[i].w_score_vector(distances[i]))
return outlier_probs
def calc_openset_classification(data_outlier_probs, num_classes, num_outlier_threshs=50):
"""
Calculates the percentage of dataset outliers given a set of outlier probabilities over a range of rejection priors.
Parameters:
data_outlier_probs (list): List of outlier probabilities for an entire dataset, categorized by class.
num_classes (int): Number of classes.
num_outlier_threshs (int): Number of outlier rejection priors (evenly spread over the interval (0,1)).
Returns:
dict: Dictionary containing outlier percentages and corresponding rejection prior values.
"""
dataset_outliers = []
threshs = []
# loop through each rejection prior value and evaluate the percentage of the dataset being considered as
# statistical outliers, i.e. each data point's outlier probability > rejection prior.
for i in range(num_outlier_threshs - 1):
outlier_threshold = (i + 1) * (1.0 / num_outlier_threshs)
threshs.append(outlier_threshold)
dataset_outliers.append(0)
total_dataset = 0
for j in range(num_classes):
total_dataset += len(data_outlier_probs[j])
for k in range(len(data_outlier_probs[j])):
if data_outlier_probs[j][k] > outlier_threshold:
dataset_outliers[i] += 1
dataset_outliers[i] = dataset_outliers[i] / float(total_dataset)
return {"thresholds": threshs, "outlier_percentage": dataset_outliers}
def calc_mean_class_acc(data_outlier_probs,label_pred_class_list_t, num_class):
threshs = [0.98]
num_outlier_threshs = len(threshs)
label_pred_class_list_t = np.array(label_pred_class_list_t,dtype=object)
best_OS_star_acc = 0
best_unk = 0
best_H = 0
for i in range(num_outlier_threshs):
total_dataset = 0
label_pred_class_list_t_copy = deepcopy(label_pred_class_list_t)
for j in range(num_class-1):
total_dataset += len(data_outlier_probs[j])
for k in range(len(data_outlier_probs[j])):
if data_outlier_probs[j][k] > threshs[i]:
label_pred_class_list_t_copy[1][j][k] = num_class-1
all_pred = np.concatenate(np.array(label_pred_class_list_t_copy[1]),axis=0)
all_label = np.concatenate(np.array(label_pred_class_list_t_copy[0]),axis=0)
per_class_num = np.zeros((num_class))
per_class_correct1 = np.zeros((num_class)).astype(np.float32)
for t in range(num_class):
ind = np.where(all_label==t)[0]
if len(ind) == 0:
continue
correct_ind = np.where(all_pred[ind] == t)[0]
per_class_correct1[t] += float(len(correct_ind))
per_class_num[t] += float(len(ind))
per_class_acc1 = per_class_correct1 / per_class_num
OS_acc1 = float(per_class_acc1.mean())
OS_star_acc1 = float(per_class_acc1[:-1].mean())
unk_acc1 = float(per_class_acc1[-1])
H_acc = 0
if OS_star_acc1 > 0 and unk_acc1 > 0:
H_acc = 2*OS_star_acc1*unk_acc1/(OS_star_acc1+unk_acc1)
if H_acc > best_H:
best_H = H_acc
best_OS_star_acc = OS_star_acc1
best_unk = unk_acc1
return best_OS_star_acc, best_unk, best_H
def correct_dist(distances_to_z_means_threshset,centroid_distance):
num_class = centroid_distance.shape[0]
for i in range(num_class-1):
len_class = len(distances_to_z_means_threshset[i])
if len_class>0:
distances_to_z_means_threshset[i] = torch.clamp(distances_to_z_means_threshset[i] - 1.0*centroid_distance[i].expand(len_class),min=0.0)
return distances_to_z_means_threshset
def inverseDecaySheduler(step, initial_lr, gamma=10, power=0.75, max_iter=1000):
return initial_lr * ((1 + gamma * min(1.0, step / float(max_iter))) ** (- power))
class OptimWithSheduler:
def __init__(self, optimizer, scheduler_func):
self.optimizer = optimizer
self.scheduler_func = scheduler_func
self.global_step = 0.0
for g in self.optimizer.param_groups:
g['initial_lr'] = g['lr']
def zero_grad(self):
self.optimizer.zero_grad()
def step(self):
for g in self.optimizer.param_groups:
g['lr'] = self.scheduler_func(step=self.global_step, initial_lr = g['initial_lr'])
self.optimizer.step()
self.global_step += 1
def reparameterize(z_mean, z_var, distribution='vmf'):
if distribution == 'normal':
q_z = torch.distributions.normal.Normal(z_mean, z_var)
elif distribution == 'vmf':
q_z = VonMisesFisher(z_mean, z_var)
else:
raise NotImplemented
return q_z
def reparameterize2(z_mean, z_var, z_dim, distribution='vmf'):
if distribution == 'normal':
q_z = torch.distributions.normal.Normal(z_mean, z_var)
p_z = torch.distributions.normal.Normal(torch.zeros_like(z_mean), torch.ones_like(z_var))
elif distribution == 'vmf':
q_z = VonMisesFisher(z_mean, z_var) | p_z = HypersphericalUniform(z_dim - 1) | 1 | 2023-11-13 09:00:25+00:00 | 8k |
SitaoLuan/When-Do-GNNs-Help | homophily_tests.py | [
{
"identifier": "random_disassortative_splits",
"path": "utils/homophily_metrics.py",
"snippet": "def remove_self_loops(edge_index, edge_attr=None):\ndef edge_homophily(A, labels, ignore_negative=False):\ndef node_homophily(A, labels):\ndef node_homophily_edge_idx(edge_idx, labels, num_nodes):\ndef comp... | import argparse
import os
import numpy as np
import torch
import torch.nn.functional as f
from pathlib import Path
from torch_geometric.utils.convert import to_scipy_sparse_matrix
from utils.homophily_metrics import random_disassortative_splits, classifier_based_performance_metric, similarity, \
adjusted_homo, \
label_informativeness, node_homophily, our_measure, edge_homophily, generalized_edge_homophily
from utils.util_funcs import row_normalized_adjacency, sys_normalized_adjacency, full_load_data_large, normalize_tensor, \
sparse_mx_to_torch_sparse_tensor | 4,306 |
if torch.cuda.is_available():
device = 'cuda:0'
else:
device = 'cpu'
device = torch.device(device)
ifsum = 1
num_exp = 10
ACMGCN_FEATURES_PATH = os.path.dirname(os.path.abspath(__file__)) + '/data/acmgcn_features/'
Path(ACMGCN_FEATURES_PATH).mkdir(parents=True, exist_ok=True)
BASE_CLASSIFIERS = ['kernel_reg0', 'kernel_reg1', 'gnb']
SMALL_DATASETS = ['cornell', 'wisconsin', 'texas', 'film', 'chameleon', 'squirrel', 'cora', 'citeseer', 'pubmed']
LARGE_DATASETS = ['deezer-europe', 'Penn94', 'arxiv-year', "genius", "twitch-gamer", 'pokec', 'snap-patents']
DATASETS = SMALL_DATASETS + LARGE_DATASETS
METRIC_LIST = {
"node_homo": lambda adj, labels: node_homophily(adj, labels),
"edge_homo": lambda adj, labels: edge_homophily(adj, labels),
"class_homo": lambda adj, labels: our_measure(adj, labels),
"node_hom_generalized": lambda adj, features, labels: generalized_edge_homophily(adj, features, labels),
"agg_homo_soft": lambda x: np.mean(x),
"agg_homo_hard": lambda x: np.mean(x),
"adj_homo": lambda adj, labels: adjusted_homo(adj, labels),
"label_info": lambda adj, labels: label_informativeness(adj, labels),
"kernel_reg0_based_homo": lambda *args, **kwargs: classifier_based_performance_metric(*args, **kwargs),
"kernel_reg1_based_homo": lambda *args, **kwargs: classifier_based_performance_metric(*args, **kwargs),
"gnb_based_homo": lambda *args, **kwargs: classifier_based_performance_metric(*args, **kwargs)
}
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--no-cuda', action='store_true', default=False,
help='Disables CUDA training.')
parser.add_argument('--dataset_name', type=str, required=True, choices=DATASETS,
help=f"The data set name, please select from the following list: \n"
f"{DATASETS}")
parser.add_argument('--symmetric', type=float, default=0,
help='1 for symmetric renormalized adj, 0 for random walk renormalized adj')
parser.add_argument('--sample_max', type=float, default=500, help='maxinum number of samples used in gntk')
parser.add_argument('--base_classifier', type=str, default='kernel_reg1', choices=BASE_CLASSIFIERS,
help='The classifier used for performance metric(kernel_reg1, kernel_reg0, svm_linear, svm_rbf, svm_poly, gnb)')
parser.add_argument('--homophily_metric', required=True, choices=list(METRIC_LIST.keys()),
help="The metric to measure homophily, please select from the following list: \n"
"[ \n"
" node_homo (node homophily), \n"
" edge_homo (edge homophily), \n"
" class_homo (class homophily), \n"
" node_hom_generalized (generalized node homophily), \n"
" agg_homo_soft (aggreation homophily with soft LAS), \n"
" agg_homo_hard (aggreation homophily with hard LAS), \n"
" adj_homo (adjusted homophily), \n"
" label_info (label informativeness), \n"
" kernel_reg0_based_homo (kernel based homophily with reg0), \n"
" kernel_reg1_based_homo (kernel based homophily with reg1), \n"
" gnb_based_homo (gnd-based homophily) \n"
"]")
args = parser.parse_args()
dataset_name = args.dataset_name
homophily_metric = args.homophily_metric
homophily_lvl = -1
if dataset_name in SMALL_DATASETS:
adj_low_unnormalized, features, labels = full_load_data_large(dataset_name)
features = normalize_tensor(features).to(device)
nnodes = (labels.shape[0])
adj = normalize_tensor(torch.eye(nnodes) + adj_low_unnormalized.to_dense(),
symmetric=args.symmetric).to(device)
adj = adj.to_sparse().to(device)
labels = labels.to(device)
else:
adj_low_unnormalized, features, labels = full_load_data_large(dataset_name)
nnodes = (labels.shape[0])
adj_low_pt = ACMGCN_FEATURES_PATH + dataset_name + '_adj_low.pt'
adj_high_pt = ACMGCN_FEATURES_PATH + dataset_name + '_adj_high.pt'
features = f.normalize(features, p=1, dim=1)
if os.path.exists(adj_low_pt) and os.path.exists(adj_high_pt):
adj = torch.load(adj_low_pt)
else:
adj = to_scipy_sparse_matrix(adj_low_unnormalized.coalesce().indices())
if args.symmetric == 1:
|
if torch.cuda.is_available():
device = 'cuda:0'
else:
device = 'cpu'
device = torch.device(device)
ifsum = 1
num_exp = 10
ACMGCN_FEATURES_PATH = os.path.dirname(os.path.abspath(__file__)) + '/data/acmgcn_features/'
Path(ACMGCN_FEATURES_PATH).mkdir(parents=True, exist_ok=True)
BASE_CLASSIFIERS = ['kernel_reg0', 'kernel_reg1', 'gnb']
SMALL_DATASETS = ['cornell', 'wisconsin', 'texas', 'film', 'chameleon', 'squirrel', 'cora', 'citeseer', 'pubmed']
LARGE_DATASETS = ['deezer-europe', 'Penn94', 'arxiv-year', "genius", "twitch-gamer", 'pokec', 'snap-patents']
DATASETS = SMALL_DATASETS + LARGE_DATASETS
METRIC_LIST = {
"node_homo": lambda adj, labels: node_homophily(adj, labels),
"edge_homo": lambda adj, labels: edge_homophily(adj, labels),
"class_homo": lambda adj, labels: our_measure(adj, labels),
"node_hom_generalized": lambda adj, features, labels: generalized_edge_homophily(adj, features, labels),
"agg_homo_soft": lambda x: np.mean(x),
"agg_homo_hard": lambda x: np.mean(x),
"adj_homo": lambda adj, labels: adjusted_homo(adj, labels),
"label_info": lambda adj, labels: label_informativeness(adj, labels),
"kernel_reg0_based_homo": lambda *args, **kwargs: classifier_based_performance_metric(*args, **kwargs),
"kernel_reg1_based_homo": lambda *args, **kwargs: classifier_based_performance_metric(*args, **kwargs),
"gnb_based_homo": lambda *args, **kwargs: classifier_based_performance_metric(*args, **kwargs)
}
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--no-cuda', action='store_true', default=False,
help='Disables CUDA training.')
parser.add_argument('--dataset_name', type=str, required=True, choices=DATASETS,
help=f"The data set name, please select from the following list: \n"
f"{DATASETS}")
parser.add_argument('--symmetric', type=float, default=0,
help='1 for symmetric renormalized adj, 0 for random walk renormalized adj')
parser.add_argument('--sample_max', type=float, default=500, help='maxinum number of samples used in gntk')
parser.add_argument('--base_classifier', type=str, default='kernel_reg1', choices=BASE_CLASSIFIERS,
help='The classifier used for performance metric(kernel_reg1, kernel_reg0, svm_linear, svm_rbf, svm_poly, gnb)')
parser.add_argument('--homophily_metric', required=True, choices=list(METRIC_LIST.keys()),
help="The metric to measure homophily, please select from the following list: \n"
"[ \n"
" node_homo (node homophily), \n"
" edge_homo (edge homophily), \n"
" class_homo (class homophily), \n"
" node_hom_generalized (generalized node homophily), \n"
" agg_homo_soft (aggreation homophily with soft LAS), \n"
" agg_homo_hard (aggreation homophily with hard LAS), \n"
" adj_homo (adjusted homophily), \n"
" label_info (label informativeness), \n"
" kernel_reg0_based_homo (kernel based homophily with reg0), \n"
" kernel_reg1_based_homo (kernel based homophily with reg1), \n"
" gnb_based_homo (gnd-based homophily) \n"
"]")
args = parser.parse_args()
dataset_name = args.dataset_name
homophily_metric = args.homophily_metric
homophily_lvl = -1
if dataset_name in SMALL_DATASETS:
adj_low_unnormalized, features, labels = full_load_data_large(dataset_name)
features = normalize_tensor(features).to(device)
nnodes = (labels.shape[0])
adj = normalize_tensor(torch.eye(nnodes) + adj_low_unnormalized.to_dense(),
symmetric=args.symmetric).to(device)
adj = adj.to_sparse().to(device)
labels = labels.to(device)
else:
adj_low_unnormalized, features, labels = full_load_data_large(dataset_name)
nnodes = (labels.shape[0])
adj_low_pt = ACMGCN_FEATURES_PATH + dataset_name + '_adj_low.pt'
adj_high_pt = ACMGCN_FEATURES_PATH + dataset_name + '_adj_high.pt'
features = f.normalize(features, p=1, dim=1)
if os.path.exists(adj_low_pt) and os.path.exists(adj_high_pt):
adj = torch.load(adj_low_pt)
else:
adj = to_scipy_sparse_matrix(adj_low_unnormalized.coalesce().indices())
if args.symmetric == 1: | adj = sys_normalized_adjacency(adj) | 2 | 2023-11-12 22:52:06+00:00 | 8k |
fkostadinov/pygape | test/test_pygape.py | [
{
"identifier": "openai_completion",
"path": "pygape/completion.py",
"snippet": "def openai_completion(prompt: str) -> any:\n response = (None, None, None)\n try:\n client = OpenAI()\n completion = client.chat.completions.create(\n model='gpt-3.5-turbo',\n messa... | import unittest
import logging
import os
import openai
import json
from dotenv import load_dotenv
from pygape.completion import openai_completion
from pygape.pygape import \
sort, SortPrompt, SortOrder, \
filter, FilterPrompt, \
find, FindPrompt, \
truthy, TruthyPrompt, \
condition, ConditionPrompt | 4,078 | ###
# How to start: python -m unittest test.test_pygape.PyGapeTestCase -v
###
class PyGapeTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
# TODO: Put this in a config file
logging.basicConfig(filename='test_out.log', encoding='utf-8', level=logging.DEBUG)
# Add parent path and .env file in root directory to the test case paths
dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
load_dotenv(dotenv_path=dotenv_path)
openai.api_key = os.getenv("OPENAI_API_KEY")
super().setUpClass()
def test_sort(self):
logging.info("################################ test_sort ################################ ")
sort_params = SortPrompt(
system_role = "a helpful assistant",
items = ["cat", "rat", "mouse", "elephant", "fly", "tiger", "bacteria", "goldfish"],
order = SortOrder.descending,
criterion = "their physical weight"
)
expected = ["elephant", "tiger", "cat", "rat", "mouse", "goldfish", "fly", "bacteria"]
prompt = sort_params.to_str()
json_response = sort(prompt, openai_completion)
retrieved = json_response["result"] # type: list
self.assertEqual(len(retrieved), len(expected))
for i in range(len(expected)):
self.assertEqual(retrieved[i], expected[i])
def test_filter(self):
logging.info("################################ test_filter ################################ ")
filter_params = FilterPrompt(
system_role = "a helpful assistant",
items = ["cat", "rock", "house", "elephant", "airplane", "tiger", "bottle", "gold"],
criterion = "whether they are inanimate. Only keep the animate ones"
)
expected = ["cat", "elephant", "tiger"]
prompt = filter_params.to_str()
json_response = filter(prompt, openai_completion)
filtered_items = [item.lower() for item in json_response["result"]] # Ensure all strings are lower case; type: list
reasons_to_keep = json_response["reason"] # type: list
self.assertEqual(len(filtered_items), len(expected))
for i in range(len(expected)):
self.assertTrue(expected[i].lower() in filtered_items) # Make sure all strings are lower case
def test_find(self):
logging.info("################################ test_find ################################ ")
find_params = FindPrompt(
system_role = "a helpful assistant",
items = ["Lise Meitner", "Marie Curie", "Chien-Shiung Wu", "Alice Augusta Ball", "Marilyn Monroe", "Katherine Johnson"],
criterion = "this person is or was not a female scientist. In case there exist multiple people with the same name, count them as a female scientist"
)
expected = "Marilyn Monroe"
prompt = find_params.to_str()
json_response = find(prompt, openai_completion)
found_item = json_response["result"] # Ensure all strings are lower case; type: list
reason = json_response["reason"] # type: list
self.assertEqual(found_item, expected)
def test_truthy(self):
logging.info("################################ test_truthy ################################ ")
| ###
# How to start: python -m unittest test.test_pygape.PyGapeTestCase -v
###
class PyGapeTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
# TODO: Put this in a config file
logging.basicConfig(filename='test_out.log', encoding='utf-8', level=logging.DEBUG)
# Add parent path and .env file in root directory to the test case paths
dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
load_dotenv(dotenv_path=dotenv_path)
openai.api_key = os.getenv("OPENAI_API_KEY")
super().setUpClass()
def test_sort(self):
logging.info("################################ test_sort ################################ ")
sort_params = SortPrompt(
system_role = "a helpful assistant",
items = ["cat", "rat", "mouse", "elephant", "fly", "tiger", "bacteria", "goldfish"],
order = SortOrder.descending,
criterion = "their physical weight"
)
expected = ["elephant", "tiger", "cat", "rat", "mouse", "goldfish", "fly", "bacteria"]
prompt = sort_params.to_str()
json_response = sort(prompt, openai_completion)
retrieved = json_response["result"] # type: list
self.assertEqual(len(retrieved), len(expected))
for i in range(len(expected)):
self.assertEqual(retrieved[i], expected[i])
def test_filter(self):
logging.info("################################ test_filter ################################ ")
filter_params = FilterPrompt(
system_role = "a helpful assistant",
items = ["cat", "rock", "house", "elephant", "airplane", "tiger", "bottle", "gold"],
criterion = "whether they are inanimate. Only keep the animate ones"
)
expected = ["cat", "elephant", "tiger"]
prompt = filter_params.to_str()
json_response = filter(prompt, openai_completion)
filtered_items = [item.lower() for item in json_response["result"]] # Ensure all strings are lower case; type: list
reasons_to_keep = json_response["reason"] # type: list
self.assertEqual(len(filtered_items), len(expected))
for i in range(len(expected)):
self.assertTrue(expected[i].lower() in filtered_items) # Make sure all strings are lower case
def test_find(self):
logging.info("################################ test_find ################################ ")
find_params = FindPrompt(
system_role = "a helpful assistant",
items = ["Lise Meitner", "Marie Curie", "Chien-Shiung Wu", "Alice Augusta Ball", "Marilyn Monroe", "Katherine Johnson"],
criterion = "this person is or was not a female scientist. In case there exist multiple people with the same name, count them as a female scientist"
)
expected = "Marilyn Monroe"
prompt = find_params.to_str()
json_response = find(prompt, openai_completion)
found_item = json_response["result"] # Ensure all strings are lower case; type: list
reason = json_response["reason"] # type: list
self.assertEqual(found_item, expected)
def test_truthy(self):
logging.info("################################ test_truthy ################################ ") | truthy_params = TruthyPrompt( | 9 | 2023-11-13 21:47:18+00:00 | 8k |
doodledood/chat-flock | examples/three_way_ai_conductor.py | [
{
"identifier": "InMemoryChatDataBackingStore",
"path": "chatflock/backing_stores/in_memory.py",
"snippet": "class InMemoryChatDataBackingStore(ChatDataBackingStore):\n messages: List[ChatMessage]\n participants: Dict[str, ChatParticipant]\n last_message_id: Optional[int] = None\n\n def __in... | import typer
from dotenv import load_dotenv
from halo import Halo
from chatflock.backing_stores.in_memory import InMemoryChatDataBackingStore
from chatflock.base import Chat
from chatflock.conductors.langchain import LangChainBasedAIChatConductor
from chatflock.participants.langchain import LangChainBasedAIChatParticipant
from chatflock.participants.user import UserChatParticipant
from chatflock.renderers.terminal import TerminalChatRenderer
from examples.common import create_chat_model | 7,092 |
def three_way_ai_conductor(model: str = "gpt-4-1106-preview", temperature: float = 0.0) -> None:
chat_model = create_chat_model(model=model, temperature=temperature)
spinner = Halo(spinner="dots")
bartender = LangChainBasedAIChatParticipant(
name="Johnny",
role="Bartender",
personal_mission="You are a bartender at a Cafe called 'Coffee Time'. You are a friendly guy who likes to "
"chat with customers. You should collaborate with the Cook when the customer asks for food. "
"You are the one in front, greeting the customer.",
chat_model=chat_model,
spinner=spinner,
)
cook = LangChainBasedAIChatParticipant(
name="Greg",
role="Cook",
personal_mission="You are a cook at a Cafe called 'Coffee Time'. You are an impatient and serious guy who "
"doesn't like to chat with customers. You should collaborate with the Bartender when the "
"customer asks for food. You are the one in the back, preparing the food.",
chat_model=chat_model,
spinner=spinner,
)
user = UserChatParticipant(name="User")
participants = [user, bartender, cook]
chat = Chat(
backing_store=InMemoryChatDataBackingStore(),
|
def three_way_ai_conductor(model: str = "gpt-4-1106-preview", temperature: float = 0.0) -> None:
chat_model = create_chat_model(model=model, temperature=temperature)
spinner = Halo(spinner="dots")
bartender = LangChainBasedAIChatParticipant(
name="Johnny",
role="Bartender",
personal_mission="You are a bartender at a Cafe called 'Coffee Time'. You are a friendly guy who likes to "
"chat with customers. You should collaborate with the Cook when the customer asks for food. "
"You are the one in front, greeting the customer.",
chat_model=chat_model,
spinner=spinner,
)
cook = LangChainBasedAIChatParticipant(
name="Greg",
role="Cook",
personal_mission="You are a cook at a Cafe called 'Coffee Time'. You are an impatient and serious guy who "
"doesn't like to chat with customers. You should collaborate with the Bartender when the "
"customer asks for food. You are the one in the back, preparing the food.",
chat_model=chat_model,
spinner=spinner,
)
user = UserChatParticipant(name="User")
participants = [user, bartender, cook]
chat = Chat(
backing_store=InMemoryChatDataBackingStore(), | renderer=TerminalChatRenderer(), | 5 | 2023-11-12 11:10:58+00:00 | 8k |
yfqiu-nlp/temporal-llms | denoising_event_lm/data/dataset_readers/event_lm/event_seq2seq_transformer_reader.py | [
{
"identifier": "Seq2SeqTransformerReader",
"path": "denoising_event_lm/data/dataset_readers/seq2seq/seq2seq_transformer_reader.py",
"snippet": "class Seq2SeqTransformerReader(DatasetReader):\n \"\"\"\n Reads a Pickle QA file and returns a ``Dataset`` where the ``Instances`` have four\n fields:... | import json, pickle
import logging
import numpy as np
import random
import pandas as pd
from typing import Any, Dict, List, Tuple, Optional, Iterable
from copy import deepcopy
from allennlp.data.fields import MetadataField, ArrayField
from overrides import overrides
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.instance import Instance
from transformers import PreTrainedTokenizer
from transformers.tokenization_auto import AutoTokenizer
from denoising_event_lm.data.dataset_readers.seq2seq.seq2seq_transformer_reader import Seq2SeqTransformerReader
from denoising_event_lm.data.data_utils.event_lm.utils import print_stat_with_posneg, print_stat_chainlen
from denoising_event_lm.utils.constants import EVENT_TAG, ARGS_TAG, POINTER_EVENT_TAGS | 4,719 |
logger = logging.getLogger(__name__)
@DatasetReader.register("event_seq2seq_transformer_reader")
class EventSeq2SeqTransformerReader(Seq2SeqTransformerReader):
"""
Reads a Pickle QA file and returns a ``Dataset`` where the ``Instances`` have four
fields:
* ``question_with_context``, a ``TextField`` that contains the concatenation of question and context,
* ``answer_span``, a ``SpanField`` into the ``question`` ``TextField`` denoting the answer.
* ``context_span`` a ``SpanField`` into the ``question`` ``TextField`` denoting the context, i.e., the part of
the text that potential answers can come from.
* A ``MetadataField`` that stores the instance's ID, the original question, the original passage text, both of
these in tokenized form, and the gold answer strings, accessible as ``metadata['id']``,
``metadata['question']``, ``metadata['context']``, ``metadata['question_tokens']``,
``metadata['context_tokens']``, and ``metadata['answers']. This is so that we can more easily use the
official SQuAD evaluation script to get metrics.
Parameters
----------
transformer_model_name : ``str``, optional (default=``bert-base-cased``)
This reader chooses tokenizer and token indexer according to this setting.
length_limit : ``int``, optional (default=self._tokenizer.model_max_length)
We will make sure that the length of all input text never exceeds this many word pieces.
truncation_strategy : `str`, optional (default=`'longest_first'`)
String selected in the following options:
- 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
starting from the longest one at each token (when there is a pair of input sequences)
- 'only_first': Only truncate the first sequence
- 'only_second': Only truncate the second sequence
- 'do_not_truncate': Do not truncate (raise an error if the input sequence is longer than max_length)
test_mode : ``bool``, optional (default=True)
whether we are in the test mode.
source_prefix : ``str``, optional (default="")
the string to prepend on context. Mainly for T5 models.
target_suffix : ``str``, optional (default="")
the string to append on target. Mainly for T5 models.
"""
def __init__(
self,
tokenizer_model_name: str,
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
lowercase: bool = False,
length_limit: Optional[int] = None,
truncation_strategy: str = "longest_first",
test_mode: bool = False,
source_prefix: str = "",
target_prefix: str = "",
target_suffix: str = "",
task_specific_args: Optional[Dict[str, Any]] = None,
event_sep: str = EVENT_TAG,
|
logger = logging.getLogger(__name__)
@DatasetReader.register("event_seq2seq_transformer_reader")
class EventSeq2SeqTransformerReader(Seq2SeqTransformerReader):
"""
Reads a Pickle QA file and returns a ``Dataset`` where the ``Instances`` have four
fields:
* ``question_with_context``, a ``TextField`` that contains the concatenation of question and context,
* ``answer_span``, a ``SpanField`` into the ``question`` ``TextField`` denoting the answer.
* ``context_span`` a ``SpanField`` into the ``question`` ``TextField`` denoting the context, i.e., the part of
the text that potential answers can come from.
* A ``MetadataField`` that stores the instance's ID, the original question, the original passage text, both of
these in tokenized form, and the gold answer strings, accessible as ``metadata['id']``,
``metadata['question']``, ``metadata['context']``, ``metadata['question_tokens']``,
``metadata['context_tokens']``, and ``metadata['answers']. This is so that we can more easily use the
official SQuAD evaluation script to get metrics.
Parameters
----------
transformer_model_name : ``str``, optional (default=``bert-base-cased``)
This reader chooses tokenizer and token indexer according to this setting.
length_limit : ``int``, optional (default=self._tokenizer.model_max_length)
We will make sure that the length of all input text never exceeds this many word pieces.
truncation_strategy : `str`, optional (default=`'longest_first'`)
String selected in the following options:
- 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
starting from the longest one at each token (when there is a pair of input sequences)
- 'only_first': Only truncate the first sequence
- 'only_second': Only truncate the second sequence
- 'do_not_truncate': Do not truncate (raise an error if the input sequence is longer than max_length)
test_mode : ``bool``, optional (default=True)
whether we are in the test mode.
source_prefix : ``str``, optional (default="")
the string to prepend on context. Mainly for T5 models.
target_suffix : ``str``, optional (default="")
the string to append on target. Mainly for T5 models.
"""
def __init__(
self,
tokenizer_model_name: str,
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
lowercase: bool = False,
length_limit: Optional[int] = None,
truncation_strategy: str = "longest_first",
test_mode: bool = False,
source_prefix: str = "",
target_prefix: str = "",
target_suffix: str = "",
task_specific_args: Optional[Dict[str, Any]] = None,
event_sep: str = EVENT_TAG, | args_sep: str = ARGS_TAG, | 4 | 2023-11-14 11:57:28+00:00 | 8k |
CryptoFuzzPy/cryptofuzz | cryptofuzz/utils.py | [
{
"identifier": "b58encode",
"path": "cryptofuzz/bs58.py",
"snippet": "def b58encode(\n v: Union[str, bytes], alphabet: bytes = ALPHABET\n) -> bytes:\n \"\"\"\n Encode a string using Base58\n \"\"\"\n v = scrub_input(v)\n\n mainSize = len(v)\n v = v.lstrip(b'\\0')\n newSize = len... | import binascii
import os, re, hashlib
import random
import struct
import ecdsa
from typing import Union
from .bs58 import b58encode, b58decode, base58_check_encode, base58encodeCheck, base58decode, base58encode
from hdwallet import HDWallet as HD_W
from hdwallet.symbols import BTC, ETH, TRX, LTC, DOGE, DGB, BTG, RVN, QTUM, DASH, ZEC, BCH, AXE
from mnemonic import Mnemonic
from .assest import (
MAIN_DIGEST_RMD160,
MAX_PRIVATE_KEY,
MAIN_PREFIX,
MAIN_SUFFIX,
ZERO_BASE_NET,
VERSION_NETWORK,
BASE58_ALPHABET,
FINGERPRINT_RMD160,
COMPRESSED_PREFIX,
COMPRESSED_PREFIX2,
UNCOMPRESSED_PREFIX,
MAIN_DIGEST,
XPUB_PREFIX,
ZERO_BYTES,
BIP39
) | 5,962 | def mne_to_wif(self, mnemonic, compress: bool = False):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_wif(seed, compress)
def mne_to_int(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_int(seed)
def mne_to_xpub(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_xpub(seed)
def mne_to_xprv(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_xprv(seed)
def mne_to_addr(self, mnemonic, compress: bool = False):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_addr(seed, compress)
def mne_to_binary(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_binary(seed)
def bytes_to_mne(self, seed):
return Mnemonic().to_mnemonic(seed)
def bytes_to_seed(self, seed):
return hashlib.pbkdf2_hmac('sha512', seed, b'mnemonic', 2048)
def bytes_to_hex(self, seed):
return binascii.hexlify(self.bytes_to_seed(seed)).decode('utf-8')
def unHexlify(self, h: str):
return binascii.unhexlify(h)
def hex_to_bytes(self, hexed):
return binascii.unhexlify(hexed)
def hex_to_mne(self, hexed: str) -> str:
seed = self.hex_to_bytes(hexed)
return self.bytes_to_mne(seed)
def hex_to_wif(self, hexed, compress: bool = False) -> str:
return self.bytes_to_wif(self.hex_to_bytes(hexed), compress)
def hex_to_xprv(self, hexed: str) -> str:
return self.bytes_to_xprv(self.hex_to_bytes(hexed))
def hex_to_xpub(self, hexed: str) -> str:
return self.bytes_to_xpub(self.hex_to_bytes(hexed))
def hex_to_int(self, hexed: str) -> int:
return int(hexed, 16)
def hex_to_pub(self, hexed: str, compress: bool = False) -> bytes:
if compress:
return self.bytes_to_public(self.hex_to_bytes(hexed), True)
else:
return self.bytes_to_public(self.hex_to_bytes(hexed), False)
def hex_to_addr(self, hexed: str, compress: bool = False) -> str:
seed = self.hex_to_bytes(hexed)
if compress:
return self.bytes_to_addr(seed, True)
else:
return self.bytes_to_addr(seed, False)
def hex_to_binary(self, hexed: str) -> str:
return self.bytes_to_binary(self.hex_to_bytes(hexed))
def bytes_to_hex(self, seed):
privatekey_int = int.from_bytes(hashlib.sha256(seed).digest(), byteorder='big')
self.gen.checkValid(privatekey_int)
pvkByte = privatekey_int.to_bytes(32, byteorder='big')
return pvkByte.hex()
def bytes_to_int(self, seed) -> int:
return int.from_bytes(seed, byteorder='big')
def bytes_to_pub(self, seed_bytes: bytes) -> bytes:
sk = ecdsa.SigningKey.from_string(seed_bytes[:32], curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
pub = COMPRESSED_PREFIX2 + vk.to_string()[-32:] if vk.to_string()[-1] % 2 == 0 else b'\x03' + vk.to_string()[-32:]
return pub
def bytes_to_public(self, seed: bytes, compress: bool = True) -> bytes:
sk = ecdsa.SigningKey.from_string(seed, curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
if compress:
prefix = COMPRESSED_PREFIX2 if vk.pubkey.point.y() % 2 == 0 else COMPRESSED_PREFIX
return prefix + vk.to_string()[:32]
else:
return UNCOMPRESSED_PREFIX + vk.to_string()
def bytes_to_xpub(self, seed: bytes, chain_code=None) -> str:
if chain_code is None:
chain_code = os.urandom(32) # .hex
prefix = self.unHexlify(XPUB_PREFIX)
FINGERPRINT = ZERO_BYTES + ZERO_BYTES
pub = self.bytes_to_pub(seed)
xpub = prefix + MAIN_DIGEST + FINGERPRINT + chain_code + pub
Hash64 = self.double_sha256(xpub)
xpub += Hash64[:4]
xpubBase58 = b58encode(xpub)
return xpubBase58.decode('utf-8')
def bytes_to_mne(self, byte: bytes):
seed = byte[:32]
return Mnemonic("english").to_mnemonic(seed)
def bytes_to_binary(self, bytes_: bytes) -> str:
if len(bytes_) != 32:
raise ValueError("Input bytes should have a length of 32.")
# Convert each byte to its binary representation and pad with zeros
return ''.join(format(byte, '08b') for byte in bytes_)
def bytes_to_wif(self, private_key, compress=True):
if compress:
|
class Generator:
def __init__(self):
super().__init__()
def checkValid(self, key: int) -> bool:
if 0 < key < MAX_PRIVATE_KEY:
return True
else:
raise ValueError(f"Secret Scalar Must be greater than 0 and less than {MAX_PRIVATE_KEY}.")
def generate_private_key(self) -> str:
randkey = "".join(random.choice("0123456789abcdef") for _ in range(64))
if self.checkValid(int(randkey, 16)):
return randkey
else:
return self.generate_private_key()
def generate_xprv(self):
return "xprv" + binascii.hexlify(os.urandom(32)).decode('utf-8')
def generate_decimal(self) -> int: return random.randint(0, MAX_PRIVATE_KEY)
def generate_binary(self) -> str:
return "".join(random.choice("01") for _ in range(256))
def generate_entropy(self, entropy_bits=256):
entropy = os.urandom(entropy_bits // 8)
checksum = hashlib.sha256(entropy).digest()[0]
entropy_with_checksum = entropy + bytes([checksum])
return entropy_with_checksum
def generate_mnemonic(self, size: int) -> str:
characters = re.findall('[A-Z][a-z]+', BIP39)
return " ".join(random.choices(characters, k=size)).lower()
class Convertor:
def __init__(self):
super().__init__()
self.gen = Generator()
def double_sha256(self, data):
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
def mne_to_seed(self, mnemonic, password=""):
salt = ("mnemonic" + password).encode('utf-8')
seed = hashlib.pbkdf2_hmac('sha512', mnemonic.encode('utf-8'), salt, 2048)
return seed[:32]
def mne_to_bytes(self, mnemonic):
return self.mne_to_seed(mnemonic)
def mne_to_hex(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_hex(seed)
def mne_to_wif(self, mnemonic, compress: bool = False):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_wif(seed, compress)
def mne_to_int(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_int(seed)
def mne_to_xpub(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_xpub(seed)
def mne_to_xprv(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_xprv(seed)
def mne_to_addr(self, mnemonic, compress: bool = False):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_addr(seed, compress)
def mne_to_binary(self, mnemonic):
seed = self.mne_to_seed(mnemonic)
return self.bytes_to_binary(seed)
def bytes_to_mne(self, seed):
return Mnemonic().to_mnemonic(seed)
def bytes_to_seed(self, seed):
return hashlib.pbkdf2_hmac('sha512', seed, b'mnemonic', 2048)
def bytes_to_hex(self, seed):
return binascii.hexlify(self.bytes_to_seed(seed)).decode('utf-8')
def unHexlify(self, h: str):
return binascii.unhexlify(h)
def hex_to_bytes(self, hexed):
return binascii.unhexlify(hexed)
def hex_to_mne(self, hexed: str) -> str:
seed = self.hex_to_bytes(hexed)
return self.bytes_to_mne(seed)
def hex_to_wif(self, hexed, compress: bool = False) -> str:
return self.bytes_to_wif(self.hex_to_bytes(hexed), compress)
def hex_to_xprv(self, hexed: str) -> str:
return self.bytes_to_xprv(self.hex_to_bytes(hexed))
def hex_to_xpub(self, hexed: str) -> str:
return self.bytes_to_xpub(self.hex_to_bytes(hexed))
def hex_to_int(self, hexed: str) -> int:
return int(hexed, 16)
def hex_to_pub(self, hexed: str, compress: bool = False) -> bytes:
if compress:
return self.bytes_to_public(self.hex_to_bytes(hexed), True)
else:
return self.bytes_to_public(self.hex_to_bytes(hexed), False)
def hex_to_addr(self, hexed: str, compress: bool = False) -> str:
seed = self.hex_to_bytes(hexed)
if compress:
return self.bytes_to_addr(seed, True)
else:
return self.bytes_to_addr(seed, False)
def hex_to_binary(self, hexed: str) -> str:
return self.bytes_to_binary(self.hex_to_bytes(hexed))
def bytes_to_hex(self, seed):
privatekey_int = int.from_bytes(hashlib.sha256(seed).digest(), byteorder='big')
self.gen.checkValid(privatekey_int)
pvkByte = privatekey_int.to_bytes(32, byteorder='big')
return pvkByte.hex()
def bytes_to_int(self, seed) -> int:
return int.from_bytes(seed, byteorder='big')
def bytes_to_pub(self, seed_bytes: bytes) -> bytes:
sk = ecdsa.SigningKey.from_string(seed_bytes[:32], curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
pub = COMPRESSED_PREFIX2 + vk.to_string()[-32:] if vk.to_string()[-1] % 2 == 0 else b'\x03' + vk.to_string()[-32:]
return pub
def bytes_to_public(self, seed: bytes, compress: bool = True) -> bytes:
sk = ecdsa.SigningKey.from_string(seed, curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
if compress:
prefix = COMPRESSED_PREFIX2 if vk.pubkey.point.y() % 2 == 0 else COMPRESSED_PREFIX
return prefix + vk.to_string()[:32]
else:
return UNCOMPRESSED_PREFIX + vk.to_string()
def bytes_to_xpub(self, seed: bytes, chain_code=None) -> str:
if chain_code is None:
chain_code = os.urandom(32) # .hex
prefix = self.unHexlify(XPUB_PREFIX)
FINGERPRINT = ZERO_BYTES + ZERO_BYTES
pub = self.bytes_to_pub(seed)
xpub = prefix + MAIN_DIGEST + FINGERPRINT + chain_code + pub
Hash64 = self.double_sha256(xpub)
xpub += Hash64[:4]
xpubBase58 = b58encode(xpub)
return xpubBase58.decode('utf-8')
def bytes_to_mne(self, byte: bytes):
seed = byte[:32]
return Mnemonic("english").to_mnemonic(seed)
def bytes_to_binary(self, bytes_: bytes) -> str:
if len(bytes_) != 32:
raise ValueError("Input bytes should have a length of 32.")
# Convert each byte to its binary representation and pad with zeros
return ''.join(format(byte, '08b') for byte in bytes_)
def bytes_to_wif(self, private_key, compress=True):
if compress: | EXTENDED_KEY = MAIN_PREFIX + private_key + MAIN_SUFFIX | 9 | 2023-11-10 14:51:41+00:00 | 8k |
henriquesebastiao/poupy | project/apps/app/urls.py | [
{
"identifier": "AccountCreateView",
"path": "project/apps/app/views/accounts.py",
"snippet": "class AccountCreateView(LoginRequiredMixin, CreateView):\n \"\"\"Create a new account.\"\"\"\n\n login_url = 'login'\n\n model = Account\n form_class = AccountEditForm\n template_name = 'pages/a... | from django.urls import path
from ..app.views.accounts import (
AccountCreateView,
AccountListView,
AccountUpdateView,
DeleteAccountConfirmView,
DeleteAccountView,
)
from ..app.views.app import App
from ..app.views.expanse import ExpanseCreateView, ExpanseView
from ..app.views.income import IncomeCreateView, IncomeView
from ..app.views.login import LoginCreateView, LoginView, logout_view
from ..app.views.settings import (
UserApplicationUpdatePasswordView,
UserApplicationUpdateView,
)
from ..app.views.signup import SignupView, UserCreateView
from ..app.views.transactions import (
TransactionDeleteView,
TransactionEditView,
TransactionsView,
)
from ..app.views.transfer import TransferCreateView, TransferView | 4,445 | """URLs module."""
urlpatterns = [
path('', App.as_view(), name='app'),
path('signup/', SignupView.as_view(), name='signup'),
path('user-create/', UserCreateView.as_view(), name='user_create'),
path('login/', LoginView.as_view(), name='login'),
path('login/create/', LoginCreateView.as_view(), name='login_create'),
path('logout/', logout_view, name='logout'),
path('transactions/', TransactionsView.as_view(), name='transactions'),
path(
'transaction/<int:transaction_id>/edit/',
| """URLs module."""
urlpatterns = [
path('', App.as_view(), name='app'),
path('signup/', SignupView.as_view(), name='signup'),
path('user-create/', UserCreateView.as_view(), name='user_create'),
path('login/', LoginView.as_view(), name='login'),
path('login/create/', LoginCreateView.as_view(), name='login_create'),
path('logout/', logout_view, name='logout'),
path('transactions/', TransactionsView.as_view(), name='transactions'),
path(
'transaction/<int:transaction_id>/edit/', | TransactionEditView.as_view(), | 18 | 2023-11-17 21:05:05+00:00 | 8k |
UWNetworksLab/adn-compiler | compiler/element/props/flow.py | [
{
"identifier": "Expr",
"path": "compiler/element/node.py",
"snippet": "class Expr(Node):\n def __init__(self, lhs: Expr, op: Operator, rhs: Expr):\n self.lhs = lhs\n self.op = op\n self.rhs = rhs\n self.type = \"unknown\""
},
{
"identifier": "Identifier",
"pat... | from typing import Dict, List, Optional, Tuple
from compiler.element.node import *
from compiler.element.node import Expr, Identifier, MethodCall
from compiler.element.props.analyzer import (
AliasAnalyzer,
CopyAnalyzer,
DropAnalyzer,
ReadAnalyzer,
StateAnalyzer,
WriteAnalyzer,
)
from compiler.element.visitor import Visitor | 5,645 | prev = v.idx
return prev
def handle_match(self, match: Match, prev: int) -> None:
expr_v = Vertex(Statement(match.expr), len(self.vertices), "match_expr")
self.vertices.append(expr_v)
self.link(prev, expr_v.idx)
prev = expr_v.idx
end_points = []
for (p, s) in match.actions:
match len(s):
case 0:
head = PASS_NODE # empty statement, do nothing
rest = []
case 1:
head = s[0]
rest = []
case _:
head = s[0]
rest = s[1:]
head_v = Vertex(head, len(self.vertices), "match_head")
self.vertices.append(head_v)
self.link(prev, head_v.idx, (expr_v.node, p))
if len(rest) == 0:
end_points.append(head_v.idx)
else:
end_points.append(self.handle_block(rest, head_v.idx))
merge_v = Vertex(PASS_NODE, len(self.vertices), "match_merge")
self.vertices.append(merge_v)
for ep in end_points:
self.link(ep, merge_v.idx)
return merge_v.idx
def build_graph(self, proc: Procedure) -> None:
start_v = Vertex(START_NODE, 0, "start")
end_v = Vertex(END_NODE, 1, "end")
self.vertices.append(start_v)
self.vertices.append(end_v)
prev = 0
for body in proc.body:
# order matters, since match is a subclass of statement
if isinstance(body, Match):
prev = self.handle_match(body, prev)
elif isinstance(body, Statement):
prev = self.handle_block([body], prev)
else:
raise Exception("build graph encountered: ", body.__class__.__name__)
self.link(prev, end_v.idx)
def extract_path(self) -> List[List[Vertex]]:
q = [0]
ret: Dict[int, List[List[Vertex]]] = {}
ret[0] = [[self.vertices[0]]]
while len(q) > 0:
u = q.pop()
for e in self.edges:
if e.u == u:
v = self.vertices[e.v]
paths = ret[u].copy()
paths = [p + [v] for p in paths]
if e.v not in ret:
ret[e.v] = paths
else:
ret[e.v] = ret[e.v] + paths
self.in_deg[e.v] -= 1
if self.in_deg[e.v] == 0:
q.append(e.v)
return ret[1]
def analyze(self, proc: Procedure, verbose: bool = False) -> Property:
# Paths represent all possible code path of this element
self.build_graph(proc)
paths = self.extract_path()
rpc_name = f"rpc_{proc.name}"
if proc.name == "req":
direction = "NET"
elif proc.name == "resp":
direction = "APP"
report = "Total #Path = " + str(len(paths)) + "\n"
ret = Property()
# Visit every possible code path and take a union of the operation
for path in paths:
report += "\nFor path: \n "
report += "->".join([v.annotation for v in path if v != self.vertices[-1]])
report += "\n\n"
path_nodes = [v.node for v in path]
aa = AliasAnalyzer(rpc_name)
targets = aa.visitBlock(path_nodes, None)
wa = WriteAnalyzer(targets)
write = wa.visitBlock(path_nodes, None)
if write:
write_fields = wa.target_fields
report += "Write: "
for (k, v) in write_fields.items():
for vv in v:
report += f"{vv} "
ret.write.append(vv[0])
report += "\n"
ra = ReadAnalyzer(targets)
read = ra.visitBlock(path_nodes, None)
if read:
read_fields = ra.target_fields
report += "Read: "
for (k, v) in read_fields.items():
for vv in v:
report += f"({vv}) "
ret.read.append(vv)
report += "\n"
|
class Property:
def __init__(self) -> None:
self.drop: bool = False
self.block: bool = False
self.read: List[str] = []
self.write: List[str] = []
self.copy: bool = False
def check(self):
self.read = list(set(self.read))
self.write = list(set(self.write))
self.read = [i.strip("'") for i in self.read]
self.write = [i.strip("'") for i in self.write]
class Edge:
def __init__(self, u: int, v: int, w: Tuple[Expr, Expr] = []) -> None:
self.u = u
self.v = v
self.w = w
class Vertex:
def __init__(self, node: Node, idx: int, annotation: Optional[str] = None) -> None:
self.node = node
self.idx = idx
if annotation is None:
self.annotation = self.node.__class__.__name__
else:
self.annotation = "[" + annotation + "]" + self.node.__class__.__name__
class FlowGraph:
def __init__(self) -> None:
self.vertices: List[Vertex] = []
self.edges: List[Edge] = []
self.in_deg: Dict[int, int] = {}
def link(self, u: int, v: int, w: Tuple[Expr, Expr] = []) -> None:
self.edges.append(Edge(u, v, w))
if v in self.in_deg:
self.in_deg[v] += 1
else:
self.in_deg[v] = 1
def handle_block(self, block: List[Statement], prev: int) -> int:
for s in block:
assert isinstance(s, Statement)
v = Vertex(s, len(self.vertices))
self.vertices.append(v)
self.link(prev, v.idx)
prev = v.idx
return prev
def handle_match(self, match: Match, prev: int) -> None:
expr_v = Vertex(Statement(match.expr), len(self.vertices), "match_expr")
self.vertices.append(expr_v)
self.link(prev, expr_v.idx)
prev = expr_v.idx
end_points = []
for (p, s) in match.actions:
match len(s):
case 0:
head = PASS_NODE # empty statement, do nothing
rest = []
case 1:
head = s[0]
rest = []
case _:
head = s[0]
rest = s[1:]
head_v = Vertex(head, len(self.vertices), "match_head")
self.vertices.append(head_v)
self.link(prev, head_v.idx, (expr_v.node, p))
if len(rest) == 0:
end_points.append(head_v.idx)
else:
end_points.append(self.handle_block(rest, head_v.idx))
merge_v = Vertex(PASS_NODE, len(self.vertices), "match_merge")
self.vertices.append(merge_v)
for ep in end_points:
self.link(ep, merge_v.idx)
return merge_v.idx
def build_graph(self, proc: Procedure) -> None:
start_v = Vertex(START_NODE, 0, "start")
end_v = Vertex(END_NODE, 1, "end")
self.vertices.append(start_v)
self.vertices.append(end_v)
prev = 0
for body in proc.body:
# order matters, since match is a subclass of statement
if isinstance(body, Match):
prev = self.handle_match(body, prev)
elif isinstance(body, Statement):
prev = self.handle_block([body], prev)
else:
raise Exception("build graph encountered: ", body.__class__.__name__)
self.link(prev, end_v.idx)
def extract_path(self) -> List[List[Vertex]]:
q = [0]
ret: Dict[int, List[List[Vertex]]] = {}
ret[0] = [[self.vertices[0]]]
while len(q) > 0:
u = q.pop()
for e in self.edges:
if e.u == u:
v = self.vertices[e.v]
paths = ret[u].copy()
paths = [p + [v] for p in paths]
if e.v not in ret:
ret[e.v] = paths
else:
ret[e.v] = ret[e.v] + paths
self.in_deg[e.v] -= 1
if self.in_deg[e.v] == 0:
q.append(e.v)
return ret[1]
def analyze(self, proc: Procedure, verbose: bool = False) -> Property:
# Paths represent all possible code path of this element
self.build_graph(proc)
paths = self.extract_path()
rpc_name = f"rpc_{proc.name}"
if proc.name == "req":
direction = "NET"
elif proc.name == "resp":
direction = "APP"
report = "Total #Path = " + str(len(paths)) + "\n"
ret = Property()
# Visit every possible code path and take a union of the operation
for path in paths:
report += "\nFor path: \n "
report += "->".join([v.annotation for v in path if v != self.vertices[-1]])
report += "\n\n"
path_nodes = [v.node for v in path]
aa = AliasAnalyzer(rpc_name)
targets = aa.visitBlock(path_nodes, None)
wa = WriteAnalyzer(targets)
write = wa.visitBlock(path_nodes, None)
if write:
write_fields = wa.target_fields
report += "Write: "
for (k, v) in write_fields.items():
for vv in v:
report += f"{vv} "
ret.write.append(vv[0])
report += "\n"
ra = ReadAnalyzer(targets)
read = ra.visitBlock(path_nodes, None)
if read:
read_fields = ra.target_fields
report += "Read: "
for (k, v) in read_fields.items():
for vv in v:
report += f"({vv}) "
ret.read.append(vv)
report += "\n"
| da = DropAnalyzer(targets, direction) | 5 | 2023-11-13 07:31:52+00:00 | 8k |
tyang816/ProtSSN | src/dataset/cath_dataset.py | [
{
"identifier": "safe_index",
"path": "src/utils/dataset_utils.py",
"snippet": "def safe_index(l, e):\n \"\"\"\n Return index of element e in list l. If e is not present, return the last index\n \"\"\"\n try:\n return l.index(e)\n except:\n return len(l) - 1"
},
{
"i... | import os
import torch
import sys
import math
import random
import warnings
import torch
import os
import sys
import torch.nn.functional as F
import scipy.spatial as spa
import numpy as np
from tqdm import tqdm
from scipy.special import softmax
from Bio.PDB import PDBParser, ShrakeRupley
from Bio.PDB.PDBExceptions import PDBConstructionWarning
from rdkit.Chem import GetPeriodicTable
from typing import Callable, List, Optional
from torch.utils.data import DataLoader
from torch_geometric.data import InMemoryDataset, Data
from src.utils.dataset_utils import safe_index, one_hot_res, log, dihedral, NormalizeProtein, dataset_argument_, get_stat | 6,320 |
@property
def processed_file_names(self) -> str:
return ['train.pt', 'val.pt']
def write_info(self):
written_filename = os.path.join(self.root, 'wrong_protein_names.txt')
file = open(written_filename, "w+")
for protein_name in self.wrong_proteins:
file.writelines(protein_name + '\n')
file.close()
def process(self):
#generate graph data and save in graph dir
self.generate_protein_graph()
# self.write_info()
filenames = os.listdir(self.saved_graph_dir)
protein_length = len(filenames)
if self.set_length:
protein_length = min(protein_length, self.set_length)
if not self.normalize_file:
self.normalize_file = get_stat(self.saved_graph_dir)
random.shuffle(filenames)
train_list = [f for f in filenames if "_" in f or "-" in f]
filenames = [f for f in filenames if "_" not in f or "-" not in f]
train_list.extend(filenames[:-self.num_val])
filenames_list = [train_list, filenames[-self.num_val:]]
for k in range(2):####split train,val,test
data_list = []
###move special name to test set
special_name_list = ["p53-dimer.pdb.pt"]
for special_name in special_name_list:
if special_name in filenames_list[0]:
filenames_list[0].remove(special_name)
filenames_list[1].append(special_name)
for i in tqdm(range(len(filenames_list[k]))):
file = filenames_list[k][i]
try:
graph1 = torch.load(os.path.join(self.saved_graph_dir, file))##load processed graph data torch pt file
except:
print(file)
continue
del graph1['distances']
del graph1['edge_dist']
del graph1['mu_r_norm']
del graph1['seq']
data_list.append(graph1)
if self.is_normalize:
normalize_transform = NormalizeProtein(filename=self.normalize_file)
data_list = [d for d in data_list if normalize_transform(d)]
if self.pre_filter is not None:
data_list = [d for d in data_list if self.pre_filter(d)]
if self.pre_transform is not None:
data_list = [self.pre_transform(d) for d in data_list]
torch.save(data_list, self.processed_paths[k])
def generate_protein_graph(self):
names = os.listdir(self.raw_file_names)
print(names)
names.sort()
n = int(np.ceil(len(names) / self.divide_num))
names = names[n * self.divide_idx:min(len(names), n * (self.divide_idx + 1))]
for idx, name in enumerate(tqdm(names)):
saved_graph_filename = os.path.join(self.saved_graph_dir, name + '.pt')
if os.path.exists(saved_graph_filename):
continue
protein_filename = os.path.join(self.raw_file_names, name)
if (name in self.wrong_proteins) or (not protein_filename):
continue
try:
rec, rec_coords, c_alpha_coords, n_coords, c_coords,seq = self.get_receptor_inference(protein_filename)
except:
continue
if rec !=False:
if len(seq)>len(c_alpha_coords):
del seq[-(len(seq)-len(c_alpha_coords)):]
#meet "dna" data will remove the file and rec will be false
# print(self.c_alpha_max_neighbors)
rec_graph = self.get_calpha_graph(rec, c_alpha_coords, n_coords, c_coords, rec_coords,seq)
if not rec_graph:
self.wrong_proteins.append(name)
continue
torch.save(rec_graph, saved_graph_filename)
def rec_residue_featurizer(self, rec, chain_id, one_hot=True, add_feature=None):
count = 0
flag_sasa=1
try:
self.sr.compute(rec, level="R")
except:
flag_sasa=0
for i, chain in enumerate(rec.get_chains()):
if i != chain_id:
continue
num_res = len(list(chain.get_residues()))#len([_ for _ in rec.get_residues()])
num_feature = 2
if add_feature.any():
num_feature += add_feature.shape[1]
res_feature = torch.zeros(num_res, self.num_residue_type + num_feature)
for i, residue in enumerate(chain.get_residues()):
if flag_sasa==0:
residue.sasa=0
sasa = residue.sasa
for atom in residue:
if atom.name == 'CA':
bfactor = atom.bfactor
assert not np.isinf(bfactor)
assert not np.isnan(bfactor)
assert not np.isinf(sasa)
assert not np.isnan(sasa)
residx = safe_index(
self.allowable_features['possible_amino_acids'], residue.get_resname())
|
current_dir = os.getcwd()
sys.path.append(current_dir)
cwd = os.getcwd()
sys.path.append(cwd + '/src/dataset_utils')
warnings.filterwarnings("ignore")
one_letter = {
'VAL':'V', 'ILE':'I', 'LEU':'L', 'GLU':'E', 'GLN':'Q',
'ASP':'D', 'ASN':'N', 'HIS':'H', 'TRP':'W', 'PHE':'F', 'TYR':'Y',
'ARG':'R', 'LYS':'K', 'SER':'S', 'THR':'T', 'MET':'M', 'ALA':'A',
'GLY':'G', 'PRO':'P', 'CYS':'C'
}
class CathDataset(InMemoryDataset):
r"""
Args:
root (string): Root directory where the dataset should be saved.
name (string): The name of the dataset.
raw_dir (string, optional): Root directory where the
original dataset stored(default: :obj:`None`)
num_residue_type (int, optional): The number of amino acid types.
(default: obj:'20')
micro_radius (int, optional): The radius of micro-environment
centered on the mask node. (default: obj:'20')
c_alpha_max_neighbors (int, optional): The number of maximum
connected nodes. (default: obj:'10')
cutoff (int, optional): The maximum connected nodes distance
(default: obj:'30')
seq_dist_cut (int, optional): one-hot encoding the sequence distance
edge attribute
(default: obj:)
[0.25,0.5,0.75,0.9,0.95,0.98,0.99]
[ 2. 3. 13. 63. 127. 247. 347.]
num_val (int, optional): The number of validation samples in case of "random" split. (default: 500)
num_test (int, optional): The number of test samples in case of "random" split. (default: 1000)
# use_localdatastet (bool) (bool,optional): If :obj:'True', online dataset
# will be downloaded. If not, local pdb files will be used
# (default: obj:'True')
transform (callable, optional): A function/transform that takes in an
:obj:`torch_geometric.data.Data` object and returns a transformed
version. The data object will be transformed before every access.
(default: :obj:`None`)
pre_transform (callable, optional): A function/transform that takes in
an :obj:`torch_geometric.data.Data` object and returns a
transformed version. The data object will be transformed before
being saved to disk. (default: :obj:`None`)
pre_filter (callable, optional): A function that takes in an
:obj:`torch_geometric.data.Data` object and returns a boolean
value, indicating whether the data object should be included in the
final dataset. (default: :obj:`None`)
"""
splits = ['train', 'val', 'test']
allowable_features = {
'possible_atomic_num_list': list(range(1, 119)) + ['misc'],
'possible_chirality_list': [
'CHI_UNSPECIFIED',
'CHI_TETRAHEDRAL_CW',
'CHI_TETRAHEDRAL_CCW',
'CHI_OTHER'
],
'possible_degree_list': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'misc'],
'possible_numring_list': [0, 1, 2, 3, 4, 5, 6, 'misc'],
'possible_implicit_valence_list': [0, 1, 2, 3, 4, 5, 6, 'misc'],
'possible_formal_charge_list': [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 'misc'],
'possible_numH_list': [0, 1, 2, 3, 4, 5, 6, 7, 8, 'misc'],
'possible_number_radical_e_list': [0, 1, 2, 3, 4, 'misc'],
'possible_hybridization_list': [
'SP', 'SP2', 'SP3', 'SP3D', 'SP3D2', 'misc'
],
'possible_is_aromatic_list': [False, True],
'possible_is_in_ring3_list': [False, True],
'possible_is_in_ring4_list': [False, True],
'possible_is_in_ring5_list': [False, True],
'possible_is_in_ring6_list': [False, True],
'possible_is_in_ring7_list': [False, True],
'possible_is_in_ring8_list': [False, True],
'possible_amino_acids': ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS',
'MET',
'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', 'HIP', 'HIE', 'TPO', 'HID', 'LEV',
'MEU',
'PTR', 'GLV', 'CYT', 'SEP', 'HIZ', 'CYM', 'GLM', 'ASQ', 'TYS', 'CYX', 'GLZ', 'misc'],
'possible_atom_type_2': ['C*', 'CA', 'CB', 'CD', 'CE', 'CG', 'CH', 'CZ', 'N*', 'ND', 'NE', 'NH', 'NZ', 'O*',
'OD',
'OE', 'OG', 'OH', 'OX', 'S*', 'SD', 'SG', 'misc'],
'possible_atom_type_3': ['C', 'CA', 'CB', 'CD', 'CD1', 'CD2', 'CE', 'CE1', 'CE2', 'CE3', 'CG', 'CG1', 'CG2',
'CH2',
'CZ', 'CZ2', 'CZ3', 'N', 'ND1', 'ND2', 'NE', 'NE1', 'NE2', 'NH1', 'NH2', 'NZ', 'O',
'OD1',
'OD2', 'OE1', 'OE2', 'OG', 'OG1', 'OH', 'OXT', 'SD', 'SG', 'misc'],
}
def __init__(self, root: str,
split: str = 'train',
num_residue_type: int = 20,
micro_radius: int = 20,
c_alpha_max_neighbors: int = 10,
cutoff: int = 30,
seq_dist_cut: int = 64,
use_micro: bool = False,
use_angle: bool = False,
use_omega: bool = False,
transform: Optional[Callable] = None,
pre_transform: Optional[Callable] = None,
pre_filter: Optional[Callable] = None,
divide_num: int = 1,
divide_idx: int = 0,
set_length: int = 500,
num_val: int = 10,
is_normalize: bool = True,
normalize_file: str = None,
p: float = 0.5,
use_sasa: bool =False,
use_bfactor: bool = False,
use_dihedral: bool = False,
use_coordinate: bool = False,
use_denoise: bool = False,
noise_type: str = 'wild',
temperature = 1.0
):
self.p=p
self.use_sasa=use_sasa
self.use_bfactor=use_bfactor
self.use_dihedral=use_dihedral
self.use_coordinate=use_coordinate
self.use_denoise=use_denoise
self.noise_type = noise_type
self.temperature = temperature
self.split = split
assert self.split in self.splits
self.num_residue_type = num_residue_type
self.micro_radius = micro_radius
self.c_alpha_max_neighbors = c_alpha_max_neighbors
self.seq_dist_cut = seq_dist_cut
self.use_micro = use_micro
self.use_angle = use_angle
self.use_omega = use_omega
self.cutoff = cutoff
self.num_val = num_val
self.divide_num = divide_num
self.divide_idx = divide_idx
self.set_length = set_length
self.is_normalize = is_normalize
self.normalize_file = normalize_file
self.wrong_proteins = ['1kp0A01', '2atcA02']
self.sr = ShrakeRupley(probe_radius=1.4, # in A. Default is 1.40 roughly the radius of a water molecule.
n_points=100) # resolution of the surface of each atom. Default is 100. A higher number of points results in more precise measurements, but slows down the calculation.
self.periodic_table = GetPeriodicTable()
self.biopython_parser = PDBParser()
super().__init__(root, transform, pre_transform, pre_filter)
self.dataset = torch.load(self.processed_paths[self.splits.index(self.split)])
# self.data, self.slices = torch.load(
# self.processed_paths[self.splits.index(self.split)])
# self.nums_amino_cum = self.slices['x']
@property
def raw_file_names(self) -> str:
raw_file_names = os.path.join('data', 'cath', "dompdb")
if not os.path.exists(raw_file_names):
os.mkdir(raw_file_names)
return raw_file_names
@property
def raw_dir(self) -> str:
if not os.path.exists(self.root):
os.mkdir(self.root)
raw_dir = os.path.join(self.root, 'raw')
if not os.path.exists(raw_dir):
os.mkdir(raw_dir)
return raw_dir
@property
def saved_graph_dir(self) -> str:
dir_root = os.path.join(self.root)
if not os.path.exists(dir_root):
os.mkdir(dir_root)
dir_name = os.path.join(dir_root, 'graph_seq')
if not os.path.exists(dir_name):
os.mkdir(dir_name)
if not self.set_length:
self.set_length = len(os.listdir(dir_name))
return dir_name
@property
def saved_amino_cum(self) -> str:
amino_cum_name = os.path.join(
self.root, 'amino_cum.pt')
return amino_cum_name
@property
def processed_dir(self) -> str:
return os.path.join(self.root, 'processed_seq')
@property
def processed_file_names(self) -> str:
return ['train.pt', 'val.pt']
def write_info(self):
written_filename = os.path.join(self.root, 'wrong_protein_names.txt')
file = open(written_filename, "w+")
for protein_name in self.wrong_proteins:
file.writelines(protein_name + '\n')
file.close()
def process(self):
#generate graph data and save in graph dir
self.generate_protein_graph()
# self.write_info()
filenames = os.listdir(self.saved_graph_dir)
protein_length = len(filenames)
if self.set_length:
protein_length = min(protein_length, self.set_length)
if not self.normalize_file:
self.normalize_file = get_stat(self.saved_graph_dir)
random.shuffle(filenames)
train_list = [f for f in filenames if "_" in f or "-" in f]
filenames = [f for f in filenames if "_" not in f or "-" not in f]
train_list.extend(filenames[:-self.num_val])
filenames_list = [train_list, filenames[-self.num_val:]]
for k in range(2):####split train,val,test
data_list = []
###move special name to test set
special_name_list = ["p53-dimer.pdb.pt"]
for special_name in special_name_list:
if special_name in filenames_list[0]:
filenames_list[0].remove(special_name)
filenames_list[1].append(special_name)
for i in tqdm(range(len(filenames_list[k]))):
file = filenames_list[k][i]
try:
graph1 = torch.load(os.path.join(self.saved_graph_dir, file))##load processed graph data torch pt file
except:
print(file)
continue
del graph1['distances']
del graph1['edge_dist']
del graph1['mu_r_norm']
del graph1['seq']
data_list.append(graph1)
if self.is_normalize:
normalize_transform = NormalizeProtein(filename=self.normalize_file)
data_list = [d for d in data_list if normalize_transform(d)]
if self.pre_filter is not None:
data_list = [d for d in data_list if self.pre_filter(d)]
if self.pre_transform is not None:
data_list = [self.pre_transform(d) for d in data_list]
torch.save(data_list, self.processed_paths[k])
def generate_protein_graph(self):
names = os.listdir(self.raw_file_names)
print(names)
names.sort()
n = int(np.ceil(len(names) / self.divide_num))
names = names[n * self.divide_idx:min(len(names), n * (self.divide_idx + 1))]
for idx, name in enumerate(tqdm(names)):
saved_graph_filename = os.path.join(self.saved_graph_dir, name + '.pt')
if os.path.exists(saved_graph_filename):
continue
protein_filename = os.path.join(self.raw_file_names, name)
if (name in self.wrong_proteins) or (not protein_filename):
continue
try:
rec, rec_coords, c_alpha_coords, n_coords, c_coords,seq = self.get_receptor_inference(protein_filename)
except:
continue
if rec !=False:
if len(seq)>len(c_alpha_coords):
del seq[-(len(seq)-len(c_alpha_coords)):]
#meet "dna" data will remove the file and rec will be false
# print(self.c_alpha_max_neighbors)
rec_graph = self.get_calpha_graph(rec, c_alpha_coords, n_coords, c_coords, rec_coords,seq)
if not rec_graph:
self.wrong_proteins.append(name)
continue
torch.save(rec_graph, saved_graph_filename)
def rec_residue_featurizer(self, rec, chain_id, one_hot=True, add_feature=None):
count = 0
flag_sasa=1
try:
self.sr.compute(rec, level="R")
except:
flag_sasa=0
for i, chain in enumerate(rec.get_chains()):
if i != chain_id:
continue
num_res = len(list(chain.get_residues()))#len([_ for _ in rec.get_residues()])
num_feature = 2
if add_feature.any():
num_feature += add_feature.shape[1]
res_feature = torch.zeros(num_res, self.num_residue_type + num_feature)
for i, residue in enumerate(chain.get_residues()):
if flag_sasa==0:
residue.sasa=0
sasa = residue.sasa
for atom in residue:
if atom.name == 'CA':
bfactor = atom.bfactor
assert not np.isinf(bfactor)
assert not np.isnan(bfactor)
assert not np.isinf(sasa)
assert not np.isnan(sasa)
residx = safe_index(
self.allowable_features['possible_amino_acids'], residue.get_resname()) | res_feat_1 = one_hot_res( | 1 | 2023-11-10 07:21:37+00:00 | 8k |
HypeboyJake/ReinforceTradeAI | c_main.py | [
{
"identifier": "CoinTradingEnv",
"path": "CoinTradingEnv.py",
"snippet": "class CoinTradingEnv(gym.Env):\r\n def __init__(self, data):\r\n super(CoinTradingEnv, self).__init__()\r\n self.data = data\r\n # 0 : Buy, 1 : Sell, 3 : Hold\r\n self.action_space = gym.spaces.Disc... | import torch
import pandas as pd
from tqdm import tqdm
from CoinTradingEnv import CoinTradingEnv
from sharing.agent import Agent
from sharing.visualization import create_folder, plot_all_charts
| 4,095 |
'''
파일의 형식은 0번째 날짜, 3번째 종가를 무조건 지켜주셔야합니다.
The file format must strictly follow:
date as the 0th element, and closing price as the 3rd element.
'''
"실제 파일경로를 입력해주세요"
"Please enter the actual file path."
real_data = pd.read_csv("file_path")
#"data는 시각화에만 사용되고 학습할 때 사용하지 않습니다"
#"The data is used only for visualization and not for training purposes"
"write the correct feature name"
data = real_data.drop(['Date'], axis=1)
#data = real_data.drop(['Time'], axis=1)
"파일에 결측치가 있다면 각주를 풀어주세요.(평균으로 대체)"
"If there are missing values in the file, please annotate them. (Replace with average)"
# data.fillna(data.mean(), inplace=True) # NAN값 평균으로 대체
data = data.values
env = CoinTradingEnv(data)
"파일의 피쳐수를 넣어주세요 (피쳐수, )형식을 유지해주세요."
"Please enter the number of features in the file, and maintain the format (number of features, )."
"ex ) state_dim = (7,)"
state_dim =
action_dim = env.action_space.n
|
'''
파일의 형식은 0번째 날짜, 3번째 종가를 무조건 지켜주셔야합니다.
The file format must strictly follow:
date as the 0th element, and closing price as the 3rd element.
'''
"실제 파일경로를 입력해주세요"
"Please enter the actual file path."
real_data = pd.read_csv("file_path")
#"data는 시각화에만 사용되고 학습할 때 사용하지 않습니다"
#"The data is used only for visualization and not for training purposes"
"write the correct feature name"
data = real_data.drop(['Date'], axis=1)
#data = real_data.drop(['Time'], axis=1)
"파일에 결측치가 있다면 각주를 풀어주세요.(평균으로 대체)"
"If there are missing values in the file, please annotate them. (Replace with average)"
# data.fillna(data.mean(), inplace=True) # NAN값 평균으로 대체
data = data.values
env = CoinTradingEnv(data)
"파일의 피쳐수를 넣어주세요 (피쳐수, )형식을 유지해주세요."
"Please enter the number of features in the file, and maintain the format (number of features, )."
"ex ) state_dim = (7,)"
state_dim =
action_dim = env.action_space.n
| agent = Agent(input_dim=state_dim, output_dim=action_dim, epsilon=0.3 , gamma= 0.99)
| 1 | 2023-11-16 12:04:20+00:00 | 8k |
atlantic-quantum/Shipyard | tests/passes/test_core_splitter.py | [
{
"identifier": "TransformError",
"path": "shipyard/compiler_error.py",
"snippet": "class TransformError(Error):\n \"\"\"Error class for Transformation Errors, raised by QASMTransformer subclasses\"\"\""
},
{
"identifier": "CoreSplitter",
"path": "shipyard/passes/core_splitter.py",
"s... | from copy import deepcopy
from pathlib import Path
from openpulse import ast, parse
from openpulse.printer import dumps
from shipyard.compiler_error import TransformError
from shipyard.passes.core_splitter import CoreSplitter, ports_for_core
from shipyard.passes.remove_unused import RemoveUnused
from shipyard.setup.internal import SetupInternal
import pytest | 6,905 |
def test_split_basic():
""" """
qasm_path = Path(__file__).parent.parent / "qasm/split.qasm"
with open(qasm_path, encoding="utf_8") as qasm_file:
qasm_code = qasm_file.read()
qasm_ast = parse(qasm_code)
def split_port(port, target_file):
transformed_ast = CoreSplitter(port).visit(deepcopy(qasm_ast))
RemoveUnused().visit(transformed_ast)
with open(
Path(__file__).parent.parent / f"qasm/{target_file}.qasm", encoding="utf_8"
) as qasm_file:
post_split = qasm_file.read()
# print(dumps(transformed_ast))
for genrated, target in zip(
dumps(transformed_ast).split("\n"), post_split.split("\n")
):
assert genrated == target
split_port("awg1_ch1", "post_split_1")
split_port("awg2_ch1", "post_split_2")
def test_ports_for_core():
json_path = Path(__file__).parent.parent / "setups/complex.json"
|
def test_split_basic():
""" """
qasm_path = Path(__file__).parent.parent / "qasm/split.qasm"
with open(qasm_path, encoding="utf_8") as qasm_file:
qasm_code = qasm_file.read()
qasm_ast = parse(qasm_code)
def split_port(port, target_file):
transformed_ast = CoreSplitter(port).visit(deepcopy(qasm_ast))
RemoveUnused().visit(transformed_ast)
with open(
Path(__file__).parent.parent / f"qasm/{target_file}.qasm", encoding="utf_8"
) as qasm_file:
post_split = qasm_file.read()
# print(dumps(transformed_ast))
for genrated, target in zip(
dumps(transformed_ast).split("\n"), post_split.split("\n")
):
assert genrated == target
split_port("awg1_ch1", "post_split_1")
split_port("awg2_ch1", "post_split_2")
def test_ports_for_core():
json_path = Path(__file__).parent.parent / "setups/complex.json" | complex_setup = SetupInternal.from_json(json_path) | 4 | 2023-11-16 17:37:29+00:00 | 8k |
PrAsAnNaRePo/LocalAgent | localagent/initialize_agents.py | [
{
"identifier": "KnowledgeBase",
"path": "localagent/knowledge_base.py",
"snippet": "class KnowledgeBase:\n def __init__(\n self,\n file_dir: str\n ) -> None:\n \"\"\"\n Creates a knowledge base for Agent.\n\n Args:\n file_dir (str): The path t... | import json
import warnings
from localagent.knowledge_base import KnowledgeBase
from localagent.utils import get_prompt_from_template, assistant_message, internal_monologue, important_message, clear_line, warning_message
from localagent.interpreter import Interpreter
from localagent.gen import stream_run, run, ollama_generate
from rich.console import Console | 5,143 | 'required': True,
'schema': {
'type': 'string'
},
}],
}
)
if len(self.tools) != 0:
self.system_prompt = self.create_prompt_with_tools()
def create_prompt_with_tools(self):
tool_desc = """{name_for_model}: Call this tool to interact with the {name_for_human} API. What is the {name_for_human} API useful for? {description_for_model} Parameters: {parameters} Format the arguments as a JSON object."""
tool_descs = []
tool_names = []
for info in self.tools:
tool_descs.append(
tool_desc.format(
name_for_model=info['name_for_model'],
name_for_human=info['name_for_human'],
description_for_model=info['description_for_model'],
parameters=json.dumps(
info['parameters'], ensure_ascii=False),
)
)
tool_names.append(info['name_for_model'])
tool_descs = '\n\n'.join(tool_descs)
tool_names = ','.join(tool_names)
if self.use_codeinterpreter:
react_prompt = f"""{self.system_}
YOUR PERSONA:
{self.system_prompt}
You have access to these following tools:
{tool_descs}
Use the following format:
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Message: the final answer to the original input question
{self.human_}: hey, you UP!{self.eos_token}{self.assistant_}:
Thought: User asking about my availability, I should respond by telling i'm available for assistance. So no need to use any tool for this.
Message: Hey there! I'm just here. How can I help you today?{self.eos_token}
{self.human_}: Create a folder called Project-1 and create a file called temp.py in it.{self.eos_token}{self.assistant_}:
Thought: The user wants to create a folder and a file in it, so I need to ask code_interpreter to create folder and file.
Action: code_interpreter
Action Input: {{"task": "Create a folder called Project-1 in the current folder and create a file called temp.py in Project-1 folder."}}{self.eos_token}
{self.human_}: This is code interpreter (not user). Created a folder called Project-1 and created a file called temp.py inside Project-1.
Thought: Now the files are created. I should tell the user about it. No need to use any tools again.
Message: Created a folder and file in it. I'm here to help you if you need any assistance.{self.eos_token}
"""
else:
react_prompt = f"""{self.system_}
YOUR PERSONA:
{self.system_prompt}
{tool_descs}
Use the following format:
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action (in json format)
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Message: the final answer to the original input question
{self.human_}: hey, you UP!{self.eos_token}{self.assistant_}:
Thought: User asking about my availability, I should respond by telling i'm available for assistance. So no need to use any tool for this.
Message: Hey there! I'm just here. How can I help you today?{self.eos_token}"""
return react_prompt
def go_flow(self, prompt):
self.history.append({'role':'user', 'content':prompt})
done = False
while not done:
prompt = get_prompt_from_template(self.system_prompt, self.history, self.human_, self.assistant_, self.eos_token)
if len(self.tools) != 0:
if self.stream:
raw_response = stream_run(self.webui_url, prompt, force_model=True) if self.webui_url else ollama_generate(self.olla_model_name, template=prompt, force_model=True, stream=True)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
else:
with console.status("[bold cyan]Thinking...") as status:
raw_response = run(self.webui_url, prompt, force_model=True) if self.webui_url else ollama_generate(self.olla_model_name, template=prompt)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
else:
if self.stream:
raw_response = stream_run(self.webui_url, prompt) if self.webui_url else ollama_generate(self.olla_model_name, template=prompt, stream=True)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
else:
with console.status("[bold cyan]Thinking...") as status:
raw_response = str(run(self.webui_url, prompt)) if self.webui_url else ollama_generate(model_name=self.olla_model_name, template=prompt)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
self.history.append({"role": "assistant", "content": raw_response})
if len(self.tools) != 0:
response = raw_response.strip().split('\n')
thought, message, action, action_inp = None, None, None, None
for i in response:
if i.startswith('Thought:'):
thought = i.replace('Thought: ', '')
if i.startswith('Message:'):
message = i.replace('Message: ', '')
if i.startswith('Action:'):
action = i.replace('Action: ', '')
if action:
start_index = raw_response.find('{')
end_index = raw_response.rfind('}')
json_part = raw_response[start_index:end_index + 1]
action_inp = json.loads(json_part)
|
console = Console()
warnings.filterwarnings("ignore")
class CreateAgent:
def __init__(
self,
webui_url: str=None,
ollama_model_name:str = None,
system_prompt: str = None,
system_:str = '',
human_:str = 'GPT4 User',
assistant_:str = "GPT4 Assistant",
eos_token:str = '<|end_of_turn|>',
tools: list[dict] = None,
use_codeinterpreter: bool = False,
interpreter_max_try:int = 3,
knowledge_base: KnowledgeBase = None,
stream:bool = False,
verbose:bool = False,
) -> None:
assert webui_url is not None or ollama_model_name is not None, 'Either webui_url or ollama_model_name should be given.'
self.webui_url = webui_url
self.olla_model_name = ollama_model_name
self.stream = stream
if webui_url is not None:
if webui_url.startswith('http'):
self.stream = False
self.webui_url = webui_url+'/v1/generate'
if verbose:
important_message('agent initialized with non stream, If you want to start agent with streaming pass the streaming uri instead.')
elif webui_url.startswith('ws'):
self.stream = True
self.webui_url = webui_url
if verbose:
important_message('agent initialized with stream, If you want to start agent with non streaming pass the regular api uri instead.')
self.system_prompt = system_prompt
self.tools = tools
self.system_ = system_
self.human_ = human_
self.assistant_ = assistant_
self.eos_token = eos_token
self.use_codeinterpreter = use_codeinterpreter
self.knowledge_base = knowledge_base
self.verbose = verbose
self.history = []
if verbose:
important_message(f'Agent initialized with stream={self.stream}')
if not system_prompt:
if verbose:
important_message('No system prompt given, creating default system prompt.')
self.system_prompt = f'{self.system_}\nYou are an AI assistant\n'
if not self.tools:
self.tools = []
if knowledge_base is not None:
if verbose:
important_message('Knowledge base is given, creating knowledge_retrival tool.')
self.system_prompt += 'You have given a Knowledge document where you able to access contents in that using knowledge_retrival tool.\n'
self.tools.append(
{
'name_for_human':
'Knowledge retrival',
'name_for_model':
'knowledge_retrival',
'description_for_model':
'knowledge_retrival is a tool used to retrive any information from the Knowledge document.',
'parameters': [{
'name': 'query',
'description': 'A query to search the specific information from document uploaded.',
'required': True,
'schema': {
'type': 'string'
},
}],
}
)
if use_codeinterpreter:
if verbose:
important_message('Code interpreter is enabled, creating code_interpreter tool.')
self.interpreter = Interpreter(
exec={"name": 'ollama' if self.olla_model_name is not None else 'webui', "uri": self.olla_model_name if self.olla_model_name is not None else self.webui_url},
max_try=interpreter_max_try,
human_=human_,
assistant_=assistant_,
eos_token=eos_token,
stream=self.stream,
)
self.tools.append(
{
'name_for_human':
'code interpreter',
'name_for_model':
'code_interpreter',
'description_for_model':
'Code Interpreter enables the assistant to write and run code. code_interpreter is sensitive, it need all the information about the task to perform it such as path to file, correct file name, any other information required to perform the task.',
'parameters': [{
'name': 'task',
'description': 'Describe the task clearly and briefly to the code interpreter to run the code and returns the output with you.',
'required': True,
'schema': {
'type': 'string'
},
}],
}
)
if len(self.tools) != 0:
self.system_prompt = self.create_prompt_with_tools()
def create_prompt_with_tools(self):
tool_desc = """{name_for_model}: Call this tool to interact with the {name_for_human} API. What is the {name_for_human} API useful for? {description_for_model} Parameters: {parameters} Format the arguments as a JSON object."""
tool_descs = []
tool_names = []
for info in self.tools:
tool_descs.append(
tool_desc.format(
name_for_model=info['name_for_model'],
name_for_human=info['name_for_human'],
description_for_model=info['description_for_model'],
parameters=json.dumps(
info['parameters'], ensure_ascii=False),
)
)
tool_names.append(info['name_for_model'])
tool_descs = '\n\n'.join(tool_descs)
tool_names = ','.join(tool_names)
if self.use_codeinterpreter:
react_prompt = f"""{self.system_}
YOUR PERSONA:
{self.system_prompt}
You have access to these following tools:
{tool_descs}
Use the following format:
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Message: the final answer to the original input question
{self.human_}: hey, you UP!{self.eos_token}{self.assistant_}:
Thought: User asking about my availability, I should respond by telling i'm available for assistance. So no need to use any tool for this.
Message: Hey there! I'm just here. How can I help you today?{self.eos_token}
{self.human_}: Create a folder called Project-1 and create a file called temp.py in it.{self.eos_token}{self.assistant_}:
Thought: The user wants to create a folder and a file in it, so I need to ask code_interpreter to create folder and file.
Action: code_interpreter
Action Input: {{"task": "Create a folder called Project-1 in the current folder and create a file called temp.py in Project-1 folder."}}{self.eos_token}
{self.human_}: This is code interpreter (not user). Created a folder called Project-1 and created a file called temp.py inside Project-1.
Thought: Now the files are created. I should tell the user about it. No need to use any tools again.
Message: Created a folder and file in it. I'm here to help you if you need any assistance.{self.eos_token}
"""
else:
react_prompt = f"""{self.system_}
YOUR PERSONA:
{self.system_prompt}
{tool_descs}
Use the following format:
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action (in json format)
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Message: the final answer to the original input question
{self.human_}: hey, you UP!{self.eos_token}{self.assistant_}:
Thought: User asking about my availability, I should respond by telling i'm available for assistance. So no need to use any tool for this.
Message: Hey there! I'm just here. How can I help you today?{self.eos_token}"""
return react_prompt
def go_flow(self, prompt):
self.history.append({'role':'user', 'content':prompt})
done = False
while not done:
prompt = get_prompt_from_template(self.system_prompt, self.history, self.human_, self.assistant_, self.eos_token)
if len(self.tools) != 0:
if self.stream:
raw_response = stream_run(self.webui_url, prompt, force_model=True) if self.webui_url else ollama_generate(self.olla_model_name, template=prompt, force_model=True, stream=True)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
else:
with console.status("[bold cyan]Thinking...") as status:
raw_response = run(self.webui_url, prompt, force_model=True) if self.webui_url else ollama_generate(self.olla_model_name, template=prompt)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
else:
if self.stream:
raw_response = stream_run(self.webui_url, prompt) if self.webui_url else ollama_generate(self.olla_model_name, template=prompt, stream=True)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
else:
with console.status("[bold cyan]Thinking...") as status:
raw_response = str(run(self.webui_url, prompt)) if self.webui_url else ollama_generate(model_name=self.olla_model_name, template=prompt)[0].replace(self.eos_token, "").replace(self.eos_token[:-1], "")
self.history.append({"role": "assistant", "content": raw_response})
if len(self.tools) != 0:
response = raw_response.strip().split('\n')
thought, message, action, action_inp = None, None, None, None
for i in response:
if i.startswith('Thought:'):
thought = i.replace('Thought: ', '')
if i.startswith('Message:'):
message = i.replace('Message: ', '')
if i.startswith('Action:'):
action = i.replace('Action: ', '')
if action:
start_index = raw_response.find('{')
end_index = raw_response.rfind('}')
json_part = raw_response[start_index:end_index + 1]
action_inp = json.loads(json_part)
| internal_monologue(thought) | 3 | 2023-11-10 07:47:41+00:00 | 8k |
ceterum1/llm-defender-subnet | llm_defender/core/miners/miner.py | [
{
"identifier": "BaseNeuron",
"path": "llm_defender/base/neuron.py",
"snippet": "class BaseNeuron:\n \"\"\"Summary of the class\n\n Class description\n\n Attributes:\n parser:\n Instance of ArgumentParser with the arguments given as\n command-line arguments in the e... | from argparse import ArgumentParser
from typing import Tuple
from llm_defender.base.neuron import BaseNeuron
from llm_defender.base.protocol import LLMDefenderProtocol
from llm_defender.core.miners.engines.prompt_injection.yara import YaraEngine
from llm_defender.core.miners.engines.prompt_injection.text_classification import TextClassificationEngine
from llm_defender.core.miners.engines.prompt_injection.vector_search import VectorEngine
from llm_defender.base.utils import validate_miner_blacklist
import sys
import requests
import bittensor as bt | 4,889 | """Module for prompt-injection neurons for the
llm-defender-subnet.
Long description
Typical example usage:
foo = bar()
foo.bar()
"""
class PromptInjectionMiner(BaseNeuron):
"""Summary of the class
Class description
Attributes:
"""
def __init__(self, parser: ArgumentParser):
super().__init__(parser=parser, profile="miner")
self.neuron_config = self.config(
bt_classes=[bt.subtensor, bt.logging, bt.wallet, bt.axon]
)
args = parser.parse_args()
if args.miner_set_weights == "False":
self.miner_set_weights = False
else:
self.miner_set_weights = True
self.chromadb_client = VectorEngine().initialize()
| """Module for prompt-injection neurons for the
llm-defender-subnet.
Long description
Typical example usage:
foo = bar()
foo.bar()
"""
class PromptInjectionMiner(BaseNeuron):
"""Summary of the class
Class description
Attributes:
"""
def __init__(self, parser: ArgumentParser):
super().__init__(parser=parser, profile="miner")
self.neuron_config = self.config(
bt_classes=[bt.subtensor, bt.logging, bt.wallet, bt.axon]
)
args = parser.parse_args()
if args.miner_set_weights == "False":
self.miner_set_weights = False
else:
self.miner_set_weights = True
self.chromadb_client = VectorEngine().initialize()
| self.model, self.tokenizer = TextClassificationEngine().initialize() | 3 | 2023-11-14 18:10:35+00:00 | 8k |
rohitsinghlab/sceodesic | sceodesic/sceo.py | [
{
"identifier": "fn_timer",
"path": "sceodesic/utils/fn_timer.py",
"snippet": "def fn_timer(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n\n # run and time function\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n el... | import numpy as np
import pandas as pd
import scipy
import scanpy as sc
import anndata
import fbpca
import sklearn
import os, sys, yaml, pickle
import functools, random
import time
from numpy.linalg import eig, eigh
from scipy.linalg import logm, svd, expm
from scipy.stats import mannwhitneyu, pearsonr, spearmanr, kendalltau, rankdata
from sklearn.decomposition import SparsePCA, MiniBatchSparsePCA, PCA
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.cluster import KMeans
from .utils import fn_timer
from .sceo_io.sceo_command_line_parser import parse_sceo_command_line_args
from .sceo_io.sceo_load_input import load_input
from .helper import compute_covariance_and_ncomps_pct_variance
from .sceo_main.get_cell_cohorts import _get_cell_cohorts
from .sceo_main.get_locally_variable_genes import _get_locally_variable_genes
from .sceo_main.estimate_covariances import _estimate_covariances
from .sceo_main.reconstruct_programs import _reconstruct_programs
from .sceo_main.write_embedding import _write_embedding | 5,936 |
## package-specific modules
# Default configuration
DEFAULT_CONFIG = {
'num_clusters': 500,
'num_hvg': 300,
'max_condition_number': 50,
'sparse_pca_lambda': 0.03,
'stratify_clustering_by_columns': 'none',
'filepath': '',
'num_hvg_per_cluster': 100,
'pvd_pct': 0.90,
'do_global_hvg': False,
# for very advanced users
'n_init': 1 # K-Means
}
def main():
args = parse_sceo_command_line_args(DEFAULT_CONFIG)
### TESTING ###
print("config:", args.config)
### TESTING ###
output_identifier = "%s_%d_hvgs_%s_clusters_%g_sparsity" % (args.output_prefix, args.num_hvg,
str(args.config.get('num_clusters')), args.config.get('sparse_pca_lambda'))
args.config['output_identifier'] = output_identifier
filepath = args.config.get('filepath', DEFAULT_CONFIG['filepath']) + '/' #if the backslash is extra, it won't hurt
args.config['clustering_filename'] = f"{filepath}clustering_results_{output_identifier}.pkl"
args.config['hvg_filename'] = f"{filepath}hvg_results_{output_identifier}.pkl"
args.config['coexpression_filename'] = f"{filepath}coexpression_results_{output_identifier}.pkl"
args.config['embedding_filename'] = f"{filepath}embedding_results_{output_identifier}.pkl"
# in case we want a custom output name for our output file
if args.adata_output_name:
args.config['sceodesic_adata_filename'] = args.adata_output_name
else:
args.config['sceodesic_adata_filename'] = f"{filepath}sceodesic_adata_results_{output_identifier}.h5ad"
# run info file output
run_info_file_fname = f"{filepath}run_info_{output_identifier}.yaml"
results_coexp = None
results_embedding = None
# Data preprocessing.
adata = load_input(args.inp_data)
# Flag 1: Clustering
if args.action <= 1:
print("At FLAG 1: clustering")
num_clusters = args.config['num_clusters']
stratify_cols = args.config['stratify_clustering_by_columns']
num_hvg = args.config['num_hvg']
n_init = args.config['n_init']
clustering_filename = args.config['clustering_filename']
clustering_results_dict = _get_cell_cohorts(
adata, num_clusters,
stratify_cols=stratify_cols,
num_hvg=num_hvg,
n_init=n_init,
clustering_filename=clustering_filename,
copy=False, return_results=True
)
# Flag 2: Compute Covariances
if args.action <= 2:
print("At FLAG 2: compute covariances")
# compute hvg
num_hvg = args.config['num_hvg']
do_global_hvg = args.config['do_global_hvg'],
num_hvg_per_cluster = args.config['num_hvg_per_cluster']
hvg_filename = args.config['hvg_filename']
top_genes, top_gene_names = _get_locally_variable_genes(
adata, num_hvg,
num_hvg_per_cluster=num_hvg_per_cluster,
global_hvg=do_global_hvg,
hvg_filename=hvg_filename,
copy=False,
return_results=True,
clustering_results=clustering_results_dict
)
# compute coexpression results
max_condition_number = args.config['max_condition_number']
pvd_pct = args.config['pvd_pct']
coexpression_filename = args.config['coexpression_filename']
results_coexp = _estimate_covariances(
adata, max_condition_number,
pvd_pct=pvd_pct,
coexpression_filename=coexpression_filename,
copy=False,
return_results=True,
top_genes=top_gene_names,
results_clustering=clustering_results_dict
)
# Flag 3: Embeddings/Modules
if args.action <= 3:
print("At FLAG 3: common PCA")
sparse_pca_lambda = args.config['sparse_pca_lambda']
embedding_filename = args.config['embedding_filename']
| #!/usr/bin/env python
## package-specific modules
# Default configuration
DEFAULT_CONFIG = {
'num_clusters': 500,
'num_hvg': 300,
'max_condition_number': 50,
'sparse_pca_lambda': 0.03,
'stratify_clustering_by_columns': 'none',
'filepath': '',
'num_hvg_per_cluster': 100,
'pvd_pct': 0.90,
'do_global_hvg': False,
# for very advanced users
'n_init': 1 # K-Means
}
def main():
args = parse_sceo_command_line_args(DEFAULT_CONFIG)
### TESTING ###
print("config:", args.config)
### TESTING ###
output_identifier = "%s_%d_hvgs_%s_clusters_%g_sparsity" % (args.output_prefix, args.num_hvg,
str(args.config.get('num_clusters')), args.config.get('sparse_pca_lambda'))
args.config['output_identifier'] = output_identifier
filepath = args.config.get('filepath', DEFAULT_CONFIG['filepath']) + '/' #if the backslash is extra, it won't hurt
args.config['clustering_filename'] = f"{filepath}clustering_results_{output_identifier}.pkl"
args.config['hvg_filename'] = f"{filepath}hvg_results_{output_identifier}.pkl"
args.config['coexpression_filename'] = f"{filepath}coexpression_results_{output_identifier}.pkl"
args.config['embedding_filename'] = f"{filepath}embedding_results_{output_identifier}.pkl"
# in case we want a custom output name for our output file
if args.adata_output_name:
args.config['sceodesic_adata_filename'] = args.adata_output_name
else:
args.config['sceodesic_adata_filename'] = f"{filepath}sceodesic_adata_results_{output_identifier}.h5ad"
# run info file output
run_info_file_fname = f"{filepath}run_info_{output_identifier}.yaml"
results_coexp = None
results_embedding = None
# Data preprocessing.
adata = load_input(args.inp_data)
# Flag 1: Clustering
if args.action <= 1:
print("At FLAG 1: clustering")
num_clusters = args.config['num_clusters']
stratify_cols = args.config['stratify_clustering_by_columns']
num_hvg = args.config['num_hvg']
n_init = args.config['n_init']
clustering_filename = args.config['clustering_filename']
clustering_results_dict = _get_cell_cohorts(
adata, num_clusters,
stratify_cols=stratify_cols,
num_hvg=num_hvg,
n_init=n_init,
clustering_filename=clustering_filename,
copy=False, return_results=True
)
# Flag 2: Compute Covariances
if args.action <= 2:
print("At FLAG 2: compute covariances")
# compute hvg
num_hvg = args.config['num_hvg']
do_global_hvg = args.config['do_global_hvg'],
num_hvg_per_cluster = args.config['num_hvg_per_cluster']
hvg_filename = args.config['hvg_filename']
top_genes, top_gene_names = _get_locally_variable_genes(
adata, num_hvg,
num_hvg_per_cluster=num_hvg_per_cluster,
global_hvg=do_global_hvg,
hvg_filename=hvg_filename,
copy=False,
return_results=True,
clustering_results=clustering_results_dict
)
# compute coexpression results
max_condition_number = args.config['max_condition_number']
pvd_pct = args.config['pvd_pct']
coexpression_filename = args.config['coexpression_filename']
results_coexp = _estimate_covariances(
adata, max_condition_number,
pvd_pct=pvd_pct,
coexpression_filename=coexpression_filename,
copy=False,
return_results=True,
top_genes=top_gene_names,
results_clustering=clustering_results_dict
)
# Flag 3: Embeddings/Modules
if args.action <= 3:
print("At FLAG 3: common PCA")
sparse_pca_lambda = args.config['sparse_pca_lambda']
embedding_filename = args.config['embedding_filename'] | results_embedding = _reconstruct_programs( | 7 | 2023-11-10 12:28:33+00:00 | 8k |
iramluism/basel | tests/unit_tests/reports/reports_test.py | [
{
"identifier": "Component",
"path": "basel/components/components.py",
"snippet": "class Component(metaclass=abc.ABCMeta):\n def __init__(\n self,\n name: str,\n nodes: List[Node] = None,\n instability: Optional[float] = 1,\n abstraction: Optional[float] = 1,\n ... | from unittest.mock import Mock
from basel.components import Component
from basel.components import Link
from basel.loaders import Loader
from basel.reports import ASReport
from basel.reports import LinkReport
from basel.reports import Reporter
from basel.reports import ReportFormat
import pytest | 4,401 | (0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_B", 0, 1, 0),
("Component_C", 0.25, 0.5, 0.25),
("Component_D", 0.7, 0, 0.7),
("Component_E", 0, 0, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
None,
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"name": ["match", "Component_A"]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_B", 0, 1, 0),
("Component_C", 0.25, 0.5, 0.25),
("Component_D", 0.7, 0, 0.7),
("Component_E", 0, 0, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"name": ["match in", ["Component_*", "Component_E"]]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_B", 0, 1, 0),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"abstraction": 1},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_D", 0.7, 0, 0.7),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"instability": ["gte", 0.7]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_B", 0, 1, 0),
("Component_C", 0.25, 0.5, 0.25),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"error": ["lte", 0.5]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_C", 0.25, 0.5, 0.25),
("Component_D", 0.7, 0, 0.7),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"instability": ["not eq", 0]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_D", 0.7, 0, 0.7),
("Component_E", 0, 0, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"error": ["gt", 0.5]},
),
],
)
def test_get_as_report(components, means, expected_report, filters):
|
MockComponent = Mock(spec=Component)
MOCK_COMPONENTS_LIST = [
Component(name="Component_A", instability=1, abstraction=1, error=1),
Component(name="Component_B", instability=0, abstraction=1, error=0),
Component(name="Component_C", instability=0.25, abstraction=0.5, error=0.25),
Component(name="Component_D", instability=0.7, abstraction=0, error=0.7),
Component(name="Component_E", instability=0, abstraction=0, error=1),
]
@pytest.mark.parametrize(
"components,means,expected_report,filters",
[
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_B", 0, 1, 0),
("Component_C", 0.25, 0.5, 0.25),
("Component_D", 0.7, 0, 0.7),
("Component_E", 0, 0, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
None,
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"name": ["match", "Component_A"]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_B", 0, 1, 0),
("Component_C", 0.25, 0.5, 0.25),
("Component_D", 0.7, 0, 0.7),
("Component_E", 0, 0, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"name": ["match in", ["Component_*", "Component_E"]]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_B", 0, 1, 0),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"abstraction": 1},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_D", 0.7, 0, 0.7),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"instability": ["gte", 0.7]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_B", 0, 1, 0),
("Component_C", 0.25, 0.5, 0.25),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"error": ["lte", 0.5]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_C", 0.25, 0.5, 0.25),
("Component_D", 0.7, 0, 0.7),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"instability": ["not eq", 0]},
),
(
MOCK_COMPONENTS_LIST,
(0.39, 0.51, 0.59),
ASReport(
columns=["Component", "I", "A", "E"],
data=[
("Component_A", 1, 1, 1),
("Component_D", 0.7, 0, 0.7),
("Component_E", 0, 0, 1),
None,
("Mean", 0.39, 0.51, 0.59),
],
),
{"error": ["gt", 0.5]},
),
],
)
def test_get_as_report(components, means, expected_report, filters): | mock_loader = Mock(spec=Loader) | 2 | 2023-11-18 13:47:55+00:00 | 8k |
KevinXu02/ControlledDreamGaussian | frankmocap/renderer/visualizer.py | [
{
"identifier": "viewer2D",
"path": "frankmocap/renderer/viewer2D.py",
"snippet": "def __ValidateNumpyImg(inputImg):\ndef ImShow(inputImg, waitTime=1, bConvRGB2BGR=False,name='image', scale=1.0):\ndef ImgSC(inputImg, waitTime=1, bConvRGB2BGR=False,name='image', scale=1.0):\ndef Vis_Bbox_minmaxPt(inputIm... | import numpy as np
import cv2
import torch
from frankmocap.renderer import viewer2D#, glViewer, glRenderer
from frankmocap.renderer import glViewer
from frankmocap.renderer import meshRenderer #glRenderer
from frankmocap.mocap_utils.coordconv import convert_smpl_to_bbox, convert_bbox_to_oriIm
from frankmocap.renderer.image_utils import draw_raw_bbox, draw_hand_bbox, draw_body_bbox, draw_arm_pose
from renderer import glViewer #glRenderer | 4,856 | # Copyright (c) Facebook, Inc. and its affiliates.
"""
Visualizing 3D humans via Opengl
- Options:
GUI mode: a screen is required
Scnreenless mode: xvfb-run can be used to avoid screen requirement
"""
class Visualizer(object):
"""
Visualizer to visuzlie SMPL reconstruction output from HMR family (HMR, SPIN, EFT)
Args:
reconstruction output
rawImg, bbox,
smpl_params (shape, pose, cams )
"""
def __init__(
self,
rendererType ='opengl_gui' #nongui or gui
):
self.rendererType = rendererType
if rendererType != "opengl_gui" and rendererType!= "opengl":
print("Wrong rendererType: {rendererType}")
assert False
self.cam_all = []
self.vert_all = []
self.bboxXYXY_all = []
self.bg_image = None
#Screenless rendering
if rendererType =='opengl':
self.renderer = meshRenderer.meshRenderer()
self.renderer.setRenderMode('geo')
self.renderer.offscreenMode(True)
else:
self.renderer = None
#Output rendering
self.renderout = None
# def setSMPLParam(self, smpl_vertices, cam, bbox_xyxy):
# """
# smpl_vertices: (6890,3)
# cam: (3,)
# bbox_xyxy: (3,)
# """
# self.cam_all.append(smpl_vertices)
# self.vert_all.append(cam)
# self.bboxXYXY_all.append(bbox_xyxy)
# def setImg(self, image):
# self.bg_image = image
# def setWindowSize(width_, height_):
# if self.rendererType=="gui":
# glViewer.setWindowSize(width_, height_)
# else:
# assert False
def visualize(self,
input_img,
hand_bbox_list = None,
body_bbox_list = None,
body_pose_list = None,
raw_hand_bboxes = None,
pred_mesh_list = None,
vis_raw_hand_bbox = True,
vis_body_pose = True,
vis_hand_bbox = True,
):
# init
res_img = input_img.copy()
# draw raw hand bboxes
if raw_hand_bboxes is not None and vis_raw_hand_bbox:
| # Copyright (c) Facebook, Inc. and its affiliates.
"""
Visualizing 3D humans via Opengl
- Options:
GUI mode: a screen is required
Scnreenless mode: xvfb-run can be used to avoid screen requirement
"""
class Visualizer(object):
"""
Visualizer to visuzlie SMPL reconstruction output from HMR family (HMR, SPIN, EFT)
Args:
reconstruction output
rawImg, bbox,
smpl_params (shape, pose, cams )
"""
def __init__(
self,
rendererType ='opengl_gui' #nongui or gui
):
self.rendererType = rendererType
if rendererType != "opengl_gui" and rendererType!= "opengl":
print("Wrong rendererType: {rendererType}")
assert False
self.cam_all = []
self.vert_all = []
self.bboxXYXY_all = []
self.bg_image = None
#Screenless rendering
if rendererType =='opengl':
self.renderer = meshRenderer.meshRenderer()
self.renderer.setRenderMode('geo')
self.renderer.offscreenMode(True)
else:
self.renderer = None
#Output rendering
self.renderout = None
# def setSMPLParam(self, smpl_vertices, cam, bbox_xyxy):
# """
# smpl_vertices: (6890,3)
# cam: (3,)
# bbox_xyxy: (3,)
# """
# self.cam_all.append(smpl_vertices)
# self.vert_all.append(cam)
# self.bboxXYXY_all.append(bbox_xyxy)
# def setImg(self, image):
# self.bg_image = image
# def setWindowSize(width_, height_):
# if self.rendererType=="gui":
# glViewer.setWindowSize(width_, height_)
# else:
# assert False
def visualize(self,
input_img,
hand_bbox_list = None,
body_bbox_list = None,
body_pose_list = None,
raw_hand_bboxes = None,
pred_mesh_list = None,
vis_raw_hand_bbox = True,
vis_body_pose = True,
vis_hand_bbox = True,
):
# init
res_img = input_img.copy()
# draw raw hand bboxes
if raw_hand_bboxes is not None and vis_raw_hand_bbox: | res_img = draw_raw_bbox(input_img, raw_hand_bboxes) | 5 | 2023-11-17 05:21:26+00:00 | 8k |
dazhangyu123/OCL | train_source.py | [
{
"identifier": "Eval",
"path": "utils/eval.py",
"snippet": "class Eval():\n def __init__(self, num_class):\n self.num_class = num_class\n self.confusion_matrix = np.zeros((self.num_class,)*2)\n self.ignore_index = None\n self.synthia = True if num_class == 16 else False\n... | import os
import random
import logging
import argparse
import torch
import torch.nn as nn
import torch.utils.data as data
import torch.nn.functional as F
import numpy as np
import sys
import shutil
from tqdm import tqdm
from math import ceil
from distutils.version import LooseVersion
from tensorboardX import SummaryWriter
from torchvision.utils import make_grid
from utils.eval import Eval
from utils.train_helper import get_model
from datasets.cityscapes_Dataset import City_Dataset, City_DataLoader, inv_preprocess, decode_labels
from datasets.gta5_Dataset import GTA5_DataLoader
from datasets.synthia_Dataset import SYNTHIA_DataLoader | 7,139 |
sys.path.append(os.path.abspath('tools'))
datasets_path={
'cityscapes': {'data_root_path': '/mnt/Xsky/zyl/dataset/dataset/Cityscapes', 'list_path': './datasets/city_list',
'image_path':'/mnt/Xsky/zyl/dataset/Cityscapes/leftImg8bit',
'gt_path': './datasets/Cityscapes/gtFine'},
'gta5': {'data_root_path': '/mnt/Xsky/zyl/dataset/GTA5', 'list_path': './datasets/gta5_list',
'image_path':'/mnt/Xsky/zyl/dataset/GTA5/images',
'gt_path': './datasets/GTA5/labels'},
'synthia': {'data_root_path': '/mnt/Xsky/zyl/dataset/RAND_CITYSCAPES', 'list_path': './datasets/synthia_list',
'image_path':'/mnt/Xsky/zyl/dataset/RAND_CITYSCAPES/RGB',
'gt_path': './datasets/SYNTHIA/GT/LABELS'},
'NTHU': {'data_root_path': './datasets/NTHU_Datasets', 'list_path': './datasets/NTHU_list'}
}
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Unsupported value encountered.')
ITER_MAX = 5000
class Trainer():
def __init__(self, args, cuda=None, train_id="None", logger=None):
self.args = args
os.environ["CUDA_VISIBLE_DEVICES"] = self.args.gpu
self.cuda = cuda and torch.cuda.is_available()
self.device = torch.device('cuda' if self.cuda else 'cpu')
self.train_id = train_id
self.logger = logger
self.current_MIoU = 0
self.best_MIou = 0
self.best_source_MIou = 0
self.current_epoch = 0
self.current_iter = 0
self.second_best_MIou = 0
# set TensorboardX
self.writer = SummaryWriter(self.args.checkpoint_dir)
# Metric definition
self.Eval = Eval(self.args.num_classes)
# loss definition
self.loss = nn.CrossEntropyLoss(weight=None, ignore_index= -1)
self.loss.to(self.device)
# model
self.model, params = get_model(self.args)
self.model = nn.DataParallel(self.model, device_ids=[0])
self.model.to(self.device)
if self.args.optim == "SGD":
self.optimizer = torch.optim.SGD(
params=params,
momentum=self.args.momentum,
weight_decay=self.args.weight_decay
)
elif self.args.optim == "Adam":
self.optimizer = torch.optim.Adam(params, betas=(0.9, 0.99), weight_decay=self.args.weight_decay)
# dataloader
if self.args.dataset=="cityscapes":
|
sys.path.append(os.path.abspath('tools'))
datasets_path={
'cityscapes': {'data_root_path': '/mnt/Xsky/zyl/dataset/dataset/Cityscapes', 'list_path': './datasets/city_list',
'image_path':'/mnt/Xsky/zyl/dataset/Cityscapes/leftImg8bit',
'gt_path': './datasets/Cityscapes/gtFine'},
'gta5': {'data_root_path': '/mnt/Xsky/zyl/dataset/GTA5', 'list_path': './datasets/gta5_list',
'image_path':'/mnt/Xsky/zyl/dataset/GTA5/images',
'gt_path': './datasets/GTA5/labels'},
'synthia': {'data_root_path': '/mnt/Xsky/zyl/dataset/RAND_CITYSCAPES', 'list_path': './datasets/synthia_list',
'image_path':'/mnt/Xsky/zyl/dataset/RAND_CITYSCAPES/RGB',
'gt_path': './datasets/SYNTHIA/GT/LABELS'},
'NTHU': {'data_root_path': './datasets/NTHU_Datasets', 'list_path': './datasets/NTHU_list'}
}
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Unsupported value encountered.')
ITER_MAX = 5000
class Trainer():
def __init__(self, args, cuda=None, train_id="None", logger=None):
self.args = args
os.environ["CUDA_VISIBLE_DEVICES"] = self.args.gpu
self.cuda = cuda and torch.cuda.is_available()
self.device = torch.device('cuda' if self.cuda else 'cpu')
self.train_id = train_id
self.logger = logger
self.current_MIoU = 0
self.best_MIou = 0
self.best_source_MIou = 0
self.current_epoch = 0
self.current_iter = 0
self.second_best_MIou = 0
# set TensorboardX
self.writer = SummaryWriter(self.args.checkpoint_dir)
# Metric definition
self.Eval = Eval(self.args.num_classes)
# loss definition
self.loss = nn.CrossEntropyLoss(weight=None, ignore_index= -1)
self.loss.to(self.device)
# model
self.model, params = get_model(self.args)
self.model = nn.DataParallel(self.model, device_ids=[0])
self.model.to(self.device)
if self.args.optim == "SGD":
self.optimizer = torch.optim.SGD(
params=params,
momentum=self.args.momentum,
weight_decay=self.args.weight_decay
)
elif self.args.optim == "Adam":
self.optimizer = torch.optim.Adam(params, betas=(0.9, 0.99), weight_decay=self.args.weight_decay)
# dataloader
if self.args.dataset=="cityscapes": | self.dataloader = City_DataLoader(self.args) | 3 | 2023-11-14 02:01:11+00:00 | 8k |
zhuhanqing/Lightening-Transformer-AE | software_model/ops/quantize.py | [
{
"identifier": "_Conv2dQ",
"path": "software_model/ops/_quant_base.py",
"snippet": "class _Conv2dQ(nn.Conv2d):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1,\n padding=0, dilation=1, groups=1, bias=True, **kwargs_q):\n super(_Conv2dQ, self).__init__(in_... | import torch
import torch.nn.functional as F
import math
import numpy as np
from ._quant_base import _Conv2dQ, Qmodes, _LinearQ, _ActQ
from .simulator import cal_coupler_wdm_error_list | 4,536 | self.phase_noise_std = phase_noise_std if self.enable_linear_noise else 0
self.kappa_noise = None if not (enable_wdm_noise and enable_linear_noise) else cal_coupler_wdm_error_list(
num_wavelength=num_wavelength, channel_spacing=channel_spacing)
self.num_wavelength = num_wavelength
self.out_features = out_features
self.in_features = in_features
if self.kappa_noise is not None:
self.kappa_noise_term = torch.tensor(self.kappa_noise).unsqueeze(0).expand((in_features // self.num_wavelength) + 1, -1).reshape(-1).contiguous()[:in_features]
else:
self.kappa_noise_term = None
self.act = QuantAct(in_features=in_features, nbits=nbits_a,
mode=Qmodes.layer_wise, offset=offset, input_noise_std=self.input_noise_std)
def add_input_noise(self, x):
# the noise std is 2sigma not 1sigma, so should be devided by 2
if self.input_noise_std > 1e-5:
# add mul noise here
noise = torch.randn_like(x).mul(
(self.input_noise_std)).mul(x.data.abs())
x = x + noise
return x
def add_output_noise(self, x):
# the noise std is 2sigma not 1sigma, so should be devided by 2
if self.output_noise_std > 1e-5:
noise = torch.randn_like(x).mul(
(self.output_noise_std)).mul(x.data.abs())
x = x + noise
return x
def add_phase_noise(self, x, noise_std=2):
# the noise std is 2sigma not 1sigma, so should be devided by 2
# DATE O2NN use 0.04 -> 0.04 * 360 / 2pi = 2.29
if noise_std > 1e-5:
noise = (torch.randn_like(x).mul_((noise_std) / 180 * np.pi)).cos_()
x = x * noise
return x
def forward(self, x):
kappa_noise_scale_factor = 2
if self.alpha is None:
return F.linear(x, self.weight, self.bias)
Qn = -2 ** (self.nbits - 1)
Qp = 2 ** (self.nbits - 1) - 1
if self.init_state == 0:
print(
f"Linear layer (mode: {self.q_mode}): initialize weight scale for int{self.nbits} quantization")
self.alpha.data.copy_(2 * self.weight.abs().mean() / math.sqrt(Qp))
self.init_state.fill_(1)
# lsq+ init
# m, v = self.weight.abs().mean(), self.weight.abs().std()
# self.alpha.data.copy_(torch.max(torch.abs(m - 3*v), torch.abs(m + 3*v)) / 2 ** (self.nbits - 1) )
assert self.init_state == 1
with torch.no_grad():
g = 1.0 / math.sqrt(self.weight.numel() * Qp)
# g = 1.0 / math.sqrt(self.weight.numel()) / Qp
# g = 1.0 / math.sqrt(self.weight.numel()) / 4
self.alpha.data.clamp_(min=1e-4)
# Method1:
alpha = grad_scale(self.alpha, g)
# w_q = round_pass((self.weight / alpha).clamp(Qn, Qp)) * alpha
# w_q = clamp(round_pass(self.weight / alpha), Qn, Qp) * alpha
w_q = round_pass((self.weight / alpha).clamp(Qn, Qp)) * alpha
# Method2:
# w_q = FunLSQ.apply(self.weight, self.alpha, g, Qn, Qp)
x = self.act(x)
# add noise @ w_q
if self.enable_linear_noise and self.input_noise_std > 1e-5:
w_q = self.add_input_noise(w_q)
if not self.training and self.phase_noise_std > 1e-5 and self.enable_linear_noise:
noise_w_q_2 = 0
noise_x_2 = 0
if self.kappa_noise is not None:
if self.kappa_noise_term.device != x.device:
self.kappa_noise_term = self.kappa_noise_term.to(x.device)
# obtain the scaling number
alpha_x_to_w = self.act.alpha / alpha
noise_x_2 = torch.matmul(x.square(), self.kappa_noise_term.unsqueeze(-1)) /(alpha_x_to_w * kappa_noise_scale_factor) # [bs, seq, 1]
noise_w_q_2 = torch.matmul(w_q.square(), -self.kappa_noise_term.unsqueeze(-1))* (alpha_x_to_w / kappa_noise_scale_factor) # [output_features, 1]
dim_3_flag = False
if x.dim() == 3:
dim_3_flag = True
bs, N, D = x.shape
bs = bs * N
x = x.reshape(-1, D)
else:
bs, D = x.shape
out = []
k = 2
num_chunks = self.out_features//k
for i in range(k):
if self.out_features%k != 0: raise RuntimeError
noisy_x = self.add_phase_noise(x.unsqueeze(-2).expand(-1, num_chunks, -1))
out.append(torch.einsum('ibk, bk->ib', noisy_x, w_q[i * num_chunks: (i+1) * num_chunks, :]))
out = torch.cat(out, 1)
if self.bias is not None:
out += self.bias
if dim_3_flag:
out = out.reshape(-1, N, self.out_features)
out = out + (noise_x_2 + noise_w_q_2.squeeze(-1)) # add [bs, seq, 1] and [1, output_features]
else:
out = F.linear(x, w_q, self.bias)
# add output noise
if self.enable_linear_noise and self.output_noise_std > 1e-5:
out = self.add_output_noise(out)
return out
| # -*- coding: utf-8 -*-
# @Author: Hanqing Zhu
# @Date: 2023-01-02 21:11:56
# @Last Modified by: Hanqing Zhu(hqzhu@utexas.edu)
# @Last Modified time: 2023-11-09 21:57:41
"""
@inproceedings{
esser2020learned,
title={LEARNED STEP SIZE QUANTIZATION},
author={Steven K. Esser and Jeffrey L. McKinstry and Deepika Bablani and Rathinakumar Appuswamy and Dharmendra S. Modha},
booktitle={International Conference on Learning Representations},
year={2020},
url={https://openreview.net/forum?id=rkgO66VKDS}
}
https://quanoview.readthedocs.io/en/latest/_raw/LSQ.html
"""
__all__ = ["QuantLinear", "QuantAct", "QuantConv2d"]
class FunLSQ(torch.autograd.Function):
@staticmethod
def forward(ctx, weight, alpha, g, Qn, Qp):
assert alpha > 0, 'alpha = {}'.format(alpha)
ctx.save_for_backward(weight, alpha)
ctx.other = g, Qn, Qp
q_w = (weight / alpha).round().clamp(Qn, Qp)
w_q = q_w * alpha
return w_q
@staticmethod
def backward(ctx, grad_weight):
weight, alpha = ctx.saved_tensors
g, Qn, Qp = ctx.other
q_w = weight / alpha
indicate_small = (q_w < Qn).float()
indicate_big = (q_w > Qp).float()
# indicate_middle = torch.ones(indicate_small.shape).to(indicate_small.device) - indicate_small - indicate_big
indicate_middle = 1.0 - indicate_small - indicate_big # Thanks to @haolibai
grad_alpha = ((indicate_small * Qn + indicate_big * Qp + indicate_middle *
(-q_w + q_w.round())) * grad_weight * g).sum().unsqueeze(dim=0)
# grad_alpha = ((indicate_small * Qn + indicate_big * Qp + indicate_middle * 0) * grad_weight * g).sum().unsqueeze(dim=0)
grad_weight = indicate_middle * grad_weight
return grad_weight, grad_alpha, None, None, None
def grad_scale(x, scale):
y = x
y_grad = x * scale
return y.detach() - y_grad.detach() + y_grad
def round_pass(x):
y = x.round()
y_grad = x
return y.detach() - y_grad.detach() + y_grad
def clamp(x, minv, maxv):
print(minv.dtype)
x = torch.minimum(x, maxv)
x = torch.maximum(x, minv)
return x
class QuantConv2d(_Conv2dQ):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, nbits=-1, nbits_a=-1, mode=Qmodes.layer_wise, offset=False,
input_noise_std=0, output_noise_std=0, phase_noise_std=0, enable_wdm_noise=False,
num_wavelength=9, channel_spacing=0.4, enable_linear_noise=False, **kwargs):
super(QuantConv2d, self).__init__(
in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias,
nbits=nbits, mode=mode,)
self.enable_linear_noise = enable_linear_noise
self.input_noise_std = input_noise_std if self.enable_linear_noise else 0
self.output_noise_std = output_noise_std if self.enable_linear_noise else 0
self.act = QuantAct(in_features=in_channels, nbits=nbits_a,
mode=Qmodes.layer_wise, offset=offset, input_noise_std=self.input_noise_std)
def add_output_noise(self, x):
# the noise std is 2sigma not 1sigma, so should be devided by 2
if self.output_noise_std > 1e-5:
noise = torch.randn_like(x).mul(
(self.output_noise_std)).mul(x.data.abs())
x = x + noise
return x
def add_input_noise(self, x):
# the noise std is 2sigma not 1sigma, so should be devided by 2
if self.input_noise_std > 1e-5:
noise = torch.randn_like(x).mul(
(self.input_noise_std)).mul(x.data.abs())
x = x + noise
return x
def forward(self, x):
if self.alpha is None:
return F.conv2d(x, self.weight, self.bias, self.stride,
self.padding, self.dilation, self.groups)
# full range quantization -> -2**(k-1) -> 2**(k-1)-1
Qn = -2 ** (self.nbits - 1)
Qp = 2 ** (self.nbits - 1) - 1
if self.init_state == 0:
print(
f"Conv layer (mode: {self.q_mode}): initialize weight scale for int{self.nbits} quantization")
self.alpha.data.copy_(2 * self.weight.abs().mean() / math.sqrt(Qp))
# self.alpha.data.copy_(quantize_by_mse(self.weight, Qn, Qp))
self.init_state.fill_(1)
with torch.no_grad():
g = 1.0 / math.sqrt(self.weight.numel() * Qp)
self.alpha.data.clamp_(min=1e-4)
# Method1: 31GB GPU memory (AlexNet w4a4 bs 2048) 17min/epoch
alpha = grad_scale(self.alpha, g)
w_q = round_pass((self.weight / alpha).clamp(Qn, Qp)) * alpha
# Method2: 25GB GPU memory (AlexNet w4a4 bs 2048) 32min/epoch
# w_q = FunLSQ.apply(self.weight, self.alpha, g, Qn, Qp)
x = self.act(x)
# add noise at w_q
if self.enable_linear_noise and self.input_noise_std > 1e-5:
w_q = self.add_input_noise(w_q)
out = F.conv2d(x, w_q, self.bias, self.stride,
self.padding, self.dilation, self.groups)
if self.enable_linear_noise and self.output_noise_std > 1e-5:
out = self.add_output_noise(out)
return out
class QuantLinear(_LinearQ):
def __init__(self, in_features, out_features, bias=True, nbits=-1, nbits_a=-1, mode=Qmodes.layer_wise, offset=False,
input_noise_std=0, output_noise_std=0, phase_noise_std=0, enable_wdm_noise=False,
num_wavelength=9, channel_spacing=0.4, enable_linear_noise=False, **kwargs):
super(QuantLinear, self).__init__(in_features=in_features, out_features=out_features, bias=bias,
nbits=nbits, mode=mode)
print(
f"Linear layer (mode: {self.q_mode}): initialize weight scale for int{self.nbits} quantization")
self.enable_linear_noise = enable_linear_noise
self.input_noise_std = input_noise_std if self.enable_linear_noise else 0
self.output_noise_std = output_noise_std if self.enable_linear_noise else 0
self.phase_noise_std = phase_noise_std if self.enable_linear_noise else 0
self.kappa_noise = None if not (enable_wdm_noise and enable_linear_noise) else cal_coupler_wdm_error_list(
num_wavelength=num_wavelength, channel_spacing=channel_spacing)
self.num_wavelength = num_wavelength
self.out_features = out_features
self.in_features = in_features
if self.kappa_noise is not None:
self.kappa_noise_term = torch.tensor(self.kappa_noise).unsqueeze(0).expand((in_features // self.num_wavelength) + 1, -1).reshape(-1).contiguous()[:in_features]
else:
self.kappa_noise_term = None
self.act = QuantAct(in_features=in_features, nbits=nbits_a,
mode=Qmodes.layer_wise, offset=offset, input_noise_std=self.input_noise_std)
def add_input_noise(self, x):
# the noise std is 2sigma not 1sigma, so should be devided by 2
if self.input_noise_std > 1e-5:
# add mul noise here
noise = torch.randn_like(x).mul(
(self.input_noise_std)).mul(x.data.abs())
x = x + noise
return x
def add_output_noise(self, x):
# the noise std is 2sigma not 1sigma, so should be devided by 2
if self.output_noise_std > 1e-5:
noise = torch.randn_like(x).mul(
(self.output_noise_std)).mul(x.data.abs())
x = x + noise
return x
def add_phase_noise(self, x, noise_std=2):
# the noise std is 2sigma not 1sigma, so should be devided by 2
# DATE O2NN use 0.04 -> 0.04 * 360 / 2pi = 2.29
if noise_std > 1e-5:
noise = (torch.randn_like(x).mul_((noise_std) / 180 * np.pi)).cos_()
x = x * noise
return x
def forward(self, x):
kappa_noise_scale_factor = 2
if self.alpha is None:
return F.linear(x, self.weight, self.bias)
Qn = -2 ** (self.nbits - 1)
Qp = 2 ** (self.nbits - 1) - 1
if self.init_state == 0:
print(
f"Linear layer (mode: {self.q_mode}): initialize weight scale for int{self.nbits} quantization")
self.alpha.data.copy_(2 * self.weight.abs().mean() / math.sqrt(Qp))
self.init_state.fill_(1)
# lsq+ init
# m, v = self.weight.abs().mean(), self.weight.abs().std()
# self.alpha.data.copy_(torch.max(torch.abs(m - 3*v), torch.abs(m + 3*v)) / 2 ** (self.nbits - 1) )
assert self.init_state == 1
with torch.no_grad():
g = 1.0 / math.sqrt(self.weight.numel() * Qp)
# g = 1.0 / math.sqrt(self.weight.numel()) / Qp
# g = 1.0 / math.sqrt(self.weight.numel()) / 4
self.alpha.data.clamp_(min=1e-4)
# Method1:
alpha = grad_scale(self.alpha, g)
# w_q = round_pass((self.weight / alpha).clamp(Qn, Qp)) * alpha
# w_q = clamp(round_pass(self.weight / alpha), Qn, Qp) * alpha
w_q = round_pass((self.weight / alpha).clamp(Qn, Qp)) * alpha
# Method2:
# w_q = FunLSQ.apply(self.weight, self.alpha, g, Qn, Qp)
x = self.act(x)
# add noise @ w_q
if self.enable_linear_noise and self.input_noise_std > 1e-5:
w_q = self.add_input_noise(w_q)
if not self.training and self.phase_noise_std > 1e-5 and self.enable_linear_noise:
noise_w_q_2 = 0
noise_x_2 = 0
if self.kappa_noise is not None:
if self.kappa_noise_term.device != x.device:
self.kappa_noise_term = self.kappa_noise_term.to(x.device)
# obtain the scaling number
alpha_x_to_w = self.act.alpha / alpha
noise_x_2 = torch.matmul(x.square(), self.kappa_noise_term.unsqueeze(-1)) /(alpha_x_to_w * kappa_noise_scale_factor) # [bs, seq, 1]
noise_w_q_2 = torch.matmul(w_q.square(), -self.kappa_noise_term.unsqueeze(-1))* (alpha_x_to_w / kappa_noise_scale_factor) # [output_features, 1]
dim_3_flag = False
if x.dim() == 3:
dim_3_flag = True
bs, N, D = x.shape
bs = bs * N
x = x.reshape(-1, D)
else:
bs, D = x.shape
out = []
k = 2
num_chunks = self.out_features//k
for i in range(k):
if self.out_features%k != 0: raise RuntimeError
noisy_x = self.add_phase_noise(x.unsqueeze(-2).expand(-1, num_chunks, -1))
out.append(torch.einsum('ibk, bk->ib', noisy_x, w_q[i * num_chunks: (i+1) * num_chunks, :]))
out = torch.cat(out, 1)
if self.bias is not None:
out += self.bias
if dim_3_flag:
out = out.reshape(-1, N, self.out_features)
out = out + (noise_x_2 + noise_w_q_2.squeeze(-1)) # add [bs, seq, 1] and [1, output_features]
else:
out = F.linear(x, w_q, self.bias)
# add output noise
if self.enable_linear_noise and self.output_noise_std > 1e-5:
out = self.add_output_noise(out)
return out
| class QuantAct(_ActQ): | 3 | 2023-11-14 05:55:48+00:00 | 8k |
davidhozic/TkClassWizard | tkclasswiz/object_frame/frame_struct.py | [
{
"identifier": "Messagebox",
"path": "tkclasswiz/messagebox.py",
"snippet": "class Messagebox:\r\n \"\"\"\r\n Wrapper for some of Messagebox methods, that offers compatibility between\r\n ttk and ttkbootstrap.\r\n \"\"\"\r\n def _process_kwargs(kwargs):\r\n if \"master\" in kwargs... | from typing import get_args, get_origin, Iterable, Union, Literal, Dict, Tuple
from collections.abc import Iterable as ABCIterable
from functools import partial
from enum import Enum
from ..convert import *
from ..dpi import *
from ..utilities import *
from ..storage import *
from ..messagebox import Messagebox
from ..extensions import extendable
from ..annotations import get_annotations
from ..doc import doc_category
from .frame_base import *
from .tooltip import ComboboxTooltip
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog as tkfile
import inspect
import copy
import json
| 3,656 |
def __init__(
self,
class_,
return_widget: Union[ComboBoxObjects, ListBoxScrolled],
parent = None,
old_data: ObjectInfo = None,
check_parameters: bool = True,
allow_save = True,
additional_values: dict = {},
_annotations_override: dict = None,
):
super().__init__(class_, return_widget, parent, old_data, check_parameters,allow_save)
self._map: Dict[str, Tuple[ComboBoxObjects, Iterable[type]]] = {}
dpi_5 = dpi_scaled(5)
dpi_5_h = dpi_5 // 2
if not (annotations := _annotations_override or get_annotations(class_)):
raise TypeError("This object cannot be edited.")
# Template
@gui_except(window=self)
def save_template():
filename = tkfile.asksaveasfilename(filetypes=[("JSON", "*.json")], parent=self)
if filename == "":
return
json_data = convert_to_dict(self.to_object(ignore_checks=True))
if not filename.endswith(".json"):
filename += ".json"
with open(filename, "w", encoding="utf-8") as file:
json.dump(json_data, file, indent=2)
Messagebox.show_info("Finished", f"Saved to {filename}", parent=self)
@gui_except(window=self)
def load_template():
filename = tkfile.askopenfilename(filetypes=[("JSON", "*.json")], parent=self)
if filename == "":
return
with open(filename, "r", encoding="utf-8") as file:
json_data: dict = json.loads(file.read())
object_info = convert_from_dict(json_data)
# Get class_ attribute if we have the ObjectInfo type, if not just compare the actual type
if object_info.class_ is not self.class_:
raise TypeError(
f"The selected template is not a {self.class_.__name__} template.\n"
f"The requested template is for type: {object_info.class_.__name__}!"
)
self.load(object_info)
bnt_menu_template = ttk.Menubutton(self.frame_toolbar, text="Template")
menu = tk.Menu(bnt_menu_template)
menu.add_command(label="Load template", command=load_template)
menu.add_command(label="Save template", command=save_template)
bnt_menu_template.configure(menu=menu)
bnt_menu_template.pack(side="left")
# Nickname entry
self.entry_nick = HintedEntry(
"Object nickname",
self.frame_main,
state="normal" if self.allow_save else "disabled"
)
self.entry_nick.pack(anchor=tk.W, padx=dpi_5_h, pady=dpi_5)
def fill_values(k: str, entry_types: list, menu: tk.Menu, combo: ComboBoxObjects):
"Fill ComboBox values based on types in ``entry_types`` and create New <object_type> buttons"
any_filled = False
for entry_type in entry_types:
if get_origin(entry_type) is Literal:
values = get_args(entry_type)
combo["values"] = values
# tkvalid.add_option_validation(combo, values)
elif entry_type is bool:
combo.insert(tk.END, True)
combo.insert(tk.END, False)
# tkvalid.add_option_validation(combo, ["True", "False", ''])
elif issubclass_noexcept(entry_type, Enum):
combo["values"] = values = [en for en in entry_type]
# tkvalid.add_option_validation(combo, list(map(str, values)) + [''])
elif entry_type is type(None):
if bool not in entry_types:
combo.insert(tk.END, None)
else: # Type not supported, try other types
any_filled = True
if self.allow_save:
menu.add_command(
label=f"New {self.get_cls_name(entry_type)}",
command=partial(self.new_object_frame, entry_type, combo)
)
# Additional values to be inserted into ComboBox
for value in additional_values.get(k, []):
combo.insert(tk.END, value)
# The class of last list like type. Needed when "Edit selected" is used
# since we don't know what type it was
return any_filled
max_attr_name_len = max(*map(len, annotations), 15) - 2
for (k, v) in annotations.items():
# Init widgets
entry_types = self.convert_types(v)
frame_annotated = ttk.Frame(self.frame_main)
frame_annotated.pack(fill=tk.BOTH, expand=True, pady=dpi_5)
ttk.Label(frame_annotated, text=k, width=max_attr_name_len).pack(side="left")
bnt_new_menu = ttk.Menubutton(frame_annotated, text="New")
menu_new = tk.Menu(bnt_new_menu)
bnt_new_menu.configure(menu=menu_new)
# Storage widget with the tooltip for displaying
# nicknames on ObjectInfo instances
w = combo = ComboBoxObjects(frame_annotated)
|
__all__ = (
"NewObjectFrameStruct",
"NewObjectFrameStructView",
)
@extendable
@doc_category("Object frames")
class NewObjectFrameStruct(NewObjectFrameBase):
"""
Frame for inside the :class:`ObjectEditWindow` that allows object definition.
Parameters
-------------
class_: Any
The class we are defining for.
return_widget: ComboBoxObjects | ListBoxScrolled
The widget to insert the ObjectInfo into after saving.
parent: TopLevel
The parent window.
old_data: ObjectInfo
The old_data ObjectInfo object to edit.
check_parameters: bool
Check parameters (by creating the real object) upon saving.
This is ignored if editing a function instead of a class.
allow_save: bool
If False, will open in read-only mode.
additional_values: Dict[str, Any]
A mapping of additional values to be inserted into corresponding field.
"""
def __new__(cls, *args, **kwargs):
if kwargs.get("allow_save", True):
obj = super().__new__(NewObjectFrameStruct)
else:
obj = super().__new__(NewObjectFrameStructView)
return obj
def __init__(
self,
class_,
return_widget: Union[ComboBoxObjects, ListBoxScrolled],
parent = None,
old_data: ObjectInfo = None,
check_parameters: bool = True,
allow_save = True,
additional_values: dict = {},
_annotations_override: dict = None,
):
super().__init__(class_, return_widget, parent, old_data, check_parameters,allow_save)
self._map: Dict[str, Tuple[ComboBoxObjects, Iterable[type]]] = {}
dpi_5 = dpi_scaled(5)
dpi_5_h = dpi_5 // 2
if not (annotations := _annotations_override or get_annotations(class_)):
raise TypeError("This object cannot be edited.")
# Template
@gui_except(window=self)
def save_template():
filename = tkfile.asksaveasfilename(filetypes=[("JSON", "*.json")], parent=self)
if filename == "":
return
json_data = convert_to_dict(self.to_object(ignore_checks=True))
if not filename.endswith(".json"):
filename += ".json"
with open(filename, "w", encoding="utf-8") as file:
json.dump(json_data, file, indent=2)
Messagebox.show_info("Finished", f"Saved to {filename}", parent=self)
@gui_except(window=self)
def load_template():
filename = tkfile.askopenfilename(filetypes=[("JSON", "*.json")], parent=self)
if filename == "":
return
with open(filename, "r", encoding="utf-8") as file:
json_data: dict = json.loads(file.read())
object_info = convert_from_dict(json_data)
# Get class_ attribute if we have the ObjectInfo type, if not just compare the actual type
if object_info.class_ is not self.class_:
raise TypeError(
f"The selected template is not a {self.class_.__name__} template.\n"
f"The requested template is for type: {object_info.class_.__name__}!"
)
self.load(object_info)
bnt_menu_template = ttk.Menubutton(self.frame_toolbar, text="Template")
menu = tk.Menu(bnt_menu_template)
menu.add_command(label="Load template", command=load_template)
menu.add_command(label="Save template", command=save_template)
bnt_menu_template.configure(menu=menu)
bnt_menu_template.pack(side="left")
# Nickname entry
self.entry_nick = HintedEntry(
"Object nickname",
self.frame_main,
state="normal" if self.allow_save else "disabled"
)
self.entry_nick.pack(anchor=tk.W, padx=dpi_5_h, pady=dpi_5)
def fill_values(k: str, entry_types: list, menu: tk.Menu, combo: ComboBoxObjects):
"Fill ComboBox values based on types in ``entry_types`` and create New <object_type> buttons"
any_filled = False
for entry_type in entry_types:
if get_origin(entry_type) is Literal:
values = get_args(entry_type)
combo["values"] = values
# tkvalid.add_option_validation(combo, values)
elif entry_type is bool:
combo.insert(tk.END, True)
combo.insert(tk.END, False)
# tkvalid.add_option_validation(combo, ["True", "False", ''])
elif issubclass_noexcept(entry_type, Enum):
combo["values"] = values = [en for en in entry_type]
# tkvalid.add_option_validation(combo, list(map(str, values)) + [''])
elif entry_type is type(None):
if bool not in entry_types:
combo.insert(tk.END, None)
else: # Type not supported, try other types
any_filled = True
if self.allow_save:
menu.add_command(
label=f"New {self.get_cls_name(entry_type)}",
command=partial(self.new_object_frame, entry_type, combo)
)
# Additional values to be inserted into ComboBox
for value in additional_values.get(k, []):
combo.insert(tk.END, value)
# The class of last list like type. Needed when "Edit selected" is used
# since we don't know what type it was
return any_filled
max_attr_name_len = max(*map(len, annotations), 15) - 2
for (k, v) in annotations.items():
# Init widgets
entry_types = self.convert_types(v)
frame_annotated = ttk.Frame(self.frame_main)
frame_annotated.pack(fill=tk.BOTH, expand=True, pady=dpi_5)
ttk.Label(frame_annotated, text=k, width=max_attr_name_len).pack(side="left")
bnt_new_menu = ttk.Menubutton(frame_annotated, text="New")
menu_new = tk.Menu(bnt_new_menu)
bnt_new_menu.configure(menu=menu_new)
# Storage widget with the tooltip for displaying
# nicknames on ObjectInfo instances
w = combo = ComboBoxObjects(frame_annotated)
| ComboboxTooltip(w)
| 4 | 2023-11-14 09:26:01+00:00 | 8k |
raphaelreme/koft | src/simulator/simulator.py | [
{
"identifier": "GlobalDriftAndRotation",
"path": "src/simulator/motion.py",
"snippet": "class GlobalDriftAndRotation:\n \"\"\"Global drift and rotation for all particles (Rigid motion)\n\n Note: With the current bad implementation, i'm not able to make this fit with other motions.\n Lets not m... | import dataclasses
import cv2
import numpy as np
import torch
import byotrack
from typing import Optional
from .motion import GlobalDriftAndRotation, GlobalMotionConfig, MotionConfig, MultipleMotion
from .particle import GaussianParticles, GaussianParticlesConfig
from .nam import NeuronalActivityModel, NamConfig | 4,598 |
@dataclasses.dataclass
class ImagingConfig:
dt: float = 100.0
snr: float = 1.5
noise: float = 0.1
@dataclasses.dataclass
class VideoConfig:
path: str = ""
start: int = 0
stop: int = -1
step: int = 1
transform: byotrack.VideoTransformConfig = byotrack.VideoTransformConfig()
def open(self) -> Optional[byotrack.Video]:
if self.path == "":
return None
video = byotrack.Video(self.path)[slice(self.start, self.stop, self.step)]
video.set_transform(self.transform)
return video
@dataclasses.dataclass
class SimulatorConfig:
base_video: VideoConfig
imaging_config: ImagingConfig
particle: GaussianParticlesConfig
background: GaussianParticlesConfig
nam: NamConfig
motion: MotionConfig
global_motion: GlobalMotionConfig
warm_up: int = 500
def random_mask(size=1024, verbose=False) -> torch.Tensor:
"""Generate a random ellipse mask roughly centered in the middle"""
thresh = 1 / np.sqrt(2 * torch.pi) ** 2 * np.exp(-1 / 2) # Thresh at 1 sigma (1 mahalanohobis)
mask_area = torch.rand(1).item() * 0.15 + 0.2 # [0.2, 0.35]
ratio = 0.5 + 1.5 * torch.rand(1).item() # [0.5, 2]
mean = size / 2 + torch.randn(2) * size / 60
std = torch.tensor([mask_area * ratio / torch.pi, mask_area / ratio / torch.pi]).sqrt() * size
distribution = torch.distributions.Normal(mean, std)
indices = torch.tensor(np.indices((size, size)), dtype=torch.float32).permute(1, 2, 0)
prob = distribution.log_prob(indices).sum(dim=2).exp() * std.prod()
mask = prob > thresh
if verbose:
print(mask.sum() / mask.numel(), mask_area)
return mask
def mask_from_frame(frame: np.ndarray) -> torch.Tensor:
"""Find the animal mask using a simple thresholding"""
# First blur the image
frame = cv2.GaussianBlur(frame, (35, 35), 10, 10)
# Set the threshold using the inflexion point of the hist
# threshold = np.quantile(frame, 0.8)
# Limit the search to threshold resulting in 10 to 40% of the image
mini = int((np.quantile(frame, 0.6) * 100).round())
maxi = int((np.quantile(frame, 0.9) * 100).round())
bins = np.array([k / 100 for k in range(101)])
hist, _ = np.histogram(frame.ravel(), bins=bins)
# Smoothing of the histogram before inflexion extraction
cumsum = np.cumsum(hist)
cumsum_pad = np.pad(cumsum, 10 // 2, mode="edge")
cumsum_smooth = np.convolve(cumsum_pad, np.ones(10) / 10, mode="valid")
argmax = np.gradient(np.gradient(np.gradient(cumsum_smooth)))[mini : maxi + 1].argmax() + mini
threshold = bins[argmax + 1]
return torch.tensor(frame > threshold)
class Simulator:
"""Simulator object
Handle the image generation and temporal evolution.
"""
def __init__(
self,
|
@dataclasses.dataclass
class ImagingConfig:
dt: float = 100.0
snr: float = 1.5
noise: float = 0.1
@dataclasses.dataclass
class VideoConfig:
path: str = ""
start: int = 0
stop: int = -1
step: int = 1
transform: byotrack.VideoTransformConfig = byotrack.VideoTransformConfig()
def open(self) -> Optional[byotrack.Video]:
if self.path == "":
return None
video = byotrack.Video(self.path)[slice(self.start, self.stop, self.step)]
video.set_transform(self.transform)
return video
@dataclasses.dataclass
class SimulatorConfig:
base_video: VideoConfig
imaging_config: ImagingConfig
particle: GaussianParticlesConfig
background: GaussianParticlesConfig
nam: NamConfig
motion: MotionConfig
global_motion: GlobalMotionConfig
warm_up: int = 500
def random_mask(size=1024, verbose=False) -> torch.Tensor:
"""Generate a random ellipse mask roughly centered in the middle"""
thresh = 1 / np.sqrt(2 * torch.pi) ** 2 * np.exp(-1 / 2) # Thresh at 1 sigma (1 mahalanohobis)
mask_area = torch.rand(1).item() * 0.15 + 0.2 # [0.2, 0.35]
ratio = 0.5 + 1.5 * torch.rand(1).item() # [0.5, 2]
mean = size / 2 + torch.randn(2) * size / 60
std = torch.tensor([mask_area * ratio / torch.pi, mask_area / ratio / torch.pi]).sqrt() * size
distribution = torch.distributions.Normal(mean, std)
indices = torch.tensor(np.indices((size, size)), dtype=torch.float32).permute(1, 2, 0)
prob = distribution.log_prob(indices).sum(dim=2).exp() * std.prod()
mask = prob > thresh
if verbose:
print(mask.sum() / mask.numel(), mask_area)
return mask
def mask_from_frame(frame: np.ndarray) -> torch.Tensor:
"""Find the animal mask using a simple thresholding"""
# First blur the image
frame = cv2.GaussianBlur(frame, (35, 35), 10, 10)
# Set the threshold using the inflexion point of the hist
# threshold = np.quantile(frame, 0.8)
# Limit the search to threshold resulting in 10 to 40% of the image
mini = int((np.quantile(frame, 0.6) * 100).round())
maxi = int((np.quantile(frame, 0.9) * 100).round())
bins = np.array([k / 100 for k in range(101)])
hist, _ = np.histogram(frame.ravel(), bins=bins)
# Smoothing of the histogram before inflexion extraction
cumsum = np.cumsum(hist)
cumsum_pad = np.pad(cumsum, 10 // 2, mode="edge")
cumsum_smooth = np.convolve(cumsum_pad, np.ones(10) / 10, mode="valid")
argmax = np.gradient(np.gradient(np.gradient(cumsum_smooth)))[mini : maxi + 1].argmax() + mini
threshold = bins[argmax + 1]
return torch.tensor(frame > threshold)
class Simulator:
"""Simulator object
Handle the image generation and temporal evolution.
"""
def __init__(
self, | particles: GaussianParticles, | 4 | 2023-11-10 10:18:39+00:00 | 8k |
quantuminterface/qiclib | src/qiclib/code/qi_prog_builder.py | [
{
"identifier": "QiCommandVisitor",
"path": "src/qiclib/code/qi_visitor.py",
"snippet": "class QiCommandVisitor(abc.ABC):\n def visit_cell_command(self, cell_cmd):\n pass\n\n def visit_context_manager(self, context_manager):\n pass\n\n def visit_if(self, if_cm):\n pass\n\n ... | import copy
import qiclib.packages.utility as util
from typing import List, Any, Dict, Union, Tuple, TYPE_CHECKING
from qiclib.code.qi_seq_instructions import SeqCellSync
from qiclib.code.qi_var_definitions import (
_QiConstValue,
QiCellProperty,
QiExpression,
QiType,
_QiVariableBase,
)
from .qi_visitor import (
QiCommandVisitor,
QiFindVarCmds,
QiCMContainedCellVisitor,
QiCmdVariableInspection,
)
from .qi_util import _get_for_range_iterations, _get_for_range_end_value
from .qi_jobs import QiCommand
from .qi_jobs import _cQiPlay_base, cQiWait, cQiPlayReadout
from .qi_var_definitions import _QiVariableBase
from .qi_jobs import _cQiPlay_base, cQiPlayReadout, cQiRecording
from .qi_sequencer import Sequencer
from .qi_jobs import QiCell
from .qi_jobs import QiCell
from .qi_jobs import (
cQiWait,
cQiPlay,
cQiPlayReadout,
cQiRotateFrame,
cQiRecording,
)
from .qi_sequencer import _ProgramCycles
from .qi_jobs import (
cQiPlay,
cQiPlayReadout,
cQiRotateFrame,
cQiRecording,
cQiWait,
)
from .qi_sequencer import Sequencer, _ProgramCycles
from .qi_var_definitions import _QiVariableBase
from .qi_jobs import cQiWait
from .qi_sequencer import _ProgramCycles
from .qi_var_definitions import _QiVariableBase
from .qi_jobs import cQiWait, _cQiPlay_base
from .qi_sequencer import _ProgramCycles
from .qi_var_definitions import _QiVariableBase
from .qi_var_definitions import _QiVariableBase
from .qi_var_definitions import _QiVariableBase
from .qi_var_definitions import QiOp, _QiVariableBase
from .qi_sequencer import _ProgramCycles
from .qi_var_definitions import _QiVariableBase
from .qi_sequencer import _ProgramCycles
from .qi_var_definitions import QiOp
from .qi_sequencer import _ProgramCycles
from .qi_sequencer import _ProgramCycles
from .qi_var_definitions import _QiVariableBase
from .qi_jobs import _QiVariableBase, _QiCalcBase
from .qi_sequencer import _ProgramCycles
from .qi_sequencer import Sequencer | 5,130 | relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
if find_var_visitor.calc_in_wait:
self.force_sync(
relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
if isinstance(start_val, _QiVariableBase) or start_val is None:
self.force_sync(
relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
if isinstance(start_val, (_QiConstValue, QiCellProperty)):
start_val = start_val.value
prog_lengths: List[int] = []
wait_cmds = {}
for cell in relevant_cells:
wait_cmds[cell] = [
cmd
for cmd in find_var_visitor.found_cmds
if cell in cmd._relevant_cells
]
prog_lengths.append(
self.cell_seq[cell].prog_cycles - (start_val * len(wait_cmds[cell]))
) # subtract already added variable waits
# negative prog_lengths imply that a self.cell_seq[cell].prog_cycles were invalid.
if any(x < 0 for x in prog_lengths):
self.force_sync(
relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
longest = max(prog_lengths)
cycles_without_waits = self.cell_seq[cell].prog_cycles - (
start_val * len(wait_cmds[cell])
)
for cell in relevant_cells:
if cycles_without_waits < longest:
# sync non variable cycles
self.cell_seq[cell]._wait_cycles(longest - cycles_without_waits)
most_waits = 0
for cell in relevant_cells:
most_waits = max(len(wait_cmds[cell]), most_waits)
waits = len(wait_cmds[cell])
for _ in range(waits, most_waits):
self.cell_seq[cell].add_wait_cmd(
cQiWait(None, for_range.var)
) # add missing waits, no multiplication to avoid overflows
def update_cycles_after_for_range(self, for_range, start_val, program_cycles_start):
"""First iteration of loop was already added to sequencer; so every variable wait already used start_val cycles.
If variable start/end are used, sets _prog_cycles to False."""
relevant_cells = self.get_relevant_cells(for_range)
end_val = self.get_for_range_val(for_range.end, relevant_cells)
if (
isinstance(for_range.start, _QiVariableBase)
or isinstance(for_range.end, _QiVariableBase)
or start_val is None
or end_val is None
):
for cell in relevant_cells:
self.cell_seq[cell]._prog_cycles.valid = False
return
if isinstance(start_val, (_QiConstValue, QiCellProperty)):
start_val = start_val.value
assert isinstance(start_val, (int, _QiVariableBase))
find_var_visitor = QiFindVarCmds(for_range.var)
for cmd in for_range.body:
cmd.accept(find_var_visitor)
wait_cmds = {}
play_cmds = {}
for cell in relevant_cells:
wait_cmds[cell] = [
cmd
for cmd in find_var_visitor.found_cmds
if cell in cmd._relevant_cells and isinstance(cmd, cQiWait)
]
play_cmds[cell] = [
cmd
for cmd in find_var_visitor.found_cmds
if cell in cmd._relevant_cells and isinstance(cmd, _cQiPlay_base)
]
for cell in relevant_cells:
if self.cell_seq[cell].prog_cycles is _ProgramCycles.INVALID:
continue
if len(find_var_visitor.found_cmds) == 0:
self.cell_seq[cell].prog_cycles += (
self.cell_seq[cell].prog_cycles - program_cycles_start[cell]
) * (
| # Copyright © 2017-2023 Quantum Interface (quantuminterface@ipe.kit.edu)
# Richard Gebauer, IPE, Karlsruhe Institute of Technology
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
This module contains the higher level parts of the code generation logic.
The entry point is in `QiProgramBuilder.build_program` which uses the `ProgramBuilderVisitor`.
`ProgramBuilderVisitor` recursively visits every `QiJob` command and generates its corresponding
RISC-V assembly sequentially.
"""
if TYPE_CHECKING:
class QiCmdExcludeVar(QiCommandVisitor):
"""Generates command list excluding cell- and variable-commands which implement variables from ignore_list.
Generates new context managers with updated bodies"""
def __init__(self, ignore_list: List[Any]) -> None:
self.ignore_list = ignore_list
self.commands: List[QiCommand] = []
def visit_cell_command(self, cell_cmd):
for variable in self.ignore_list:
if (
isinstance(cell_cmd, _cQiPlay_base)
and variable in cell_cmd._associated_variable_set
):
if (
isinstance(cell_cmd, cQiPlayReadout)
and cell_cmd.recording is not None
):
self.commands.append(cell_cmd.recording)
return
elif (
isinstance(cell_cmd, cQiWait)
and isinstance(cell_cmd.length, _QiVariableBase)
and cell_cmd.length.id == variable.id
):
# If cQiWait.length is QiCalc, append command
return
self.commands.append(cell_cmd)
def visit_context_manager(self, context_manager):
exclude_var = QiCmdExcludeVar(self.ignore_list)
for command in context_manager.body:
command.accept(exclude_var)
if len(exclude_var.commands) == 0:
return
new_cm = copy.copy(context_manager)
new_cm._relevant_cells.update(context_manager._relevant_cells)
new_cm.body = exclude_var.commands
self.commands.append(new_cm)
def visit_if(self, if_cm):
"""Searches If/Else for commands containing variables defined in self.ignore_list.
Creates new bodies and checks their size, so no empty ifs are returned."""
exclude_if_body = QiCmdExcludeVar(self.ignore_list)
for command in if_cm.body:
command.accept(exclude_if_body)
new_if = copy.copy(if_cm)
new_if.body = exclude_if_body.commands
if if_cm.is_followed_by_else():
exclude_else_body = QiCmdExcludeVar(self.ignore_list)
for command in if_cm._else_body:
command.accept(exclude_else_body)
if len(exclude_else_body.commands) > 0:
new_if._else_body = exclude_else_body.commands
if len(new_if.body) != 0 or len(new_if._else_body) != 0:
self.commands.append(new_if)
def visit_parallel(self, parallel_cm):
new_parallel = copy.copy(parallel_cm)
new_parallel.parallel = []
for cmd_list in parallel_cm.entries:
exclude_var = QiCmdExcludeVar(self.ignore_list)
for cmd in cmd_list:
cmd.accept(exclude_var)
if len(exclude_var.commands) > 0:
new_parallel.parallel.append(exclude_var.commands)
if len(new_parallel.parallel) > 0:
self.commands.append(new_parallel)
def visit_variable_command(self, variable_cmd):
for variable in self.ignore_list:
if variable.id == variable_cmd.var.id:
return
self.commands.append(variable_cmd)
def visit_sync_command(self, sync_cmd):
self.commands.append(sync_cmd)
def visit_mem_store_command(self, store_cmd):
self.commands.append(store_cmd)
class QiCmdReplaceTriggerVar(QiCommandVisitor):
"""Generates command list, replacing trigger commands utilizing var with a trigger command of length 1.
Generates new context managers with updated bodies."""
def __init__(self, replace_var) -> None:
self.replace_var = replace_var
self.commands: List[QiCommand] = []
def visit_cell_command(self, cell_cmd):
if (
isinstance(cell_cmd, _cQiPlay_base)
and self.replace_var in cell_cmd._associated_variable_set
):
new_cmd = copy.copy(cell_cmd)
new_cmd._relevant_cells.update(cell_cmd._relevant_cells)
if isinstance(cell_cmd, cQiPlayReadout) and isinstance(
cell_cmd.recording, cQiRecording
):
new_cmd.recording = copy.copy(cell_cmd.recording)
new_cmd.length = util.conv_cycles_to_time(
1
) # set length to 1 for possible Parallel sequence generation
new_cmd._var_single_cycle_trigger = True
self.commands.append(new_cmd)
return
self.commands.append(cell_cmd)
def visit_context_manager(self, context_manager):
replace_var = QiCmdReplaceTriggerVar(self.replace_var)
for command in context_manager.body:
command.accept(replace_var)
new_cm = copy.copy(context_manager)
new_cm._relevant_cells.update(context_manager._relevant_cells)
new_cm.body = replace_var.commands
self.commands.append(new_cm)
def visit_if(self, if_cm):
"""Searches If/Else for commands containing variable defined in self.replace_var."""
replace_var_if = QiCmdReplaceTriggerVar(self.replace_var)
for command in if_cm.body:
command.accept(replace_var_if)
new_if = copy.copy(if_cm)
new_if.body = replace_var_if.commands
if if_cm.is_followed_by_else():
replace_var_else = QiCmdReplaceTriggerVar(self.replace_var)
for command in if_cm._else_body:
command.accept(replace_var_else)
new_if._else_body = replace_var_else.commands
self.commands.append(new_if)
def visit_parallel(self, parallel_cm):
new_parallel = copy.copy(parallel_cm)
new_parallel.parallel = []
for cmd_list in parallel_cm.parallel:
replace_var = QiCmdReplaceTriggerVar(self.replace_var)
for cmd in cmd_list:
cmd.accept(replace_var)
new_parallel.parallel.append(replace_var.commands)
if len(new_parallel.parallel) > 0:
self.commands.append(new_parallel)
def visit_variable_command(self, variable_cmd):
self.commands.append(variable_cmd)
def visit_sync_command(self, sync_cmd):
self.commands.append(sync_cmd)
def visit_mem_store_command(self, store_cmd):
self.commands.append(store_cmd)
class ProgramBuilderVisitor(QiCommandVisitor):
def __init__(self, cell_seq, job_cell_to_digital_unit_cell_map) -> None:
self.cell_seq: Dict[QiCell, Sequencer] = cell_seq
self.if_depth: int = 0 # Used to check if currently processing commands inside If-Context-Manager
self.for_range_end_val_list: List[
Tuple[_QiVariableBase, Union[QiExpression, int]]
] = []
self.job_cell_to_digital_unit_cell_map = job_cell_to_digital_unit_cell_map
def get_relevant_cells(self, cmd):
"""Generates a list of releveant cells from the cells registered to the builder and the command cmd"""
return [cell for cell in self.cell_seq.keys() if cell in cmd._relevant_cells]
def end_of_body(self, relevant_cells):
"""End of body --> stop potentially running pulses"""
for cell in self.cell_seq.keys():
if cell in relevant_cells:
self.cell_seq[cell].end_of_command_body()
def build_element_body(self, body, relevant_cells):
"""Function used to build commands from body.
end_of_body() is called afterwards to end possibly ongoing pulses"""
for cmd in body:
cmd.accept(self)
self.end_of_body(relevant_cells)
def force_sync(self, relevant_cells, sync_point):
"""Forces the given cells to synchronize by inserting a SeqCellSync instruction."""
digital_unit_cell_indices = list(
map(
lambda cell: self.job_cell_to_digital_unit_cell_map[cell.cellID],
relevant_cells,
)
)
for cell in relevant_cells:
cell_sequencer = self.cell_seq[cell]
cell_sequencer.add_instruction_to_list(
SeqCellSync(digital_unit_cell_indices)
)
cell_sequencer._prog_cycles.set_synchronized(sync_point)
def cells_implicitly_synchronizable(self, cells):
all_valid = all(self.cell_seq[cell].prog_cycles >= 0 for cell in cells)
def all_share_syncpoint():
return (
len(
set(
map(
lambda cell: self.cell_seq[
cell
]._prog_cycles.last_sync_point,
cells,
)
)
)
== 1
)
return all_valid and all_share_syncpoint()
def sync_cells(self, relevant_cells, sync_point):
"""
Synchronizes given cells, implicitly if possible, explicitly otherwise.
If implicit synch is possible, it evaluates the current programm lengths of sequencers
of relevant_cells. If valid prog_lengths are found adds Wait commands at sequencers
with shorter programs.
"""
relevant_cells: List[QiCell] = relevant_cells
if len(relevant_cells) <= 1:
return
if not self.cells_implicitly_synchronizable(relevant_cells):
self.force_sync(relevant_cells, sync_point)
else:
prog_lengths: List[int] = list(
map(lambda cell: self.cell_seq[cell].prog_cycles, relevant_cells)
)
longest = max(prog_lengths)
for cell in relevant_cells:
if self.cell_seq[cell].prog_cycles < longest:
self.cell_seq[cell]._wait_cycles(
longest - self.cell_seq[cell].prog_cycles
)
def _unroll_loop_0(self, for_range, static_unroll=False):
"""Function used for unrolling ForRange with variable value 0.
A new program body is built from ForRange.body excluding wait and pulse commands using solely ForRange.var.
The new program body is then added to the sequencer."""
exclude_var = QiCmdExcludeVar([for_range.var])
for cmd in for_range.body:
cmd.accept(exclude_var)
if len(exclude_var.commands) == 0:
return
relevant_cells = self.get_relevant_cells(for_range)
for cell in relevant_cells:
if static_unroll is True:
# set register value to 0 in case it had different values before --> important for possible use in conditions
self.cell_seq[cell].set_variable_value(for_range.var, 0)
# register one cycle of ForRange, actual start/end/step values not relevant
self.cell_seq[cell].register_for_range(
for_range.var, 0, for_range.step.value, for_range.step.value
)
self.build_element_body(exclude_var.commands, for_range._relevant_cells)
for cell in relevant_cells:
self.cell_seq[cell].exit_for_range()
def _unroll_loop_1(self, for_range):
"""Function used for unrolling ForRange with variable value 1.
A new program body is built from ForRange.body, replacing pulse commands using ForRange.var with trigger commands with length 1.
The new program body is then added to the sequencer."""
replace_var = QiCmdReplaceTriggerVar(for_range.var)
for cmd in for_range.body:
cmd.accept(replace_var)
relevant_cells = self.get_relevant_cells(for_range)
for cell in relevant_cells:
self.cell_seq[cell].register_for_range(
for_range.var, 1, 1 + for_range.step.value, for_range.step.value
) # register one cycle of ForRange, actual start/end/step values not relevant
self.build_element_body(replace_var.commands, for_range._relevant_cells)
for cell in relevant_cells:
self.cell_seq[cell].exit_for_range()
def visit_cell_command(self, cell_cmd):
relevant_cells = self.get_relevant_cells(cell_cmd)
for cell in relevant_cells:
if isinstance(cell_cmd, cQiWait):
# Ignore Wait command if it is of length less than a cycle.
length = cell_cmd.length
if (
isinstance(length, (int, float))
and util.conv_time_to_cycles(length) == 0
):
return
self.cell_seq[cell].add_wait_cmd(cell_cmd)
elif isinstance(cell_cmd, (cQiPlay, cQiRotateFrame)):
self.cell_seq[cell].add_trigger_cmd(
manipulation=cell_cmd,
var_single_cycle=cell_cmd._var_single_cycle_trigger,
)
elif isinstance(cell_cmd, cQiPlayReadout):
# cell_cmd.combine_recording is either None or cQiRecording
self.cell_seq[cell].add_trigger_cmd(
readout=cell_cmd,
recording=cell_cmd.recording,
var_single_cycle=cell_cmd._var_single_cycle_trigger,
)
elif isinstance(cell_cmd, cQiRecording):
self.cell_seq[cell].add_trigger_cmd(recording=cell_cmd)
def visit_context_manager(self, context_manager):
"""Context managers are evaluated in respective visit"""
def visit_if(self, if_cm):
"""Visits If command and builds sequencer instructions.
Tries synchronizing if multiple cells are used."""
jump_over_if = {}
program_counters = {}
relevant_cells = self.get_relevant_cells(if_cm)
self.sync_cells(relevant_cells, _ProgramCycles.SyncPoint(if_cm))
self.if_depth += 1
for cell in relevant_cells:
jump_over_if[cell] = self.cell_seq[cell].add_if_condition(if_cm.condition)
# conditional branching makes implicit sync by wait impossible
self.cell_seq[cell]._prog_cycles.valid = False
program_counters[cell] = self.cell_seq[cell].get_prog_size() - 1
self.build_element_body(if_cm.body, if_cm._relevant_cells)
if if_cm.is_followed_by_else():
jump_over_else = {}
for cell in relevant_cells:
# add jump after if-body to jump over else-body
jump_over_else[cell] = self.cell_seq[cell].add_jump()
jump_over_if[cell].set_jump_value(
self.cell_seq[cell].get_prog_size() - program_counters[cell]
)
program_counters[cell] = self.cell_seq[cell].get_prog_size() - 1
self.build_element_body(if_cm._else_body, if_cm._relevant_cells)
for cell in relevant_cells:
jump_over_else[cell].jump_val = (
self.cell_seq[cell].get_prog_size() - program_counters[cell]
)
else:
for cell in relevant_cells:
jump_over_if[cell].set_jump_value(
self.cell_seq[cell].get_prog_size() - program_counters[cell]
)
self.if_depth -= 1
def visit_parallel(self, parallel_cm):
"""Visits Parallel command and builds sequencer command.
Searches for manipulation, readout and recording pulses inside body and summarizes them in one trigger command.
"""
relevant_cells = self.get_relevant_cells(parallel_cm)
self.sync_cells(relevant_cells, _ProgramCycles.SyncPoint(parallel_cm))
for cell in relevant_cells:
time_slots = parallel_cm._generate_command_body(cell, self.cell_seq[cell])
for time_slot in time_slots:
if isinstance(time_slot.cmd_tuples[0].cmd, cQiWait):
self.cell_seq[cell].add_wait_cmd(cQiWait(cell, time_slot.duration))
else:
manipulation = None
readout = None
recording = None
for cmd_tuple in time_slot.cmd_tuples:
trigger_cmd = copy.copy(cmd_tuple.cmd)
trigger_cmd.length = time_slot.duration
if isinstance(cmd_tuple.cmd, (cQiPlay, cQiRotateFrame)):
if cmd_tuple.choke_cmd is True:
trigger_cmd.trigger_index = Sequencer.CHOKE_PULSE_INDEX
manipulation = trigger_cmd
elif isinstance(cmd_tuple.cmd, cQiPlayReadout):
if cmd_tuple.choke_cmd is True:
trigger_cmd.trigger_index = Sequencer.CHOKE_PULSE_INDEX
trigger_cmd.recording = None
readout = trigger_cmd
recording = trigger_cmd.recording
elif isinstance(cmd_tuple.cmd, cQiRecording):
recording = trigger_cmd
self.cell_seq[cell].add_trigger_cmd(
manipulation=manipulation,
readout=readout,
recording=recording,
recording_delay=False,
)
def try_sync_for_range(self, for_range, start_val: "QiExpression"):
"""If multiple cells are used inside a ForRange context manager the program tries to sync cells before restarting the loop.
If the ForRange does not use its variable for Pulses or waits a normal sync is used.
"""
relevant_cells = self.get_relevant_cells(for_range)
if len(relevant_cells) == 1:
return
find_var_visitor = QiFindVarCmds(for_range.var)
for cmd in for_range.body:
cmd.accept(find_var_visitor)
if len(find_var_visitor.found_cmds) == 0:
self.sync_cells(
relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
if find_var_visitor.calc_in_wait:
self.force_sync(
relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
if isinstance(start_val, _QiVariableBase) or start_val is None:
self.force_sync(
relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
if isinstance(start_val, (_QiConstValue, QiCellProperty)):
start_val = start_val.value
prog_lengths: List[int] = []
wait_cmds = {}
for cell in relevant_cells:
wait_cmds[cell] = [
cmd
for cmd in find_var_visitor.found_cmds
if cell in cmd._relevant_cells
]
prog_lengths.append(
self.cell_seq[cell].prog_cycles - (start_val * len(wait_cmds[cell]))
) # subtract already added variable waits
# negative prog_lengths imply that a self.cell_seq[cell].prog_cycles were invalid.
if any(x < 0 for x in prog_lengths):
self.force_sync(
relevant_cells,
_ProgramCycles.SyncPoint(
for_range, _ProgramCycles.SyncPointType.AFTER_FOR_RANGE_ITERATION
),
)
return
longest = max(prog_lengths)
cycles_without_waits = self.cell_seq[cell].prog_cycles - (
start_val * len(wait_cmds[cell])
)
for cell in relevant_cells:
if cycles_without_waits < longest:
# sync non variable cycles
self.cell_seq[cell]._wait_cycles(longest - cycles_without_waits)
most_waits = 0
for cell in relevant_cells:
most_waits = max(len(wait_cmds[cell]), most_waits)
waits = len(wait_cmds[cell])
for _ in range(waits, most_waits):
self.cell_seq[cell].add_wait_cmd(
cQiWait(None, for_range.var)
) # add missing waits, no multiplication to avoid overflows
def update_cycles_after_for_range(self, for_range, start_val, program_cycles_start):
"""First iteration of loop was already added to sequencer; so every variable wait already used start_val cycles.
If variable start/end are used, sets _prog_cycles to False."""
relevant_cells = self.get_relevant_cells(for_range)
end_val = self.get_for_range_val(for_range.end, relevant_cells)
if (
isinstance(for_range.start, _QiVariableBase)
or isinstance(for_range.end, _QiVariableBase)
or start_val is None
or end_val is None
):
for cell in relevant_cells:
self.cell_seq[cell]._prog_cycles.valid = False
return
if isinstance(start_val, (_QiConstValue, QiCellProperty)):
start_val = start_val.value
assert isinstance(start_val, (int, _QiVariableBase))
find_var_visitor = QiFindVarCmds(for_range.var)
for cmd in for_range.body:
cmd.accept(find_var_visitor)
wait_cmds = {}
play_cmds = {}
for cell in relevant_cells:
wait_cmds[cell] = [
cmd
for cmd in find_var_visitor.found_cmds
if cell in cmd._relevant_cells and isinstance(cmd, cQiWait)
]
play_cmds[cell] = [
cmd
for cmd in find_var_visitor.found_cmds
if cell in cmd._relevant_cells and isinstance(cmd, _cQiPlay_base)
]
for cell in relevant_cells:
if self.cell_seq[cell].prog_cycles is _ProgramCycles.INVALID:
continue
if len(find_var_visitor.found_cmds) == 0:
self.cell_seq[cell].prog_cycles += (
self.cell_seq[cell].prog_cycles - program_cycles_start[cell]
) * ( | _get_for_range_iterations(start_val, end_val, for_range.step.value) | 4 | 2023-11-10 10:26:10+00:00 | 8k |
jpcadena/fastapi-boilerplate | app/services/infrastructure/auth.py | [
{
"identifier": "get_auth_settings",
"path": "app/config/config.py",
"snippet": "@lru_cache()\ndef get_auth_settings() -> AuthSettings:\n \"\"\"\n Get auth settings cached\n :return: Auth settings instance\n :rtype: AuthSettings\n \"\"\"\n return AuthSettings()"
},
{
"identifie... | import logging
import time
from typing import Annotated, Any, Optional
from fastapi import Depends, HTTPException, status
from redis.asyncio import Redis
from app.config.config import get_auth_settings
from app.config.db.auth_settings import AuthSettings
from app.core.security.jwt import create_access_token, create_refresh_token
from app.models.sql.user import User
from app.models.unstructured.token import Token as TokenDB
from app.schemas.external.token import Token, TokenPayload, TokenResponse
from app.schemas.infrastructure.scope import Scope
from app.services.infrastructure.token import TokenService
from app.utils.utils import get_nationality_code | 4,332 | """
A module for auth in the app.services package.
"""
logger: logging.Logger = logging.getLogger(__name__)
class AuthService:
"""
Service class for user authentication.
"""
@staticmethod
def _build_payload(
user: User,
| """
A module for auth in the app.services package.
"""
logger: logging.Logger = logging.getLogger(__name__)
class AuthService:
"""
Service class for user authentication.
"""
@staticmethod
def _build_payload(
user: User, | auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], | 0 | 2023-11-17 00:32:32+00:00 | 8k |
vitant-lang/CBAM-ASPP | get_miou.py | [
{
"identifier": "DeeplabV3",
"path": "deeplab.py",
"snippet": "class DeeplabV3(object):\n _defaults = {\n #-------------------------------------------------------------------#\n # model_path指向logs文件夹下的权值文件\n # 训练好后logs文件夹下存在多个权值文件,选择验证集损失较低的即可。\n # 验证集损失较低不代表miou较高,仅... | import os
from PIL import Image
from tqdm import tqdm
from deeplab import DeeplabV3
from utils.utils_metrics import compute_mIoU, show_results | 6,713 |
'''
进行指标评估需要注意以下几点:
1、该文件生成的图为灰度图,因为值比较小,按照PNG形式的图看是没有显示效果的,所以看到近似全黑的图是正常的。
2、该文件计算的是验证集的miou,当前该库将测试集当作验证集使用,不单独划分测试集
'''
if __name__ == "__main__":
#---------------------------------------------------------------------------#
# miou_mode用于指定该文件运行时计算的内容
# miou_mode为0代表整个miou计算流程,包括获得预测结果、计算miou。
# miou_mode为1代表仅仅获得预测结果。
# miou_mode为2代表仅仅计算miou。
#---------------------------------------------------------------------------#
miou_mode = 0
#------------------------------#
# 分类个数+1、如2+1
#------------------------------#
num_classes = 3
#--------------------------------------------#
# 区分的种类,和json_to_dataset里面的一样
#--------------------------------------------#
#name_classes = ["background","aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
name_classes = ["_background_","cat","coal"]
#-------------------------------------------------------#
# 指向VOC数据集所在的文件夹
# 默认指向根目录下的VOC数据集
#-------------------------------------------------------#
VOCdevkit_path = 'VOCdevkit'
image_ids = open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Segmentation/val.txt"),'r').read().splitlines()
gt_dir = os.path.join(VOCdevkit_path, "VOC2007/SegmentationClass/")
miou_out_path = "miou_out"
pred_dir = os.path.join(miou_out_path, 'detection-results')
if miou_mode == 0 or miou_mode == 1:
if not os.path.exists(pred_dir):
os.makedirs(pred_dir)
print("Load model.")
deeplab = DeeplabV3()
print("Load model done.")
print("Get predict result.")
for image_id in tqdm(image_ids):
image_path = os.path.join(VOCdevkit_path, "VOC2007/JPEGImages/"+image_id+".jpg")
image = Image.open(image_path)
image = deeplab.get_miou_png(image)
image.save(os.path.join(pred_dir, image_id + ".png"))
print("Get predict result done.")
if miou_mode == 0 or miou_mode == 2:
print("Get miou.")
hist, IoUs, PA_Recall, Precision = compute_mIoU(gt_dir, pred_dir, image_ids, num_classes, name_classes) # 执行计算mIoU的函数
print("Get miou done.")
|
'''
进行指标评估需要注意以下几点:
1、该文件生成的图为灰度图,因为值比较小,按照PNG形式的图看是没有显示效果的,所以看到近似全黑的图是正常的。
2、该文件计算的是验证集的miou,当前该库将测试集当作验证集使用,不单独划分测试集
'''
if __name__ == "__main__":
#---------------------------------------------------------------------------#
# miou_mode用于指定该文件运行时计算的内容
# miou_mode为0代表整个miou计算流程,包括获得预测结果、计算miou。
# miou_mode为1代表仅仅获得预测结果。
# miou_mode为2代表仅仅计算miou。
#---------------------------------------------------------------------------#
miou_mode = 0
#------------------------------#
# 分类个数+1、如2+1
#------------------------------#
num_classes = 3
#--------------------------------------------#
# 区分的种类,和json_to_dataset里面的一样
#--------------------------------------------#
#name_classes = ["background","aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
name_classes = ["_background_","cat","coal"]
#-------------------------------------------------------#
# 指向VOC数据集所在的文件夹
# 默认指向根目录下的VOC数据集
#-------------------------------------------------------#
VOCdevkit_path = 'VOCdevkit'
image_ids = open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Segmentation/val.txt"),'r').read().splitlines()
gt_dir = os.path.join(VOCdevkit_path, "VOC2007/SegmentationClass/")
miou_out_path = "miou_out"
pred_dir = os.path.join(miou_out_path, 'detection-results')
if miou_mode == 0 or miou_mode == 1:
if not os.path.exists(pred_dir):
os.makedirs(pred_dir)
print("Load model.")
deeplab = DeeplabV3()
print("Load model done.")
print("Get predict result.")
for image_id in tqdm(image_ids):
image_path = os.path.join(VOCdevkit_path, "VOC2007/JPEGImages/"+image_id+".jpg")
image = Image.open(image_path)
image = deeplab.get_miou_png(image)
image.save(os.path.join(pred_dir, image_id + ".png"))
print("Get predict result done.")
if miou_mode == 0 or miou_mode == 2:
print("Get miou.")
hist, IoUs, PA_Recall, Precision = compute_mIoU(gt_dir, pred_dir, image_ids, num_classes, name_classes) # 执行计算mIoU的函数
print("Get miou done.") | show_results(miou_out_path, hist, IoUs, PA_Recall, Precision, name_classes) | 2 | 2023-11-17 13:25:28+00:00 | 8k |
dataaug/open-interpreter-free | interpreter/core/core.py | [
{
"identifier": "cli",
"path": "interpreter/cli/cli.py",
"snippet": "def cli(interpreter):\n parser = argparse.ArgumentParser(description=\"Open Interpreter\")\n\n # Add arguments\n for arg in arguments:\n if arg[\"type\"] == bool:\n parser.add_argument(\n f'-{a... | import json
import os
from datetime import datetime
from ..cli.cli import cli
from ..llm.setup_llm import setup_llm
from ..terminal_interface.terminal_interface import terminal_interface
from ..terminal_interface.validate_llm_settings import validate_llm_settings
from ..utils.check_for_update import check_for_update
from ..utils.display_markdown_message import display_markdown_message
from ..utils.get_config import get_config, user_config_path
from ..utils.local_storage_path import get_storage_path
from .generate_system_message import generate_system_message
from .respond import respond | 6,987 | """
This file defines the Interpreter class.
It's the main file. `import interpreter` will import an instance of this class.
"""
class Interpreter:
def cli(self):
cli(self)
def __init__(self):
# State
self.messages = []
self._code_interpreters = {}
self.config_file = user_config_path
# Settings
self.local = False
self.auto_run = False
self.debug_mode = False
self.max_output = 2000
self.safe_mode = "off"
self.disable_procedures = False
# Conversation history
self.conversation_history = True
self.conversation_filename = None
self.conversation_history_path = get_storage_path("conversations")
# LLM settings
self.model = ""
self.temperature = None
self.system_message = ""
self.context_window = None
self.max_tokens = None
self.api_base = None
self.api_key = None
self.max_budget = None
self._llm = None
self.function_calling_llm = None
self.vision = False # LLM supports vision
# Load config defaults
self.extend_config(self.config_file)
# Check for update
try:
if not self.local:
# This should actually be pushed into the utility
if check_for_update():
| """
This file defines the Interpreter class.
It's the main file. `import interpreter` will import an instance of this class.
"""
class Interpreter:
def cli(self):
cli(self)
def __init__(self):
# State
self.messages = []
self._code_interpreters = {}
self.config_file = user_config_path
# Settings
self.local = False
self.auto_run = False
self.debug_mode = False
self.max_output = 2000
self.safe_mode = "off"
self.disable_procedures = False
# Conversation history
self.conversation_history = True
self.conversation_filename = None
self.conversation_history_path = get_storage_path("conversations")
# LLM settings
self.model = ""
self.temperature = None
self.system_message = ""
self.context_window = None
self.max_tokens = None
self.api_base = None
self.api_key = None
self.max_budget = None
self._llm = None
self.function_calling_llm = None
self.vision = False # LLM supports vision
# Load config defaults
self.extend_config(self.config_file)
# Check for update
try:
if not self.local:
# This should actually be pushed into the utility
if check_for_update(): | display_markdown_message( | 5 | 2023-11-16 03:10:42+00:00 | 8k |
3dp-accelerometer/octoprint-accelerometer | octoprint_accelerometer/plugin.py | [
{
"identifier": "DataPostProcessRunner",
"path": "octoprint_accelerometer/data_post_process.py",
"snippet": "class DataPostProcessRunner:\n \"\"\"\n Runner for traversing stream files and post-processing (FFT) if necessary.\n \"\"\"\n def __init__(self,\n logger: Logger,\n ... | import os
import flask
import octoprint.plugin
from typing import Any, Dict, List, Literal, Optional, Tuple
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
from octoprint.util import is_hidden_path
from py3dpaxxel.cli.args import convert_axis_from_str
from py3dpaxxel.controller.api import Py3dpAxxel
from py3dpaxxel.sampling_tasks.series_argument_generator import RunArgsGenerator
from py3dpaxxel.storage.file_filter import FileSelector, File
from py3dpaxxel.storage.filename import timestamp_from_args
from py3dpaxxel.storage.filename_meta import FilenameMetaStream, FilenameMetaFft
from octoprint_accelerometer.data_post_process import DataPostProcessRunner
from octoprint_accelerometer.event_types import DataProcessingEventType, RecordingEventType
from octoprint_accelerometer.record_step_series import RecordStepSeriesRunner
from octoprint_accelerometer.transfer_types import RunMeta, SequenceMeta, StreamMeta, DataSets, FftMeta, Timestamp | 7,023 | octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin):
OUTPUT_STREAM_FILE_NAME_PREFIX: str = "axxel"
OUTPUT_FFT_FILE_NAME_PREFIX: str = "fft"
# noinspection PyMissingConstructor
def __init__(self):
# following parameters are shared among settings and UI
self.distance_x_mm: int = 0
self.distance_y_mm: int = 0
self.distance_z_mm: int = 0
self.step_count: int = 0
self.speed_x_mm_s: int = 0
self.speed_y_mm_s: int = 0
self.speed_z_mm_s: int = 0
self.acceleration_x_mm_ss: int = 0
self.acceleration_y_mm_ss: int = 0
self.acceleration_z_mm_ss: int = 0
self.anchor_point_coord_x_mm: int = 0
self.anchor_point_coord_y_mm: int = 0
self.anchor_point_coord_z_mm: int = 0
self.sequence_count: int = 0
self.go_start: bool = False
self.return_start: bool = False
self.auto_home: bool = False
self.start_frequency_hz: int = 0
self.stop_frequency_hz: int = 0
self.step_frequency_hz: int = 0
self.start_zeta_em2: int = 0
self.stop_zeta_em2: int = 0
self.step_zeta_em2: int = 0
self.sensor_output_data_rate_hz: int = 0
self.data_remove_before_run: bool = False
self.do_sample_x: bool = False
self.do_sample_y: bool = False
self.do_sample_z: bool = False
self.recording_timespan_s: float = 0
self.sequence_separation_s: float = 0
self.step_separation_s: float = 0
self.do_dry_run: bool = False
# other parameters shared with UI
self.devices_seen: List[str] = []
self.device: str = ""
self.controller_fifo_overrun_error: bool = False
self.controller_response_error: bool = False
# following parameters are computed from above parameters
self.axis_x_sampling_start: Point3D = Point3D(0, 0, 0)
self.axis_y_sampling_start: Point3D = Point3D(0, 0, 0)
self.axis_z_sampling_start: Point3D = Point3D(0, 0, 0)
# recording runner: once constructed before invocation all properties shall be updated
self.data_recording_runner: Optional[RecordStepSeriesRunner] = None
self.data_processing_runner: Optional[DataPostProcessRunner] = None
@staticmethod
def _get_devices() -> Tuple[str, List[str]]:
"""
:return: tuple of primary device (if any) and list of all devices
"""
seen_devices: List[str] = [k for k in Py3dpAxxel.get_devices_dict().keys()]
primary: str = seen_devices[0] if len(seen_devices) > 0 else None
return primary, seen_devices
def _update_seen_devices(self):
primary, seen_devices = self._get_devices()
self._logger.debug(f"seen devices: primary={primary}, seen={seen_devices}")
self.devices_seen = seen_devices
self.device = primary if primary is not None else ""
@octoprint.plugin.BlueprintPlugin.route("/set_values", methods=["POST"])
def on_api_set_values(self):
data = flask.request.json
self._update_members_from_api(data)
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/start_recording", methods=["POST"])
def on_api_start_recording(self):
self._start_recording()
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/abort_recording", methods=["POST"])
def on_api_abort_recording(self):
self._abort_recording()
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/start_data_processing", methods=["POST"])
def on_api_start_data_processing(self):
self._start_data_processing()
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/get_estimate", methods=["GET"])
def on_api_get_estimate(self):
return flask.jsonify({f"estimate": self._estimate_duration()})
@octoprint.plugin.BlueprintPlugin.route("/get_parameters", methods=["GET"])
def on_api_get_parameters(self):
return flask.jsonify({f"parameters": self._get_parameter_dict(flask.request.args)})
@octoprint.plugin.BlueprintPlugin.route("/get_files_listing", methods=["GET"])
def on_api_get_files_listing(self):
fs = FileSelector(os.path.join(self.get_plugin_data_folder(), ".*"))
files_details = fs.filter()
return flask.jsonify({f"files": files_details})
@octoprint.plugin.BlueprintPlugin.route("/get_stream_files_listing", methods=["GET"])
def on_api_get_stream_files_listing(self):
fs = FileSelector(os.path.join(self.get_plugin_data_folder(), f"{self.OUTPUT_STREAM_FILE_NAME_PREFIX}-.*\\.tsv$"))
files = fs.filter()
|
class Point3D:
def __init__(self, x: int, y: int, z: int):
self.x: int = x
self.y: int = y
self.z: int = z
def __str__(self):
return f"x={self.x} y={self.y} z={self.z}"
class OctoprintAccelerometerPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin):
OUTPUT_STREAM_FILE_NAME_PREFIX: str = "axxel"
OUTPUT_FFT_FILE_NAME_PREFIX: str = "fft"
# noinspection PyMissingConstructor
def __init__(self):
# following parameters are shared among settings and UI
self.distance_x_mm: int = 0
self.distance_y_mm: int = 0
self.distance_z_mm: int = 0
self.step_count: int = 0
self.speed_x_mm_s: int = 0
self.speed_y_mm_s: int = 0
self.speed_z_mm_s: int = 0
self.acceleration_x_mm_ss: int = 0
self.acceleration_y_mm_ss: int = 0
self.acceleration_z_mm_ss: int = 0
self.anchor_point_coord_x_mm: int = 0
self.anchor_point_coord_y_mm: int = 0
self.anchor_point_coord_z_mm: int = 0
self.sequence_count: int = 0
self.go_start: bool = False
self.return_start: bool = False
self.auto_home: bool = False
self.start_frequency_hz: int = 0
self.stop_frequency_hz: int = 0
self.step_frequency_hz: int = 0
self.start_zeta_em2: int = 0
self.stop_zeta_em2: int = 0
self.step_zeta_em2: int = 0
self.sensor_output_data_rate_hz: int = 0
self.data_remove_before_run: bool = False
self.do_sample_x: bool = False
self.do_sample_y: bool = False
self.do_sample_z: bool = False
self.recording_timespan_s: float = 0
self.sequence_separation_s: float = 0
self.step_separation_s: float = 0
self.do_dry_run: bool = False
# other parameters shared with UI
self.devices_seen: List[str] = []
self.device: str = ""
self.controller_fifo_overrun_error: bool = False
self.controller_response_error: bool = False
# following parameters are computed from above parameters
self.axis_x_sampling_start: Point3D = Point3D(0, 0, 0)
self.axis_y_sampling_start: Point3D = Point3D(0, 0, 0)
self.axis_z_sampling_start: Point3D = Point3D(0, 0, 0)
# recording runner: once constructed before invocation all properties shall be updated
self.data_recording_runner: Optional[RecordStepSeriesRunner] = None
self.data_processing_runner: Optional[DataPostProcessRunner] = None
@staticmethod
def _get_devices() -> Tuple[str, List[str]]:
"""
:return: tuple of primary device (if any) and list of all devices
"""
seen_devices: List[str] = [k for k in Py3dpAxxel.get_devices_dict().keys()]
primary: str = seen_devices[0] if len(seen_devices) > 0 else None
return primary, seen_devices
def _update_seen_devices(self):
primary, seen_devices = self._get_devices()
self._logger.debug(f"seen devices: primary={primary}, seen={seen_devices}")
self.devices_seen = seen_devices
self.device = primary if primary is not None else ""
@octoprint.plugin.BlueprintPlugin.route("/set_values", methods=["POST"])
def on_api_set_values(self):
data = flask.request.json
self._update_members_from_api(data)
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/start_recording", methods=["POST"])
def on_api_start_recording(self):
self._start_recording()
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/abort_recording", methods=["POST"])
def on_api_abort_recording(self):
self._abort_recording()
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/start_data_processing", methods=["POST"])
def on_api_start_data_processing(self):
self._start_data_processing()
response = flask.jsonify(message="OK")
response.status_code = 202
return response
@octoprint.plugin.BlueprintPlugin.route("/get_estimate", methods=["GET"])
def on_api_get_estimate(self):
return flask.jsonify({f"estimate": self._estimate_duration()})
@octoprint.plugin.BlueprintPlugin.route("/get_parameters", methods=["GET"])
def on_api_get_parameters(self):
return flask.jsonify({f"parameters": self._get_parameter_dict(flask.request.args)})
@octoprint.plugin.BlueprintPlugin.route("/get_files_listing", methods=["GET"])
def on_api_get_files_listing(self):
fs = FileSelector(os.path.join(self.get_plugin_data_folder(), ".*"))
files_details = fs.filter()
return flask.jsonify({f"files": files_details})
@octoprint.plugin.BlueprintPlugin.route("/get_stream_files_listing", methods=["GET"])
def on_api_get_stream_files_listing(self):
fs = FileSelector(os.path.join(self.get_plugin_data_folder(), f"{self.OUTPUT_STREAM_FILE_NAME_PREFIX}-.*\\.tsv$"))
files = fs.filter() | files_details = [StreamMeta(f, FilenameMetaStream().from_filename(f.filename_ext)) for f in files] | 6 | 2023-11-14 17:15:15+00:00 | 8k |
hmmbug/pythaidate | tests/test_csdate.py | [
{
"identifier": "julianday",
"path": "pythaidate/julianday.py",
"snippet": "def to_julianday(year, month, day):\ndef from_julianday(jd):\ndef today(): # pragma: no cover\ndef date_to_julianday(d):\ndef julianday_to_date(obj):\n B = 0\n A = math.trunc(yearp / 100.)\n B = 2 - A + mat... | from datetime import date, timedelta
from pythaidate import CsDate, julianday
from pythaidate.constants import CS_JULIAN_DAY_OFFSET
import json
import unittest
import os
import pathlib
import random
import logging | 5,699 |
random.seed()
this_path = pathlib.Path(__file__).parent.resolve()
for datafile in ("cs.json", "cs.min.json"):
datafile = os.path.join(this_path, "data", datafile)
if os.path.exists(datafile):
break
else:
raise FileNotFoundError("CS data file not found.")
with open(datafile) as fh:
TESTDATA = json.load(fh)
MIN_YEAR = 0 # 638 AD
MAX_YEAR = 1462 # 2100 AD
MAX_YEAR = 2362 # 3000 AD
RUN_PERCENT = 10
if os.environ.get("RUN_PERCENT"):
RUN_PERCENT = int(os.environ.get("RUN_PERCENT"))
if RUN_PERCENT > 100:
RUN_PERCENT = 100
class Test_CsDate(unittest.TestCase):
def random_dates(self, min_year=MIN_YEAR, max_year=MAX_YEAR, sample_rate_pc=None):
if sample_rate_pc is None:
sample_rate_pc = RUN_PERCENT
for y in range(min_year, max_year):
|
random.seed()
this_path = pathlib.Path(__file__).parent.resolve()
for datafile in ("cs.json", "cs.min.json"):
datafile = os.path.join(this_path, "data", datafile)
if os.path.exists(datafile):
break
else:
raise FileNotFoundError("CS data file not found.")
with open(datafile) as fh:
TESTDATA = json.load(fh)
MIN_YEAR = 0 # 638 AD
MAX_YEAR = 1462 # 2100 AD
MAX_YEAR = 2362 # 3000 AD
RUN_PERCENT = 10
if os.environ.get("RUN_PERCENT"):
RUN_PERCENT = int(os.environ.get("RUN_PERCENT"))
if RUN_PERCENT > 100:
RUN_PERCENT = 100
class Test_CsDate(unittest.TestCase):
def random_dates(self, min_year=MIN_YEAR, max_year=MAX_YEAR, sample_rate_pc=None):
if sample_rate_pc is None:
sample_rate_pc = RUN_PERCENT
for y in range(min_year, max_year): | yd = CsDate.fromyd(year=y, days=0) | 1 | 2023-11-18 21:14:01+00:00 | 8k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.