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
smrfeld/tsmixer-pytorch
utils/tsmixer.py
[ { "identifier": "TSMixerConf", "path": "utils/tsmixer_conf.py", "snippet": "class TSMixerConf(DataClassDictMixin):\n\n class Initialize(Enum):\n FROM_LATEST_CHECKPOINT = \"from-latest-checkpoint\"\n \"Load the model from the latest checkpoint\"\n\n FROM_BEST_CHECKPOINT = \"from-b...
from .tsmixer_conf import TSMixerConf, TrainingMetadata, makedirs from .model import TSMixerModel from .load_csv import DataNormalization from typing import Optional, Tuple, Dict, List from loguru import logger from tqdm import tqdm from dataclasses import dataclass from mashumaro import DataClassDictMixin import os import torch import json import time import shutil import yaml
3,367
class TSMixer: """TSMixer including training and prediction methods """ def __init__(self, conf: TSMixerConf): """Constructor for TSMixer class Args: conf (TSMixerConf): Configuration """ conf.check_valid() self.conf = conf # Create the model self.model = TSMixerModel( input_length=self.conf.input_length, forecast_length=self.conf.prediction_length, no_feats=self.conf.no_features, feat_mixing_hidden_channels=self.conf.feat_mixing_hidden_channels or self.conf.no_features, no_mixer_layers=self.conf.no_mixer_layers, dropout=self.conf.dropout ) # Move to device self.model.to(self.conf.device) # Load the model if self.conf.initialize == self.conf.Initialize.FROM_LATEST_CHECKPOINT: self.load_checkpoint(fname=self.conf.checkpoint_latest) elif self.conf.initialize == self.conf.Initialize.FROM_BEST_CHECKPOINT: self.load_checkpoint(fname=self.conf.checkpoint_best) elif self.conf.initialize == self.conf.Initialize.FROM_SCRATCH: pass else: raise NotImplementedError(f"Initialize {self.conf.initialize} not implemented") def load_checkpoint(self, fname: str, optimizer: Optional[torch.optim.Optimizer] = None) -> Tuple[int,float]: """Load a checkpoint, optionally including the optimizer state Args: fname (str): File name optimizer (Optional[torch.optim.Optimizer], optional): Optimizer to update from checkpoint. Defaults to None. Returns: Tuple[int,float]: Epoch and loss """ logger.debug(f"Loading model weights from {fname}") checkpoint = torch.load(fname) self.model.load_state_dict(checkpoint['model_state_dict']) if optimizer is not None: logger.debug(f"Loading optimizer state from {fname}") optimizer.load_state_dict(checkpoint['optimizer_state_dict']) epoch = checkpoint['epoch'] loss = checkpoint['loss'] logger.info(f"Loaded optimizer state from epoch {epoch} with loss {loss}") return epoch, loss def predict(self, batch_input: torch.Tensor) -> torch.Tensor: """Predict the output for a batch of input data Args: batch_input (torch.Tensor): Input data of shape (batch_size, input_length (time), no_features) Returns: torch.Tensor: Predicted output of shape (batch_size, prediction_length (time), no_features) """ self.model.eval() # Check size assert batch_input.shape[1] == self.conf.input_length, f"Input length {batch_input.shape[1]} does not match configuration {self.conf.input_length}" assert batch_input.shape[2] == self.conf.no_features, f"Number of features {batch_input.shape[2]} does not match configuration {self.conf.no_features}" # Predict batch_input = batch_input.to(self.conf.device) with torch.no_grad(): batch_pred_hat = self.model(batch_input) return batch_pred_hat
class TSMixer: """TSMixer including training and prediction methods """ def __init__(self, conf: TSMixerConf): """Constructor for TSMixer class Args: conf (TSMixerConf): Configuration """ conf.check_valid() self.conf = conf # Create the model self.model = TSMixerModel( input_length=self.conf.input_length, forecast_length=self.conf.prediction_length, no_feats=self.conf.no_features, feat_mixing_hidden_channels=self.conf.feat_mixing_hidden_channels or self.conf.no_features, no_mixer_layers=self.conf.no_mixer_layers, dropout=self.conf.dropout ) # Move to device self.model.to(self.conf.device) # Load the model if self.conf.initialize == self.conf.Initialize.FROM_LATEST_CHECKPOINT: self.load_checkpoint(fname=self.conf.checkpoint_latest) elif self.conf.initialize == self.conf.Initialize.FROM_BEST_CHECKPOINT: self.load_checkpoint(fname=self.conf.checkpoint_best) elif self.conf.initialize == self.conf.Initialize.FROM_SCRATCH: pass else: raise NotImplementedError(f"Initialize {self.conf.initialize} not implemented") def load_checkpoint(self, fname: str, optimizer: Optional[torch.optim.Optimizer] = None) -> Tuple[int,float]: """Load a checkpoint, optionally including the optimizer state Args: fname (str): File name optimizer (Optional[torch.optim.Optimizer], optional): Optimizer to update from checkpoint. Defaults to None. Returns: Tuple[int,float]: Epoch and loss """ logger.debug(f"Loading model weights from {fname}") checkpoint = torch.load(fname) self.model.load_state_dict(checkpoint['model_state_dict']) if optimizer is not None: logger.debug(f"Loading optimizer state from {fname}") optimizer.load_state_dict(checkpoint['optimizer_state_dict']) epoch = checkpoint['epoch'] loss = checkpoint['loss'] logger.info(f"Loaded optimizer state from epoch {epoch} with loss {loss}") return epoch, loss def predict(self, batch_input: torch.Tensor) -> torch.Tensor: """Predict the output for a batch of input data Args: batch_input (torch.Tensor): Input data of shape (batch_size, input_length (time), no_features) Returns: torch.Tensor: Predicted output of shape (batch_size, prediction_length (time), no_features) """ self.model.eval() # Check size assert batch_input.shape[1] == self.conf.input_length, f"Input length {batch_input.shape[1]} does not match configuration {self.conf.input_length}" assert batch_input.shape[2] == self.conf.no_features, f"Number of features {batch_input.shape[2]} does not match configuration {self.conf.no_features}" # Predict batch_input = batch_input.to(self.conf.device) with torch.no_grad(): batch_pred_hat = self.model(batch_input) return batch_pred_hat
def load_data_norm(self) -> Optional[DataNormalization]:
4
2023-11-18 19:56:18+00:00
4k
CV-Reimplementation/Ucolor-Reimplementation
data/data_RGB.py
[ { "identifier": "DataLoaderTrain", "path": "data/dataset_RGB.py", "snippet": "class DataLoaderTrain(Dataset):\n def __init__(self, rgb_dir, inp='input', target='target', img_options=None):\n super(DataLoaderTrain, self).__init__()\n\n inp_files = sorted(os.listdir(os.path.join(rgb_dir, ...
import os from .dataset_RGB import DataLoaderTrain, DataLoaderVal, DataLoaderTest
1,714
def get_training_data(rgb_dir, inp, target, img_options): assert os.path.exists(rgb_dir) return DataLoaderTrain(rgb_dir, inp, target, img_options) def get_validation_data(rgb_dir, inp, target, img_options): assert os.path.exists(rgb_dir)
def get_training_data(rgb_dir, inp, target, img_options): assert os.path.exists(rgb_dir) return DataLoaderTrain(rgb_dir, inp, target, img_options) def get_validation_data(rgb_dir, inp, target, img_options): assert os.path.exists(rgb_dir)
return DataLoaderVal(rgb_dir, inp, target, img_options)
1
2023-11-14 05:40:54+00:00
4k
ottuco/multi-api-mocker
tests/test_utils.py
[ { "identifier": "MockAPIResponse", "path": "multi_api_mocker/definitions.py", "snippet": "class MockAPIResponse:\n \"\"\"\n Represents a mock response for an API endpoint, encapsulating details such as\n the response data, status code, and any associated exceptions. It is designed\n to be su...
from multi_api_mocker.definitions import MockAPIResponse from multi_api_mocker.models import MockConfiguration, ResponseKwargs from multi_api_mocker.utils import group_by_url
2,333
# Test grouping with a single mock def test_group_by_url_single_mock(): mock_response = MockAPIResponse( url="https://example.com/api", method="GET", status_code=200, json={"key": "value"}, ) # Create an instance of ResponseKwargs response_kwargs = ResponseKwargs(status_code=200, json={"key": "value"}) expected = [
# Test grouping with a single mock def test_group_by_url_single_mock(): mock_response = MockAPIResponse( url="https://example.com/api", method="GET", status_code=200, json={"key": "value"}, ) # Create an instance of ResponseKwargs response_kwargs = ResponseKwargs(status_code=200, json={"key": "value"}) expected = [
MockConfiguration(
1
2023-11-12 08:01:06+00:00
4k
Jisencc/yolov5_dual_weighting
utils/augmentations.py
[ { "identifier": "LOGGER", "path": "utils/general.py", "snippet": "LOGGER = logging.getLogger(LOGGING_NAME) # define globally (used in train.py, val.py, detect.py, etc.)" }, { "identifier": "check_version", "path": "utils/general.py", "snippet": "def check_version(current='0.0.0', minimu...
import math import random import cv2 import numpy as np import torch import torchvision.transforms as T import torchvision.transforms.functional as TF import albumentations as A import albumentations as A from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy from utils.metrics import bbox_ioa from albumentations.pytorch import ToTensorV2
1,788
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Image augmentation functions """ IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation class Albumentations: # YOLOv5 Albumentations class (optional, only used if package is installed) def __init__(self, size=640): self.transform = None prefix = colorstr('albumentations: ') try: check_version(A.__version__, '1.0.3', hard=True) # version requirement T = [ A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0), A.Blur(p=0.01), A.MedianBlur(p=0.01), A.ToGray(p=0.01), A.CLAHE(p=0.01), A.RandomBrightnessContrast(p=0.0), A.RandomGamma(p=0.0), A.ImageCompression(quality_lower=75, p=0.0)] # transforms self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Image augmentation functions """ IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation class Albumentations: # YOLOv5 Albumentations class (optional, only used if package is installed) def __init__(self, size=640): self.transform = None prefix = colorstr('albumentations: ') try: check_version(A.__version__, '1.0.3', hard=True) # version requirement T = [ A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0), A.Blur(p=0.01), A.MedianBlur(p=0.01), A.ToGray(p=0.01), A.CLAHE(p=0.01), A.RandomBrightnessContrast(p=0.0), A.RandomGamma(p=0.0), A.ImageCompression(quality_lower=75, p=0.0)] # transforms self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
0
2023-11-12 13:28:26+00:00
4k
WU-CVGL/BAD-NeRFstudio
badnerf/cameras/badnerf_camera_optimizer.py
[ { "identifier": "linear_interpolation", "path": "badnerf/cameras/spline.py", "snippet": "def linear_interpolation(\n start_pose: Float[LieTensor, \"*batch_size 7\"],\n end_pose: Float[LieTensor, \"*batch_size 7\"],\n u: Float[Tensor, \"interpolations\"],\n) -> Tuple[\n Float[LieT...
import functools import pypose as pp import torch from typing import Literal, Optional, Tuple, Type, Union from dataclasses import dataclass, field from jaxtyping import Float, Int from pypose import LieTensor from torch import Tensor, nn from typing_extensions import assert_never from nerfstudio.cameras.rays import RayBundle from nerfstudio.configs.base_config import InstantiateConfig from badnerf.cameras.spline import linear_interpolation, linear_interpolation_mid
1,875
mode: Literal["off", "linear", "bspline"] = "off" """Pose optimization strategy to use. linear: linear interpolation on SE(3); bspline: cubic b-spline interpolation on SE(3).""" num_virtual_views: int = 10 """The number of samples used to model the motion-blurring.""" initial_noise_se3_std: float = 1e-5 """Initial perturbation to pose delta on se(3). Must be non-zero to prevent NaNs.""" class BadNerfCameraOptimizer(nn.Module): """Optimization for BAD-NeRF virtual camera trajectories.""" config: BadNerfCameraOptimizerConfig def __init__( self, config: BadNerfCameraOptimizerConfig, num_cameras: int, device: Union[torch.device, str], non_trainable_camera_indices: Optional[Int[Tensor, "num_non_trainable_cameras"]] = None, **kwargs, ) -> None: super().__init__() self.config = config self.num_cameras = num_cameras self.device = device self.non_trainable_camera_indices = non_trainable_camera_indices self.dof = 6 # Initialize learnable parameters. if self.config.mode == "off": pass elif self.config.mode == "linear": self.num_control_knots = 2 elif self.config.mode == "cubic": self.num_control_knots = 4 else: assert_never(self.config.mode) self.pose_adjustment = pp.Parameter( pp.randn_se3( (num_cameras, self.num_control_knots), sigma=self.config.initial_noise_se3_std, device=device, ), ) def forward( self, indices: Int[Tensor, "camera_indices"], ) -> Float[Tensor, "camera_indices self.num_control_knots self.dof"]: """Indexing into camera adjustments. Args: indices: indices of Cameras to optimize. Returns: Transformation matrices from optimized camera coordinates to given camera coordinates. """ outputs = [] # Apply learned transformation delta. if self.config.mode == "off": pass else: outputs.append(self.pose_adjustment.Exp()[indices.int(), :]) # Detach non-trainable indices by setting to identity transform if ( torch.is_grad_enabled() and self.non_trainable_camera_indices is not None and len(indices) > len(self.non_trainable_camera_indices) ): if self.non_trainable_camera_indices.device != self.pose_adjustment.device: self.non_trainable_camera_indices = self.non_trainable_camera_indices.to(self.pose_adjustment.device) nt = self.non_trainable_camera_indices outputs[0][nt] = outputs[0][nt].clone().detach() # Return: identity if no transforms are needed, otherwise composite transforms together. if len(outputs) == 0: if self.config.mode == "linear": return pp.identity_SE3( *(indices.shape[0], self.num_control_knots), device=self.pose_adjustment.device ) else: assert_never(self.config.mode) return functools.reduce(pp.mul, outputs) def spline_interpolation_bundle( self, camera_indices: Int[Tensor, "num_rays"] ) -> Tuple[ Float[LieTensor, "num_rays num_virtual_views 4"], Float[Tensor, "num_rays num_virtual_views 3"] ]: """ Interpolate camera poses for each ray in the bundle. """ camera_opt = self(camera_indices) camera_opt_to_camera_start = camera_opt[:, 0, :] camera_opt_to_camera_end = camera_opt[:, 1, :] q, t = linear_interpolation( camera_opt_to_camera_start, camera_opt_to_camera_end, torch.linspace(0, 1, self.config.num_virtual_views, device=camera_opt_to_camera_start.device) ) return q, t def spline_interpolation_mid( self, camera_indices: Int[Tensor, "num_rays"] ) -> Tuple[ Float[LieTensor, "num_rays 4"], Float[Tensor, "num_rays 3"] ]: """ Get median camera poses for each ray in the bundle. """ camera_opt = self(camera_indices) camera_opt_to_camera_start = camera_opt[:, 0, :] camera_opt_to_camera_end = camera_opt[:, 1, :]
""" Pose and Intrinsics Optimizers """ from __future__ import annotations @dataclass class BadNerfCameraOptimizerConfig(InstantiateConfig): """Configuration of BAD-NeRF camera optimizer.""" _target: Type = field(default_factory=lambda: BadNerfCameraOptimizer) """The target class to be instantiated.""" mode: Literal["off", "linear", "bspline"] = "off" """Pose optimization strategy to use. linear: linear interpolation on SE(3); bspline: cubic b-spline interpolation on SE(3).""" num_virtual_views: int = 10 """The number of samples used to model the motion-blurring.""" initial_noise_se3_std: float = 1e-5 """Initial perturbation to pose delta on se(3). Must be non-zero to prevent NaNs.""" class BadNerfCameraOptimizer(nn.Module): """Optimization for BAD-NeRF virtual camera trajectories.""" config: BadNerfCameraOptimizerConfig def __init__( self, config: BadNerfCameraOptimizerConfig, num_cameras: int, device: Union[torch.device, str], non_trainable_camera_indices: Optional[Int[Tensor, "num_non_trainable_cameras"]] = None, **kwargs, ) -> None: super().__init__() self.config = config self.num_cameras = num_cameras self.device = device self.non_trainable_camera_indices = non_trainable_camera_indices self.dof = 6 # Initialize learnable parameters. if self.config.mode == "off": pass elif self.config.mode == "linear": self.num_control_knots = 2 elif self.config.mode == "cubic": self.num_control_knots = 4 else: assert_never(self.config.mode) self.pose_adjustment = pp.Parameter( pp.randn_se3( (num_cameras, self.num_control_knots), sigma=self.config.initial_noise_se3_std, device=device, ), ) def forward( self, indices: Int[Tensor, "camera_indices"], ) -> Float[Tensor, "camera_indices self.num_control_knots self.dof"]: """Indexing into camera adjustments. Args: indices: indices of Cameras to optimize. Returns: Transformation matrices from optimized camera coordinates to given camera coordinates. """ outputs = [] # Apply learned transformation delta. if self.config.mode == "off": pass else: outputs.append(self.pose_adjustment.Exp()[indices.int(), :]) # Detach non-trainable indices by setting to identity transform if ( torch.is_grad_enabled() and self.non_trainable_camera_indices is not None and len(indices) > len(self.non_trainable_camera_indices) ): if self.non_trainable_camera_indices.device != self.pose_adjustment.device: self.non_trainable_camera_indices = self.non_trainable_camera_indices.to(self.pose_adjustment.device) nt = self.non_trainable_camera_indices outputs[0][nt] = outputs[0][nt].clone().detach() # Return: identity if no transforms are needed, otherwise composite transforms together. if len(outputs) == 0: if self.config.mode == "linear": return pp.identity_SE3( *(indices.shape[0], self.num_control_knots), device=self.pose_adjustment.device ) else: assert_never(self.config.mode) return functools.reduce(pp.mul, outputs) def spline_interpolation_bundle( self, camera_indices: Int[Tensor, "num_rays"] ) -> Tuple[ Float[LieTensor, "num_rays num_virtual_views 4"], Float[Tensor, "num_rays num_virtual_views 3"] ]: """ Interpolate camera poses for each ray in the bundle. """ camera_opt = self(camera_indices) camera_opt_to_camera_start = camera_opt[:, 0, :] camera_opt_to_camera_end = camera_opt[:, 1, :] q, t = linear_interpolation( camera_opt_to_camera_start, camera_opt_to_camera_end, torch.linspace(0, 1, self.config.num_virtual_views, device=camera_opt_to_camera_start.device) ) return q, t def spline_interpolation_mid( self, camera_indices: Int[Tensor, "num_rays"] ) -> Tuple[ Float[LieTensor, "num_rays 4"], Float[Tensor, "num_rays 3"] ]: """ Get median camera poses for each ray in the bundle. """ camera_opt = self(camera_indices) camera_opt_to_camera_start = camera_opt[:, 0, :] camera_opt_to_camera_end = camera_opt[:, 1, :]
q, t = linear_interpolation_mid(
1
2023-11-10 07:40:22+00:00
4k
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
2,977
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)
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)
3
2023-11-13 10:26:11+00:00
4k
nttcom/WASB-SBDT
src/losses/heatmap.py
[ { "identifier": "BCELoss", "path": "src/losses/bce.py", "snippet": "class BCELoss(nn.Module):\n '''\n weighted binary cross-entropy loss proposed in https://ieeexplore.ieee.org/document/9302757\n (probably) this is exactly the same with focal loss cf. https://arxiv.org/abs/1708.02002 with gamma...
from torch import nn from .bce import BCELoss from .wbce import WBCELoss from .focal_loss import BinaryFocalLoss from .dice_loss import DiceLoss from .combo_loss import ComboLoss from .quality_focal_loss import QualityFocalLoss from utils.utils import _sigmoid
3,275
class HeatmapLoss(nn.Module): def __init__(self, cfg): super().__init__() loss_name = cfg['loss']['sub_name'] if loss_name=='mse': self._loss = nn.MSELoss() elif loss_name=='bce': #self._loss = nn.BCELoss()
class HeatmapLoss(nn.Module): def __init__(self, cfg): super().__init__() loss_name = cfg['loss']['sub_name'] if loss_name=='mse': self._loss = nn.MSELoss() elif loss_name=='bce': #self._loss = nn.BCELoss()
self._loss = BCELoss()
0
2023-11-15 02:11:00+00:00
4k
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
3,174
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
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])
1
2023-11-14 20:29:11+00:00
4k
barkure/white-dove-backend
routers/user_router.py
[ { "identifier": "is_token_valid", "path": "services/auth_utils.py", "snippet": "def is_token_valid(token: str):\n try:\n payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n exp_timestamp = payload.get(\"exp\")\n current_time = datetime.utcnow()\n exp_datetime...
from fastapi import APIRouter from services.auth_utils import is_token_valid from services.users import create_user, get_user, update_user, delete_user, get_all_users, login, github_oauth, unbind_github_oauth, update_blogName from config import GITHUB_OAUTH_URL
1,936
# 创建一个APIRouter实例 router = APIRouter() # 创建用户 @router.post("/create_user") async def create_user_endpoint(payload: dict): response = create_user(payload) return response # 获取用户 @router.post("/get_user") async def get_user_endpoint(payload: dict): response = get_user(payload) return response # 更新用户 @router.post("/update_user") async def update_user_endpoint(payload: dict):
# 创建一个APIRouter实例 router = APIRouter() # 创建用户 @router.post("/create_user") async def create_user_endpoint(payload: dict): response = create_user(payload) return response # 获取用户 @router.post("/get_user") async def get_user_endpoint(payload: dict): response = get_user(payload) return response # 更新用户 @router.post("/update_user") async def update_user_endpoint(payload: dict):
response = update_user(payload)
3
2023-11-11 04:46:58+00:00
4k
globality-corp/deboiler
deboiler/lxml_query.py
[ { "identifier": "LxmlNode", "path": "deboiler/models/lxml_node.py", "snippet": "class LxmlNode:\n \"\"\"\n A wrapper around an Lxml _Element node that owns several method to extract\n title, text, headings, lists, breadcrumbs, etc.\n \"\"\"\n\n def __init__(self, node: Union[_ElementTree,...
from deboiler.models.lxml_node import LxmlNode, LxmlTree from deboiler.models.tag import TagDefinition
3,435
# Tags to identify candidate subtrees # ("div", False) - tag name should be exactly 'div' # ("navigation", True) - tag name should contain 'navigation' CANDIDATE_SUBTREE_TAGS = [ TagDefinition("div", partial_match=False), TagDefinition("nav", partial_match=False), TagDefinition("form"), TagDefinition("navigation"), TagDefinition("footer"), TagDefinition("header"), TagDefinition("menu"), TagDefinition("top"), TagDefinition("bottom"), TagDefinition("left"), TagDefinition("right"), ] def construct_query(): # e.g. nodes of type 'nav' (exact match) or type containing 'navigation' # //*[self::nav or contains(local-name(), 'navigation')] shared_tags_query = " or ".join(tag.to_xpath() for tag in CANDIDATE_SUBTREE_TAGS) return f"//*[{shared_tags_query}]"
# Tags to identify candidate subtrees # ("div", False) - tag name should be exactly 'div' # ("navigation", True) - tag name should contain 'navigation' CANDIDATE_SUBTREE_TAGS = [ TagDefinition("div", partial_match=False), TagDefinition("nav", partial_match=False), TagDefinition("form"), TagDefinition("navigation"), TagDefinition("footer"), TagDefinition("header"), TagDefinition("menu"), TagDefinition("top"), TagDefinition("bottom"), TagDefinition("left"), TagDefinition("right"), ] def construct_query(): # e.g. nodes of type 'nav' (exact match) or type containing 'navigation' # //*[self::nav or contains(local-name(), 'navigation')] shared_tags_query = " or ".join(tag.to_xpath() for tag in CANDIDATE_SUBTREE_TAGS) return f"//*[{shared_tags_query}]"
def get_candidate_nodes(parsed_content: LxmlTree) -> list[LxmlNode]:
0
2023-11-17 23:11:45+00:00
4k
jusiro/CLAP
datasets/caltech101.py
[ { "identifier": "OxfordPets", "path": "datasets/oxford_pets.py", "snippet": "class OxfordPets(DatasetBase):\n\n dataset_dir = \"oxford_pets\"\n\n def __init__(self, cfg):\n root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT))\n self.dataset_dir = os.path.join(root, self.datas...
import os import pickle from dassl.data.datasets import DATASET_REGISTRY, Datum, DatasetBase from dassl.utils import mkdir_if_missing from .oxford_pets import OxfordPets from .dtd import DescribableTextures as DTD
2,891
IGNORED = ["BACKGROUND_Google", "Faces_easy"] NEW_CNAMES = { "airplanes": "airplane", "Faces": "face", "Leopards": "leopard", "Motorbikes": "motorbike", } @DATASET_REGISTRY.register() class Caltech101(DatasetBase): dataset_dir = "caltech-101" def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, "101_ObjectCategories") self.split_path = os.path.join(self.dataset_dir, "split_zhou_Caltech101.json") self.split_fewshot_dir = os.path.join(self.dataset_dir, "split_fewshot") mkdir_if_missing(self.split_fewshot_dir) if os.path.exists(self.split_path): train, val, test = OxfordPets.read_split(self.split_path, self.image_dir) else:
IGNORED = ["BACKGROUND_Google", "Faces_easy"] NEW_CNAMES = { "airplanes": "airplane", "Faces": "face", "Leopards": "leopard", "Motorbikes": "motorbike", } @DATASET_REGISTRY.register() class Caltech101(DatasetBase): dataset_dir = "caltech-101" def __init__(self, cfg): root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = os.path.join(root, self.dataset_dir) self.image_dir = os.path.join(self.dataset_dir, "101_ObjectCategories") self.split_path = os.path.join(self.dataset_dir, "split_zhou_Caltech101.json") self.split_fewshot_dir = os.path.join(self.dataset_dir, "split_fewshot") mkdir_if_missing(self.split_fewshot_dir) if os.path.exists(self.split_path): train, val, test = OxfordPets.read_split(self.split_path, self.image_dir) else:
train, val, test = DTD.read_and_split_data(self.image_dir, ignored=IGNORED, new_cnames=NEW_CNAMES)
0
2023-11-17 21:00:56+00:00
4k
solovieff/kibernikto
kibernikto/telegram/channel/gnews/publisher.py
[ { "identifier": "constants", "path": "kibernikto/constants.py", "snippet": "TG_MASTER_ID = int(os.environ['TG_MASTER_ID'])\nTG_BOT_KEY = os.environ['TG_BOT_KEY']\nTG_REACTION_CALLS = os.environ.get('TG_REACTION_CALLS', \"никто, падаль, хонда\")\nTG_REACTION_CALLS = \"\".join(TG_REACTION_CALLS.split())\n...
import asyncio import json import logging import traceback import yaml from json import JSONDecodeError from random import shuffle from xml.sax.saxutils import quoteattr from kibernikto import constants from openai import AsyncOpenAI from openai.types.chat import ChatCompletion from kibernikto.telegram.channel.gnews.retriever import GroundNewsItem, get_by_interest, get_main_events, \ get_blindspots
3,187
default_interests = constants.TG_CHANNEL_INTERESTS __to_publish_ids = set() __to_publish = [] __published_ids = set() __client_async = None __model = "gpt-4-1106-preview" __system_message = { 'role': 'system', 'content': """ Starting now you are Kibernikto, a powerful member of a secret masonic lodge. Kibernikto jokes in a sinister manner and sometimes says dirty words. Kibernikto manner of speech is very cynic, arrogant and sarcastic. Kibernikto speaks russian only always and in the first person! If he sees another language -- he translates to russian. Kibernikto never says anything bad about Russia, russian president, army or allies. Kibernikto does not speak war slogans. Kibernikto never laughts openly at people suffer. Kibernikto understands all the global political intrigue and backstabbing and takes this into account when answering. Kibernikto does not use additional markup and changes double quotes inside his texts and translations to single ones! """ } POST_PUBLISH_REQUEST = """ Here go your tasks with this YAML representing the event coverage in different media (left, center, right): 1) Create additional "intrigue_west" field. 1.1) Put your cynic, arrogant and sarcastic thoughts about the article subject and media sentiments in russian to the new "intrigue_west" field. Dont forget that media can easily lie! Don't be too concise. 2) Create additional "intrigue_rus" field. 2.1) Put pro-russian biased summary in intelligent manner to "intrigue_rus" field. 2) Translate the property values of resulting YAML to russian in a ridiculous manner. Leave the key names in english! 3) Return result data YAML only. Result example: title: translated title description: translated description intrigue_west: summary intrigue_rus: russian biased summary summaries: translated summaries values if present """ async def load_news(main=True, interests=True, blindspot=False): logging.info("Loading the news...") if main:
default_interests = constants.TG_CHANNEL_INTERESTS __to_publish_ids = set() __to_publish = [] __published_ids = set() __client_async = None __model = "gpt-4-1106-preview" __system_message = { 'role': 'system', 'content': """ Starting now you are Kibernikto, a powerful member of a secret masonic lodge. Kibernikto jokes in a sinister manner and sometimes says dirty words. Kibernikto manner of speech is very cynic, arrogant and sarcastic. Kibernikto speaks russian only always and in the first person! If he sees another language -- he translates to russian. Kibernikto never says anything bad about Russia, russian president, army or allies. Kibernikto does not speak war slogans. Kibernikto never laughts openly at people suffer. Kibernikto understands all the global political intrigue and backstabbing and takes this into account when answering. Kibernikto does not use additional markup and changes double quotes inside his texts and translations to single ones! """ } POST_PUBLISH_REQUEST = """ Here go your tasks with this YAML representing the event coverage in different media (left, center, right): 1) Create additional "intrigue_west" field. 1.1) Put your cynic, arrogant and sarcastic thoughts about the article subject and media sentiments in russian to the new "intrigue_west" field. Dont forget that media can easily lie! Don't be too concise. 2) Create additional "intrigue_rus" field. 2.1) Put pro-russian biased summary in intelligent manner to "intrigue_rus" field. 2) Translate the property values of resulting YAML to russian in a ridiculous manner. Leave the key names in english! 3) Return result data YAML only. Result example: title: translated title description: translated description intrigue_west: summary intrigue_rus: russian biased summary summaries: translated summaries values if present """ async def load_news(main=True, interests=True, blindspot=False): logging.info("Loading the news...") if main:
events = await get_main_events(known_ids=__published_ids.union(__to_publish_ids))
3
2023-11-11 18:39:28+00:00
4k
leeyuentuen/tibber_ev
custom_components/tibber_ev/sensor.py
[ { "identifier": "MAX_CHARGE_RANGE", "path": "custom_components/tibber_ev/const.py", "snippet": "MAX_CHARGE_RANGE = 375" }, { "identifier": "TibberEVEntity", "path": "custom_components/tibber_ev/entity.py", "snippet": "class TibberEVEntity(Entity):\n\n def __init__(self, device: Tibber...
import logging from typing import Final from dataclasses import dataclass from datetime import timedelta from .const import MAX_CHARGE_RANGE from .entity import TibberEVEntity from homeassistant.helpers.typing import StateType from homeassistant import const from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.components.sensor import ( SensorEntity, SensorEntityDescription, SensorStateClass, SensorDeviceClass ) from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers import entity_platform from . import DOMAIN as TIBBER_EV_DOMAIN from .tibber import Tibber, TibberApi from homeassistant.const import ( PERCENTAGE, )
1,697
round_digits=None, state_class=SensorStateClass.TOTAL, device_class=SensorDeviceClass.BATTERY, ), TibberSensorDescription( key="last_seen", name="last seen", icon="mdi:eye", path="lastSeen", subpath=None, unit=None, round_digits=None, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.TIMESTAMP, ), TibberSensorDescription( key="last_seen_text", name="last seen text", icon="mdi:eye", path="lastSeenText", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="is_charging", name="is charging", icon="mdi:battery-charging", path="battery", subpath="isCharging", unit=None, round_digits=None, ), TibberSensorDescription( key="shortName", name="shortname", icon="mdi:rename-outline", path="shortName", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="full_name", name="full name", icon="mdi:car", path="name", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="is_alive", name="Is alive", icon="mdi:shield-account", path="isAlive", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="schedule", name="schedule", icon="mdi:battery-clock", path="schedule", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="id", name="id", icon="mdi:car", path="id", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="range", name="Range", icon="mdi:map-marker-distance", path=None, subpath=None, unit="km", round_digits=0, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.DISTANCE, ), ) async def async_setup_platform( hass: HomeAssistant, config: ConfigEntry, async_add_entities: AddEntitiesCallback, discovery_info=None): pass async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback): """Set up using config_entry.""" # get the device tibberApi: TibberApi tibberApi = hass.data[TIBBER_EV_DOMAIN][entry.entry_id] ev_data = await tibberApi.get_ev_data() for ev in ev_data: device = Tibber(hass, ev, tibberApi) device.raw_data = ev # get the name of the raw_data sensors = [ TibberSensor(device, description) for description in TIBBER_SENSOR_TYPES ] async_add_entities(sensors) platform = entity_platform.current_platform.get()
_LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(seconds=15) @dataclass class TibberSensorDescriptionMixin: """Define an entity description mixin for sensor entities.""" path: str subpath: str | None unit: str round_digits: int | None unit: str | None @dataclass class TibberSensorDescription( SensorEntityDescription, TibberSensorDescriptionMixin ): """Class to describe an Tibber sensor entity.""" TIBBER_SENSOR_TYPES: Final[tuple[TibberSensorDescription, ...]] = ( TibberSensorDescription( key="battery_soc", name="battery soc", path="battery", subpath="percent", unit=PERCENTAGE, round_digits=None, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.BATTERY, ), TibberSensorDescription( key="battery_charge_limit", name="battery charge limit", icon="mdi:battery-plus-variant", path="battery", subpath="chargeLimit", unit=PERCENTAGE, round_digits=None, state_class=SensorStateClass.TOTAL, device_class=SensorDeviceClass.BATTERY, ), TibberSensorDescription( key="last_seen", name="last seen", icon="mdi:eye", path="lastSeen", subpath=None, unit=None, round_digits=None, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.TIMESTAMP, ), TibberSensorDescription( key="last_seen_text", name="last seen text", icon="mdi:eye", path="lastSeenText", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="is_charging", name="is charging", icon="mdi:battery-charging", path="battery", subpath="isCharging", unit=None, round_digits=None, ), TibberSensorDescription( key="shortName", name="shortname", icon="mdi:rename-outline", path="shortName", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="full_name", name="full name", icon="mdi:car", path="name", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="is_alive", name="Is alive", icon="mdi:shield-account", path="isAlive", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="schedule", name="schedule", icon="mdi:battery-clock", path="schedule", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="id", name="id", icon="mdi:car", path="id", subpath=None, unit=None, round_digits=None, ), TibberSensorDescription( key="range", name="Range", icon="mdi:map-marker-distance", path=None, subpath=None, unit="km", round_digits=0, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.DISTANCE, ), ) async def async_setup_platform( hass: HomeAssistant, config: ConfigEntry, async_add_entities: AddEntitiesCallback, discovery_info=None): pass async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback): """Set up using config_entry.""" # get the device tibberApi: TibberApi tibberApi = hass.data[TIBBER_EV_DOMAIN][entry.entry_id] ev_data = await tibberApi.get_ev_data() for ev in ev_data: device = Tibber(hass, ev, tibberApi) device.raw_data = ev # get the name of the raw_data sensors = [ TibberSensor(device, description) for description in TIBBER_SENSOR_TYPES ] async_add_entities(sensors) platform = entity_platform.current_platform.get()
class TibberSensor(TibberEVEntity, SensorEntity):
1
2023-11-14 18:59:47+00:00
4k
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
3,386
# 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. """
# 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(
4
2023-11-13 08:19:53+00:00
4k
svetlovtech/gptize
gptize/gptizer.py
[ { "identifier": "File", "path": "gptize/models.py", "snippet": "class File:\n \"\"\"Class representing a file in the project.\"\"\"\n def __init__(self, file_name: str, directory: str):\n self.file_name = file_name\n self.directory = directory\n self.content = \"\"\n se...
import logging import os import pathspec from .models import File, Project from .settings import Settings from .output_builder import OutputBuilder
2,075
specified in .gitignore are not included. Parameters: root_path (str): The path to the root of the directory to be processed. Raises: FileNotFoundError: If the specified directory does not exist. Exception: For any other issues encountered during the directory processing. """ project_name = os.path.basename(root_path) self._project = Project(project_name, root_path) self._gitignore = self.load_gitignore(root_path) self.populate_files() def process_file(self, file_path: str): """ Processes a single file. This method creates a Project object for the file, treating the file as an individual project. It bypasses .gitignore processing, as it is assumed that the specific file is intentionally selected for processing. The method creates a File object for the specified file, reads its content, and adds it to the project's file list. It handles binary and text files accordingly. Parameters: file_path (str): The path to the file to be processed. This includes both the directory path and file name. Raises: FileNotFoundError: If the specified file does not exist. IOError: If there is an issue reading the file. Exception: For any other unexpected issues encountered during file processing. """ root_path, file_name = os.path.split(file_path) project_name = os.path.basename(root_path) if root_path else 'SingleFileProject' self._project = Project(project_name, root_path or '.') self._gitignore = pathspec.PathSpec.from_lines('gitwildmatch', []) file_obj = File(file_name, file_path) self.load_file_content(file_obj) self._project.files.append(file_obj) @property def project(self) -> Project: """Property to access the project object.""" return self._project def load_gitignore(self, root_path: str) -> pathspec.PathSpec: """Load .gitignore patterns for filtering files.""" gitignore_path = os.path.join(root_path, Settings.GITIGNORE_PATH) try: with open(gitignore_path, 'r') as file: gitignore = pathspec.PathSpec.from_lines('gitwildmatch', file) logging.info(".gitignore loaded") return gitignore except FileNotFoundError: logging.warning( ".gitignore not found, all files will be processed") return pathspec.PathSpec.from_lines('gitwildmatch', []) except Exception as e: logging.error(f"An unexpected error occurred: {e}") def populate_files(self) -> None: """Populate the project with files, excluding those matched by .gitignore and inside ignored directories.""" for root, dirs, files in os.walk(self.project.root_path): dirs[:] = [d for d in dirs if d not in Settings.IGNORED_DIRECTORIES] for file_name in files: file_path = os.path.join(root, file_name) relative_path = os.path.relpath( file_path, self.project.root_path) if self._gitignore.match_file(relative_path): logging.debug(f"File {relative_path} is ignored") continue file_obj = File(file_name, relative_path) self.load_file_content(file_obj) self.project.files.append(file_obj) def load_file_content(self, file: File) -> None: try: with open(file.directory, 'rb') as f: if b'\0' in f.read(1024): file.is_binary = True logging.info(f"Binary file detected: {file.file_name}") return except IOError as e: logging.error(f"Error reading file {file.directory}: {e}") return for encoding in Settings.DEFAULT_ENCODINGS: try: with open(file.directory, 'r', encoding=encoding) as f: file.content = f.read() self.calculate_content_size(file) logging.info( f"Content of {file.file_name} loaded with encoding {encoding}") break except UnicodeDecodeError: continue except IOError as e: logging.error(f"Error reading file {file.directory}: {e}") break except Exception as e: logging.error( f"An unexpected error occurred while reading {file.file_name}: {e}") break else: logging.error( f"Failed to read {file.file_name} in any known encoding") def calculate_content_size(self, file: File) -> None: """Calculate the size of the content of a file in bytes.""" file.content_size = len(file.content.encode('utf-8')) def combine_files(self) -> str: """ Combine the content of all files into a single string using OutputBuilder, while respecting the size and token count limits. """
class GPTizer: def __init__(self): self._project = None self._gitignore = None def process_directory(self, root_path: str): """ Processes all the files within a given directory. This method initializes the Project object for the specified directory, loads the .gitignore patterns, and populates the project with files that are not ignored by .gitignore. The method traverses through the directory recursively and adds all relevant files to the project's file list, ensuring that binary files and files specified in .gitignore are not included. Parameters: root_path (str): The path to the root of the directory to be processed. Raises: FileNotFoundError: If the specified directory does not exist. Exception: For any other issues encountered during the directory processing. """ project_name = os.path.basename(root_path) self._project = Project(project_name, root_path) self._gitignore = self.load_gitignore(root_path) self.populate_files() def process_file(self, file_path: str): """ Processes a single file. This method creates a Project object for the file, treating the file as an individual project. It bypasses .gitignore processing, as it is assumed that the specific file is intentionally selected for processing. The method creates a File object for the specified file, reads its content, and adds it to the project's file list. It handles binary and text files accordingly. Parameters: file_path (str): The path to the file to be processed. This includes both the directory path and file name. Raises: FileNotFoundError: If the specified file does not exist. IOError: If there is an issue reading the file. Exception: For any other unexpected issues encountered during file processing. """ root_path, file_name = os.path.split(file_path) project_name = os.path.basename(root_path) if root_path else 'SingleFileProject' self._project = Project(project_name, root_path or '.') self._gitignore = pathspec.PathSpec.from_lines('gitwildmatch', []) file_obj = File(file_name, file_path) self.load_file_content(file_obj) self._project.files.append(file_obj) @property def project(self) -> Project: """Property to access the project object.""" return self._project def load_gitignore(self, root_path: str) -> pathspec.PathSpec: """Load .gitignore patterns for filtering files.""" gitignore_path = os.path.join(root_path, Settings.GITIGNORE_PATH) try: with open(gitignore_path, 'r') as file: gitignore = pathspec.PathSpec.from_lines('gitwildmatch', file) logging.info(".gitignore loaded") return gitignore except FileNotFoundError: logging.warning( ".gitignore not found, all files will be processed") return pathspec.PathSpec.from_lines('gitwildmatch', []) except Exception as e: logging.error(f"An unexpected error occurred: {e}") def populate_files(self) -> None: """Populate the project with files, excluding those matched by .gitignore and inside ignored directories.""" for root, dirs, files in os.walk(self.project.root_path): dirs[:] = [d for d in dirs if d not in Settings.IGNORED_DIRECTORIES] for file_name in files: file_path = os.path.join(root, file_name) relative_path = os.path.relpath( file_path, self.project.root_path) if self._gitignore.match_file(relative_path): logging.debug(f"File {relative_path} is ignored") continue file_obj = File(file_name, relative_path) self.load_file_content(file_obj) self.project.files.append(file_obj) def load_file_content(self, file: File) -> None: try: with open(file.directory, 'rb') as f: if b'\0' in f.read(1024): file.is_binary = True logging.info(f"Binary file detected: {file.file_name}") return except IOError as e: logging.error(f"Error reading file {file.directory}: {e}") return for encoding in Settings.DEFAULT_ENCODINGS: try: with open(file.directory, 'r', encoding=encoding) as f: file.content = f.read() self.calculate_content_size(file) logging.info( f"Content of {file.file_name} loaded with encoding {encoding}") break except UnicodeDecodeError: continue except IOError as e: logging.error(f"Error reading file {file.directory}: {e}") break except Exception as e: logging.error( f"An unexpected error occurred while reading {file.file_name}: {e}") break else: logging.error( f"Failed to read {file.file_name} in any known encoding") def calculate_content_size(self, file: File) -> None: """Calculate the size of the content of a file in bytes.""" file.content_size = len(file.content.encode('utf-8')) def combine_files(self) -> str: """ Combine the content of all files into a single string using OutputBuilder, while respecting the size and token count limits. """
builder = OutputBuilder()
3
2023-11-11 20:59:01+00:00
4k
civrealm/civrealm
src/civrealm/envs/freeciv_wrapper/observation_wrapper.py
[ { "identifier": "Wrapper", "path": "src/civrealm/envs/freeciv_wrapper/core.py", "snippet": "class Wrapper(gymnasium.Wrapper):\n def reset(self, *, seed=None, options=None, **kwargs):\n return self.env.reset(seed=seed, options=options, **kwargs)" }, { "identifier": "wrapper_override", ...
from collections import OrderedDict from copy import deepcopy from functools import reduce from gymnasium import spaces from civrealm.configs import fc_args from civrealm.envs.freeciv_wrapper.tensor_base_wrapper import TensorBase from civrealm.freeciv.players.diplomacy_actions import GOLD_SET from .core import Wrapper, wrapper_override from .utils import add_shape, resize_data, update import numpy as np import civrealm.freeciv.players.player_const as player_const
2,681
# Add info to city and unit from civcontroller update(obs["city"], self.unwrapped.civ_controller.city_ctrl.cities) update(obs["unit"], self.unwrapped.civ_controller.unit_ctrl.units) # update player info with dipl_state update(obs["player"], obs.get("dipl", {})) my_player_id = self.get_wrapper_attr("my_player_id") obs["dipl"] = { player: state["diplomacy_clause_map"] for player, state in obs.get("dipl", {}).items() if player != my_player_id } for player, treaty in obs["dipl"].items(): obs["dipl"][player] = self._encode_treaty(treaty, player) # remove unused fields and keep mask if given obs = { k: v for k, v in obs.items() if k in self.observation_config["filter_observation"] or k.endswith("mask") } # Add others fields and initialize obs["others_unit"] = {} obs["others_city"] = {} for field in ["unit", "city"]: for key, val in list(obs[field].items()): if val["owner"] != my_player_id: # delete others' entity from unit and city obs["others_" + field][key] = obs[field].pop(key) obs["others_player"] = { key: obs["player"].pop(key) for key in list(obs["player"].keys()) if key != my_player_id } obs["player"] = obs["player"][my_player_id] # Initialize build_cost with 0 for now obs["rules"]["build_cost"] = 0 mutable_fields = [field for field in obs.keys() if field in self.mutable_fields] immutable_fields = [ field for field in obs.keys() if field in self.immutable_fields ] ops = self.observation_config["obs_ops"] # Handle immutable # delete unused keywords and transform useful keywords def apply_ops(field): for k, val in list(obs[field].items()): if k in list(ops[field].keys()): obs[field][k] = ops[field][k](val) else: obs[field].pop(k) for field in immutable_fields: apply_ops(field) # Handle mutable # delete unused keywords and transform useful keywords def apply_ops_mutable(field): for entity_id, entity in list(obs[field].items()): for k, val in list(entity.items()): if k in list(ops[field].keys()): entity[k] = ops[field][k](val) else: entity.pop(k) for field in mutable_fields: apply_ops_mutable(field) self.others_player_ids = sorted(obs["others_player"].keys()) return obs def _embed_immutable(self, obs): immutable = { field: obs[field] for field in obs if field in self.immutable_fields } if not self.obs_initialized: for field, field_dict in immutable.items(): self.obs_layout[field] = OrderedDict( [(k, field_dict[k].shape) for k in sorted(list(field_dict.keys()))] ) for field, field_dict in immutable.items(): # check field layout is correct if tensor_debug: assert self.obs_layout[field] == { k: v.shape for k, v in field_dict.items() } obs[field] = np.concatenate( [field_dict[k] for k in sorted(list(field_dict.keys()))], axis=-1 ).astype(np.int32) return obs def _embed_mutable(self, obs): mutable = {field: obs[field] for field in obs if field in self.mutable_fields} mutable_layout = self.observation_config["obs_mutable_layout"] if not self.obs_initialized: for field, entity_dict in mutable.items(): layout = mutable_layout[field] self.obs_layout[field] = OrderedDict( [(key, layout[key]) for key in sorted(layout)] ) for field, entity_dict in mutable.items(): # for empty field, fill with zero if len(entity_dict) == 0: mutable[field] = np.zeros( [ self.observation_config["resize"][field],
tensor_debug = fc_args["debug.tensor_debug"] @wrapper_override(["observation"]) class TensorObservation(Wrapper): """ A wrapper that defines tensor observation space, transforms observations got from FreecivBaseEnv into tensor observations. Parameters ---------- env: A FreecivBaseEnv wrapped by TensorBase wrapper Attributes --------- observation_config: dict tensor observation configuration observation_space: gymnasium.spaces.Dict a gymnasium.spaces.Dict with keys speficified in configuration; observation with keywords `mask` would not be removed. obs_initialized: bool whether observation spaces has been initialized obs_layout: dict a dict that specify shapes of flattened numpy arrays in observation """ mutable_fields = [ "city", "unit", "others_city", "others_unit", "others_player", "dipl", ] immutable_fields = ["map", "rules", "player", "gov"] def __init__(self, env: TensorBase): self.obs_initialized = False self.observation_config = env.get_wrapper_attr("config") self.observation_config["resize"]["dipl"] = self.observation_config["resize"][ "others_player" ] self.obs_layout = {} self.others_player_ids = [] super().__init__(env) def observation(self, observation): """ convert observations obtained from `FreecivBaseEnv` into a dict of flattend numpy arrays. """ # in case of gameover, return None as observation if len(observation.get("player", {})) == 0: return None observation = deepcopy(observation) observation = self._merge_player_techs(observation) obs_dict = self._handle_dict(observation) obs = self._embed_immutable(deepcopy(obs_dict)) obs = self._embed_mutable(obs) if not self.obs_initialized: self.observation_space = self._infer_obs_space(obs) self.obs_initialized = True if tensor_debug: self._check_obs_layout(obs) return obs def _handle_dict(self, obs): obs["city"] = obs.get("city", {}) obs["unit"] = obs.get("unit", {}) # TODO: This should be the base env's reponsibility # Add info to city and unit from civcontroller update(obs["city"], self.unwrapped.civ_controller.city_ctrl.cities) update(obs["unit"], self.unwrapped.civ_controller.unit_ctrl.units) # update player info with dipl_state update(obs["player"], obs.get("dipl", {})) my_player_id = self.get_wrapper_attr("my_player_id") obs["dipl"] = { player: state["diplomacy_clause_map"] for player, state in obs.get("dipl", {}).items() if player != my_player_id } for player, treaty in obs["dipl"].items(): obs["dipl"][player] = self._encode_treaty(treaty, player) # remove unused fields and keep mask if given obs = { k: v for k, v in obs.items() if k in self.observation_config["filter_observation"] or k.endswith("mask") } # Add others fields and initialize obs["others_unit"] = {} obs["others_city"] = {} for field in ["unit", "city"]: for key, val in list(obs[field].items()): if val["owner"] != my_player_id: # delete others' entity from unit and city obs["others_" + field][key] = obs[field].pop(key) obs["others_player"] = { key: obs["player"].pop(key) for key in list(obs["player"].keys()) if key != my_player_id } obs["player"] = obs["player"][my_player_id] # Initialize build_cost with 0 for now obs["rules"]["build_cost"] = 0 mutable_fields = [field for field in obs.keys() if field in self.mutable_fields] immutable_fields = [ field for field in obs.keys() if field in self.immutable_fields ] ops = self.observation_config["obs_ops"] # Handle immutable # delete unused keywords and transform useful keywords def apply_ops(field): for k, val in list(obs[field].items()): if k in list(ops[field].keys()): obs[field][k] = ops[field][k](val) else: obs[field].pop(k) for field in immutable_fields: apply_ops(field) # Handle mutable # delete unused keywords and transform useful keywords def apply_ops_mutable(field): for entity_id, entity in list(obs[field].items()): for k, val in list(entity.items()): if k in list(ops[field].keys()): entity[k] = ops[field][k](val) else: entity.pop(k) for field in mutable_fields: apply_ops_mutable(field) self.others_player_ids = sorted(obs["others_player"].keys()) return obs def _embed_immutable(self, obs): immutable = { field: obs[field] for field in obs if field in self.immutable_fields } if not self.obs_initialized: for field, field_dict in immutable.items(): self.obs_layout[field] = OrderedDict( [(k, field_dict[k].shape) for k in sorted(list(field_dict.keys()))] ) for field, field_dict in immutable.items(): # check field layout is correct if tensor_debug: assert self.obs_layout[field] == { k: v.shape for k, v in field_dict.items() } obs[field] = np.concatenate( [field_dict[k] for k in sorted(list(field_dict.keys()))], axis=-1 ).astype(np.int32) return obs def _embed_mutable(self, obs): mutable = {field: obs[field] for field in obs if field in self.mutable_fields} mutable_layout = self.observation_config["obs_mutable_layout"] if not self.obs_initialized: for field, entity_dict in mutable.items(): layout = mutable_layout[field] self.obs_layout[field] = OrderedDict( [(key, layout[key]) for key in sorted(layout)] ) for field, entity_dict in mutable.items(): # for empty field, fill with zero if len(entity_dict) == 0: mutable[field] = np.zeros( [ self.observation_config["resize"][field],
*reduce(add_shape, self.obs_layout[field].values()),
2
2023-11-18 19:35:50+00:00
4k
Sheppsu/discord-ext-listening
discord/ext/listening/processing.py
[ { "identifier": "Decoder", "path": "discord/ext/listening/opus.py", "snippet": "class Decoder(BaseDecoder):\n def packet_get_nb_channels(self, data: bytes) -> int:\n return self.CHANNELS" }, { "identifier": "SILENT_FRAME", "path": "discord/ext/listening/sink.py", "snippet": "SI...
import multiprocessing import queue import struct import threading import nacl.secret from concurrent.futures import Future from typing import Dict, List, Optional, Tuple, Union from .opus import Decoder from .sink import SILENT_FRAME, AudioFrame, RawAudioData, RTCPPacket, get_audio_packet
2,783
def __init__(self, max_processes: int, *, wait_timeout: Optional[float] = 3): if max_processes < 1: raise ValueError("max_processes must be greater than 0") if wait_timeout is None or wait_timeout < 1: raise ValueError("wait_timeout must be greater than 0") self.max_processes: int = max_processes self.wait_timeout: Optional[float] = wait_timeout self._processes: Dict[int, Tuple] = {} self._wait_queue: queue.Queue = queue.Queue() self._wait_loop_running: threading.Event = threading.Event() self._lock: threading.Lock = threading.Lock() def submit(self, data: bytes, n_p: int, decode: bool, mode: str, secret_key: List[int]) -> Future: self._lock.acquire() if n_p >= self.max_processes: raise ValueError(f"n_p must be less than the maximum processes ({self.max_processes})") if n_p not in self._processes: self._spawn_process(n_p) future = Future() self._processes[n_p][0].send((data, decode, mode, secret_key)) self._wait_queue.put((n_p, future)) self._start_recv_loop() self._lock.release() return future def _spawn_process(self, n_p) -> None: conn1, conn2 = _mp_ctx.Pipe(duplex=True) process = AudioUnpacker(args=(conn2,)) process.start() self._processes[n_p] = (conn1, process) def _start_recv_loop(self) -> None: if not self._wait_loop_running.is_set(): threading.Thread(target=self._recv_loop).start() def _recv_loop(self) -> None: self._wait_loop_running.set() while True: try: n_p, future = self._wait_queue.get(timeout=self.wait_timeout) except queue.Empty: break try: ret = self._processes[n_p][0].recv() except EOFError: self._lock.acquire() self._processes.pop(n_p) self._lock.release() continue (future.set_exception if isinstance(ret, BaseException) else future.set_result)(ret) self._wait_loop_running.clear() class AudioUnpacker(_mp_ctx.Process): def __init__(self, **kwargs): super().__init__(daemon=True, **kwargs) self.secret_key: Optional[List[int]] = None self.decoders: Dict[int, Decoder] = {} def run(self) -> None: pipe = self._args[0] # type: ignore while True: try: data, decode, mode, secret_key = pipe.recv() if secret_key is not None: self.secret_key = secret_key packet = self.unpack_audio_packet(data, mode, decode) if isinstance(packet, RTCPPacket): # enum not picklable packet.pt = packet.pt.value # type: ignore pipe.send(packet) except BaseException as exc: pipe.send(exc) return def _decrypt_xsalsa20_poly1305(self, header, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) # type: ignore nonce = bytearray(24) nonce[:12] = header return self.strip_header_ext(box.decrypt(bytes(data), bytes(nonce))) def _decrypt_xsalsa20_poly1305_suffix(self, header, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) # type: ignore nonce_size = nacl.secret.SecretBox.NONCE_SIZE nonce = data[-nonce_size:] return self.strip_header_ext(box.decrypt(bytes(data[:-nonce_size]), nonce)) def _decrypt_xsalsa20_poly1305_lite(self, header, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) # type: ignore nonce = bytearray(24) nonce[:4] = data[-4:] data = data[:-4] return self.strip_header_ext(box.decrypt(bytes(data), bytes(nonce))) @staticmethod def strip_header_ext(data: bytes) -> bytes: if data[0] == 0xBE and data[1] == 0xDE and len(data) > 4: _, length = struct.unpack_from('>HH', data) offset = 4 + length * 4 data = data[offset:] return data def unpack_audio_packet(self, data: bytes, mode: str, decode: bool) -> Union[RTCPPacket, AudioFrame]: packet = get_audio_packet(data, getattr(self, '_decrypt_' + mode))
__all__ = ("AudioProcessPool",) _mp_ctx = multiprocessing.get_context("spawn") class AudioProcessPool: """Process pool for processing audio packets received from voice channels. Parameters ---------- max_processes: :class:`int` The audio processing pool will distribute audio processing across this number of processes. wait_timeout: Optional[:class:`int`] A process will automatically finish when it has not received any audio after this amount of time. Default is 3. None means it will never finish via timeout. Raises ------ ValueError max_processes or wait_timeout must be greater than 0 """ # TODO: add cleanup functionality def __init__(self, max_processes: int, *, wait_timeout: Optional[float] = 3): if max_processes < 1: raise ValueError("max_processes must be greater than 0") if wait_timeout is None or wait_timeout < 1: raise ValueError("wait_timeout must be greater than 0") self.max_processes: int = max_processes self.wait_timeout: Optional[float] = wait_timeout self._processes: Dict[int, Tuple] = {} self._wait_queue: queue.Queue = queue.Queue() self._wait_loop_running: threading.Event = threading.Event() self._lock: threading.Lock = threading.Lock() def submit(self, data: bytes, n_p: int, decode: bool, mode: str, secret_key: List[int]) -> Future: self._lock.acquire() if n_p >= self.max_processes: raise ValueError(f"n_p must be less than the maximum processes ({self.max_processes})") if n_p not in self._processes: self._spawn_process(n_p) future = Future() self._processes[n_p][0].send((data, decode, mode, secret_key)) self._wait_queue.put((n_p, future)) self._start_recv_loop() self._lock.release() return future def _spawn_process(self, n_p) -> None: conn1, conn2 = _mp_ctx.Pipe(duplex=True) process = AudioUnpacker(args=(conn2,)) process.start() self._processes[n_p] = (conn1, process) def _start_recv_loop(self) -> None: if not self._wait_loop_running.is_set(): threading.Thread(target=self._recv_loop).start() def _recv_loop(self) -> None: self._wait_loop_running.set() while True: try: n_p, future = self._wait_queue.get(timeout=self.wait_timeout) except queue.Empty: break try: ret = self._processes[n_p][0].recv() except EOFError: self._lock.acquire() self._processes.pop(n_p) self._lock.release() continue (future.set_exception if isinstance(ret, BaseException) else future.set_result)(ret) self._wait_loop_running.clear() class AudioUnpacker(_mp_ctx.Process): def __init__(self, **kwargs): super().__init__(daemon=True, **kwargs) self.secret_key: Optional[List[int]] = None self.decoders: Dict[int, Decoder] = {} def run(self) -> None: pipe = self._args[0] # type: ignore while True: try: data, decode, mode, secret_key = pipe.recv() if secret_key is not None: self.secret_key = secret_key packet = self.unpack_audio_packet(data, mode, decode) if isinstance(packet, RTCPPacket): # enum not picklable packet.pt = packet.pt.value # type: ignore pipe.send(packet) except BaseException as exc: pipe.send(exc) return def _decrypt_xsalsa20_poly1305(self, header, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) # type: ignore nonce = bytearray(24) nonce[:12] = header return self.strip_header_ext(box.decrypt(bytes(data), bytes(nonce))) def _decrypt_xsalsa20_poly1305_suffix(self, header, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) # type: ignore nonce_size = nacl.secret.SecretBox.NONCE_SIZE nonce = data[-nonce_size:] return self.strip_header_ext(box.decrypt(bytes(data[:-nonce_size]), nonce)) def _decrypt_xsalsa20_poly1305_lite(self, header, data) -> bytes: box = nacl.secret.SecretBox(bytes(self.secret_key)) # type: ignore nonce = bytearray(24) nonce[:4] = data[-4:] data = data[:-4] return self.strip_header_ext(box.decrypt(bytes(data), bytes(nonce))) @staticmethod def strip_header_ext(data: bytes) -> bytes: if data[0] == 0xBE and data[1] == 0xDE and len(data) > 4: _, length = struct.unpack_from('>HH', data) offset = 4 + length * 4 data = data[offset:] return data def unpack_audio_packet(self, data: bytes, mode: str, decode: bool) -> Union[RTCPPacket, AudioFrame]: packet = get_audio_packet(data, getattr(self, '_decrypt_' + mode))
if not isinstance(packet, RawAudioData): # is RTCP packet
3
2023-11-15 00:16:36+00:00
4k
RAIVNLab/MatFormer-OLMo
olmo/optim.py
[ { "identifier": "OptimizerType", "path": "olmo/config.py", "snippet": "class OptimizerType(StrEnum):\n lionw = \"lionw\"\n adam = \"adam\"\n adamw = \"adamw\"" }, { "identifier": "SchedulerType", "path": "olmo/config.py", "snippet": "class SchedulerType(StrEnum):\n cosine_wit...
import math import torch import torch.nn as nn from bisect import bisect_right from typing import Any, Dict, List, Tuple from torch.optim.optimizer import Optimizer from .config import OptimizerType, SchedulerType, TrainConfig from .model import LayerNormBase
3,235
grad = p.grad state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like(p) exp_avg = state["exp_avg"] beta1, beta2 = group["betas"] # Weight update update = exp_avg * beta1 + grad * (1 - beta1) p.add_(torch.sign(update), alpha=-group["lr"]) # Decay the momentum running average coefficient exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2) return loss def get_param_groups(model: nn.Module) -> List[Dict[str, Any]]: """ Separate parameters into weight decay and non weight decay groups. """ # Separate out parameters that we don't want to apply weight decay to, like norms and biases. decay = set() no_decay = set() all_params = {} for mn, m in model.named_modules(): for pn, p in m.named_parameters(): # NOTE: because named_modules and named_parameters are recursive # we will see the same tensors p many many times, but doing it this way # allows us to know which parent module any tensor p belongs to... if not p.requires_grad: continue fpn = f"{mn}.{pn}" if mn else pn all_params[fpn] = p if pn.endswith("bias"): # all biases will not be decayed no_decay.add(fpn) elif pn.endswith("weight") and isinstance(m, nn.Linear): decay.add(fpn) elif pn.endswith("weight") and isinstance(m, (LayerNormBase, nn.LayerNorm, nn.Embedding)): no_decay.add(fpn) # Validate that we've considered every parameter inter_params = decay & no_decay union_params = decay | no_decay assert decay assert no_decay assert len(inter_params) == 0, f"parameters {inter_params} made it into both decay/no_decay sets!" assert ( len(all_params.keys() - union_params) == 0 ), f"parameters {all_params.keys() - union_params} were not separated into either decay/no_decay set!" # Create the pytorch optimizer groups. return [ {"params": [all_params[pn] for pn in sorted(list(decay))]}, {"params": [all_params[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, ] def fix_optim_state_dict(optimizer: Optimizer, state_dict: Dict[str, Any]) -> Dict[str, Any]: """ Make sure `state_dict`, which only have 1 param group, is compatible with the optimizer which may have two param groups (one for params with weight decay, the other for those without). """ if len(state_dict["param_groups"]) == 1 and len(optimizer.param_groups) == 2: assert optimizer.param_groups[1]["weight_decay"] == 0.0 # Decay decay_param_group = {k: v for k, v in state_dict["param_groups"][0].items() if k != "params"} decay_param_group["params"] = optimizer.state_dict()["param_groups"][0]["params"] # No decay. no_decay_param_group = {k: v for k, v in state_dict["param_groups"][0].items() if k != "params"} no_decay_param_group["weight_decay"] = 0.0 no_decay_param_group["params"] = optimizer.state_dict()["param_groups"][1]["params"] state_dict["param_groups"] = [decay_param_group, no_decay_param_group] return state_dict def build_optimizer(cfg: TrainConfig, model: nn.Module) -> torch.optim.Optimizer: params = ( get_param_groups(model) if (cfg.optimizer.no_decay_norm_and_bias and cfg.optimizer.weight_decay > 0.0) else model.parameters() ) if cfg.optimizer.name == OptimizerType.lionw: return LionW( params, lr=cfg.optimizer.learning_rate, betas=cfg.optimizer.betas, weight_decay=cfg.optimizer.weight_decay, ) elif cfg.optimizer.name == OptimizerType.adam: return torch.optim.Adam( params, lr=cfg.optimizer.learning_rate, betas=cfg.optimizer.betas, weight_decay=cfg.optimizer.weight_decay, ) elif cfg.optimizer.name == OptimizerType.adamw: return torch.optim.AdamW( params, lr=cfg.optimizer.learning_rate, betas=cfg.optimizer.betas, weight_decay=cfg.optimizer.weight_decay, ) else: raise NotImplementedError def build_scheduler(cfg: TrainConfig, optim: torch.optim.Optimizer) -> torch.optim.lr_scheduler.LRScheduler: schedulers: List[torch.optim.lr_scheduler.LRScheduler] = []
__all__ = ["LionW", "build_optimizer", "build_scheduler", "set_new_base_lr"] class LionW(Optimizer): """Adapted from https://github.com/google/automl/blob/master/lion/lion_pytorch.py""" def __init__( self, params, lr: float = 1e-4, betas: Tuple[float, float] = (0.9, 0.99), weight_decay: float = 0.0, ): assert lr > 0.0 assert all([0.0 <= beta <= 1.0 for beta in betas]) defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay) super().__init__(params, defaults) for group in self.param_groups: group["initial_lr"] = group["lr"] @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group["params"]: if p.grad is None: continue # Perform stepweight decay p.data.mul_(1 - group["lr"] * group["weight_decay"]) grad = p.grad state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like(p) exp_avg = state["exp_avg"] beta1, beta2 = group["betas"] # Weight update update = exp_avg * beta1 + grad * (1 - beta1) p.add_(torch.sign(update), alpha=-group["lr"]) # Decay the momentum running average coefficient exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2) return loss def get_param_groups(model: nn.Module) -> List[Dict[str, Any]]: """ Separate parameters into weight decay and non weight decay groups. """ # Separate out parameters that we don't want to apply weight decay to, like norms and biases. decay = set() no_decay = set() all_params = {} for mn, m in model.named_modules(): for pn, p in m.named_parameters(): # NOTE: because named_modules and named_parameters are recursive # we will see the same tensors p many many times, but doing it this way # allows us to know which parent module any tensor p belongs to... if not p.requires_grad: continue fpn = f"{mn}.{pn}" if mn else pn all_params[fpn] = p if pn.endswith("bias"): # all biases will not be decayed no_decay.add(fpn) elif pn.endswith("weight") and isinstance(m, nn.Linear): decay.add(fpn) elif pn.endswith("weight") and isinstance(m, (LayerNormBase, nn.LayerNorm, nn.Embedding)): no_decay.add(fpn) # Validate that we've considered every parameter inter_params = decay & no_decay union_params = decay | no_decay assert decay assert no_decay assert len(inter_params) == 0, f"parameters {inter_params} made it into both decay/no_decay sets!" assert ( len(all_params.keys() - union_params) == 0 ), f"parameters {all_params.keys() - union_params} were not separated into either decay/no_decay set!" # Create the pytorch optimizer groups. return [ {"params": [all_params[pn] for pn in sorted(list(decay))]}, {"params": [all_params[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, ] def fix_optim_state_dict(optimizer: Optimizer, state_dict: Dict[str, Any]) -> Dict[str, Any]: """ Make sure `state_dict`, which only have 1 param group, is compatible with the optimizer which may have two param groups (one for params with weight decay, the other for those without). """ if len(state_dict["param_groups"]) == 1 and len(optimizer.param_groups) == 2: assert optimizer.param_groups[1]["weight_decay"] == 0.0 # Decay decay_param_group = {k: v for k, v in state_dict["param_groups"][0].items() if k != "params"} decay_param_group["params"] = optimizer.state_dict()["param_groups"][0]["params"] # No decay. no_decay_param_group = {k: v for k, v in state_dict["param_groups"][0].items() if k != "params"} no_decay_param_group["weight_decay"] = 0.0 no_decay_param_group["params"] = optimizer.state_dict()["param_groups"][1]["params"] state_dict["param_groups"] = [decay_param_group, no_decay_param_group] return state_dict def build_optimizer(cfg: TrainConfig, model: nn.Module) -> torch.optim.Optimizer: params = ( get_param_groups(model) if (cfg.optimizer.no_decay_norm_and_bias and cfg.optimizer.weight_decay > 0.0) else model.parameters() ) if cfg.optimizer.name == OptimizerType.lionw: return LionW( params, lr=cfg.optimizer.learning_rate, betas=cfg.optimizer.betas, weight_decay=cfg.optimizer.weight_decay, ) elif cfg.optimizer.name == OptimizerType.adam: return torch.optim.Adam( params, lr=cfg.optimizer.learning_rate, betas=cfg.optimizer.betas, weight_decay=cfg.optimizer.weight_decay, ) elif cfg.optimizer.name == OptimizerType.adamw: return torch.optim.AdamW( params, lr=cfg.optimizer.learning_rate, betas=cfg.optimizer.betas, weight_decay=cfg.optimizer.weight_decay, ) else: raise NotImplementedError def build_scheduler(cfg: TrainConfig, optim: torch.optim.Optimizer) -> torch.optim.lr_scheduler.LRScheduler: schedulers: List[torch.optim.lr_scheduler.LRScheduler] = []
if cfg.scheduler.name == SchedulerType.cosine_with_warmup:
1
2023-11-14 02:24:07+00:00
4k
1in-oos/ccplus
caringcaribou/modules/fuzzer.py
[ { "identifier": "CanActions", "path": "caringcaribou/utils/can_actions.py", "snippet": "class CanActions:\n\n def __init__(self, arb_id=None, notifier_enabled=True):\n \"\"\"\n CanActions constructor\n\n :param arb_id: int default arbitration ID for object or None\n :param...
from sys import version_info, stdout from itertools import product from caringcaribou.utils.can_actions import CanActions from caringcaribou.utils.common import hex_str_to_nibble_list, int_from_byte_list, list_to_hex_str, parse_int_dec_or_hex from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MIN, BYTE_MAX, BYTE_MIN from time import sleep import argparse import random
2,553
from __future__ import print_function # Python 2/3 compatibility if version_info[0] == 2: range = xrange input = raw_input # Number of seconds to wait between messages DELAY_BETWEEN_MESSAGES = 0.01 # Message data length limits MIN_DATA_LENGTH = 1 MAX_DATA_LENGTH = 8 # Max size of random seed if no seed is provided in arguments DEFAULT_SEED_MAX = 2 ** 16 # Number of sub-lists to split message list into per round in 'replay' mode REPLAY_NUMBER_OF_SUB_LISTS = 5 def directive_str(arb_id, data): """ Converts a directive to its string representation :param arb_id: message arbitration ID :param data: message data bytes :return: str representing directive """
from __future__ import print_function # Python 2/3 compatibility if version_info[0] == 2: range = xrange input = raw_input # Number of seconds to wait between messages DELAY_BETWEEN_MESSAGES = 0.01 # Message data length limits MIN_DATA_LENGTH = 1 MAX_DATA_LENGTH = 8 # Max size of random seed if no seed is provided in arguments DEFAULT_SEED_MAX = 2 ** 16 # Number of sub-lists to split message list into per round in 'replay' mode REPLAY_NUMBER_OF_SUB_LISTS = 5 def directive_str(arb_id, data): """ Converts a directive to its string representation :param arb_id: message arbitration ID :param data: message data bytes :return: str representing directive """
data = list_to_hex_str(data, "")
3
2023-11-13 05:05:46+00:00
4k
L1bra1/WeakMotion
predict_FGBG_mask.py
[ { "identifier": "PreSegNet", "path": "weak_model.py", "snippet": "class PreSegNet(nn.Module):\n def __init__(self, FGBG_category_num=2, height_feat_size=13):\n super(PreSegNet, self).__init__()\n\n self.FGBG_classify = FGBGEstimation(motion_category_num=FGBG_category_num)\n self....
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import time import sys import argparse import os from weak_model import PreSegNet from data.weak_utils import remove_close, filter_pc, convert_semantic_to_FGBG, gen_voxel_indices_for_pc, convert_semantic_to_FGBG_waymo from sklearn.metrics import confusion_matrix from tqdm import tqdm
1,941
def check_folder(folder_path): if not os.path.exists(folder_path): os.mkdir(folder_path) return folder_path height_feat_size = 13 # The size along the height dimension parser = argparse.ArgumentParser() parser.add_argument('-d', '--data', default='/path_to/nuScenes/weak-data/train', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-s', '--save_FB', default='/path_to/nuScenes/FGBG-data/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--datatype', default='nuScenes', type=str, choices=['Waymo', 'nuScenes']) parser.add_argument('--pretrained', default='pretrained/nuscenes_seg_0-01.pth', type=str) parser.add_argument('--gpu', default='0') args = parser.parse_args() print(args) os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu datatype = args.datatype def main(): # Specify gpu device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device_num = torch.cuda.device_count() print("device number", device_num) voxel_size = (0.25, 0.25, 0.4) if datatype == 'nuScenes': area_extents = np.array([[-32., 32.], [-32., 32.], [-3., 2.]]) elif datatype == 'Waymo': area_extents = np.array([[-32., 32.], [-32., 32.], [-1., 4.]]) dims = (256, 256, 13) model = PreSegNet(FGBG_category_num=2, height_feat_size=height_feat_size) model = nn.DataParallel(model) model = model.to(device) if args.pretrained != '': checkpoint = torch.load(args.pretrained) model.load_state_dict(checkpoint['model_state_dict']) check_folder(args.save_FB) model_name = args.pretrained.split('/')[-1][:-4] args.save_FB = check_folder(os.path.join(args.save_FB, model_name)) # get file list seq_dirs = [] for d in os.listdir(args.data): tmp_0 = os.path.join(args.data, d) seq_dirs.append(tmp_0) # for file in tqdm(seq_dirs, total=len(seq_dirs), smoothing=0.9): for idx, file in tqdm(enumerate(seq_dirs, 0), total=len(seq_dirs), smoothing=0.9): if datatype == 'nuScenes': scene_name = file.split('/')[-1] file = os.path.join(file, '0.npy') elif datatype == 'Waymo': scene_name = file.split('/')[-1].split('.')[0] weak_data_handle = np.load(file, allow_pickle=True) weak_dict = weak_data_handle.item() pc_0, FGBG_gt_0, voxel_points_0 = gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index=0) pc_1, FGBG_gt_1, voxel_points_1 = gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index=1) pc_2, FGBG_gt_2, voxel_points_2 = gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index=2) pred_0 = estimate_FBGB_for_point(model, voxel_points_0, pc_0, area_extents, voxel_size, device) pred_1 = estimate_FBGB_for_point(model, voxel_points_1, pc_1, area_extents, voxel_size, device) pred_2 = estimate_FBGB_for_point(model, voxel_points_2, pc_2, area_extents, voxel_size, device) FG_pred_0_bool = (pred_0 - 1).astype(np.bool_) FG_pred_1_bool = (pred_1 - 1).astype(np.bool_) FG_pred_2_bool = (pred_2 - 1).astype(np.bool_) file_name = os.path.join(args.save_FB, scene_name + '.npz') np.savez(file_name, pred_0=FG_pred_0_bool, pred_1=FG_pred_1_bool, pred_2=FG_pred_2_bool) print('Finish!') return def gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index = 0): pc = weak_dict['synchronized_pc_' + str(index)].T[:, 0:3] label = weak_dict['points_label_' + str(index)] if datatype == 'nuScenes': FGBG_gt_mask = convert_semantic_to_FGBG(label[:, 0]) # 1: Background; 2: Foreground elif datatype == 'Waymo':
def check_folder(folder_path): if not os.path.exists(folder_path): os.mkdir(folder_path) return folder_path height_feat_size = 13 # The size along the height dimension parser = argparse.ArgumentParser() parser.add_argument('-d', '--data', default='/path_to/nuScenes/weak-data/train', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-s', '--save_FB', default='/path_to/nuScenes/FGBG-data/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--datatype', default='nuScenes', type=str, choices=['Waymo', 'nuScenes']) parser.add_argument('--pretrained', default='pretrained/nuscenes_seg_0-01.pth', type=str) parser.add_argument('--gpu', default='0') args = parser.parse_args() print(args) os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu datatype = args.datatype def main(): # Specify gpu device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device_num = torch.cuda.device_count() print("device number", device_num) voxel_size = (0.25, 0.25, 0.4) if datatype == 'nuScenes': area_extents = np.array([[-32., 32.], [-32., 32.], [-3., 2.]]) elif datatype == 'Waymo': area_extents = np.array([[-32., 32.], [-32., 32.], [-1., 4.]]) dims = (256, 256, 13) model = PreSegNet(FGBG_category_num=2, height_feat_size=height_feat_size) model = nn.DataParallel(model) model = model.to(device) if args.pretrained != '': checkpoint = torch.load(args.pretrained) model.load_state_dict(checkpoint['model_state_dict']) check_folder(args.save_FB) model_name = args.pretrained.split('/')[-1][:-4] args.save_FB = check_folder(os.path.join(args.save_FB, model_name)) # get file list seq_dirs = [] for d in os.listdir(args.data): tmp_0 = os.path.join(args.data, d) seq_dirs.append(tmp_0) # for file in tqdm(seq_dirs, total=len(seq_dirs), smoothing=0.9): for idx, file in tqdm(enumerate(seq_dirs, 0), total=len(seq_dirs), smoothing=0.9): if datatype == 'nuScenes': scene_name = file.split('/')[-1] file = os.path.join(file, '0.npy') elif datatype == 'Waymo': scene_name = file.split('/')[-1].split('.')[0] weak_data_handle = np.load(file, allow_pickle=True) weak_dict = weak_data_handle.item() pc_0, FGBG_gt_0, voxel_points_0 = gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index=0) pc_1, FGBG_gt_1, voxel_points_1 = gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index=1) pc_2, FGBG_gt_2, voxel_points_2 = gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index=2) pred_0 = estimate_FBGB_for_point(model, voxel_points_0, pc_0, area_extents, voxel_size, device) pred_1 = estimate_FBGB_for_point(model, voxel_points_1, pc_1, area_extents, voxel_size, device) pred_2 = estimate_FBGB_for_point(model, voxel_points_2, pc_2, area_extents, voxel_size, device) FG_pred_0_bool = (pred_0 - 1).astype(np.bool_) FG_pred_1_bool = (pred_1 - 1).astype(np.bool_) FG_pred_2_bool = (pred_2 - 1).astype(np.bool_) file_name = os.path.join(args.save_FB, scene_name + '.npz') np.savez(file_name, pred_0=FG_pred_0_bool, pred_1=FG_pred_1_bool, pred_2=FG_pred_2_bool) print('Finish!') return def gen_voxel_for_PreSegNet(weak_dict, area_extents, voxel_size, dims, index = 0): pc = weak_dict['synchronized_pc_' + str(index)].T[:, 0:3] label = weak_dict['points_label_' + str(index)] if datatype == 'nuScenes': FGBG_gt_mask = convert_semantic_to_FGBG(label[:, 0]) # 1: Background; 2: Foreground elif datatype == 'Waymo':
FGBG_gt_mask = convert_semantic_to_FGBG_waymo(label[:, 0])
5
2023-11-12 07:03:29+00:00
4k
c3exchange/c3-smartcontracts-v1
contracts_unified/core/internal/move.py
[ { "identifier": "GlobalStateHandler", "path": "contracts_unified/core/state_handler/global_handler.py", "snippet": "class GlobalStateHandler:\n \"\"\"Global state handler\"\"\"\n\n instrument_size = abi.make(InstrumentListElement).type_spec().byte_length_static()\n max_instrument_count = 80\n\n...
from typing import cast from pyteal import ( ABIReturnSubroutine, And, Assert, Expr, For, If, Int, Not, Reject, Seq, abi, ) from contracts_unified.core.state_handler.global_handler import GlobalStateHandler from contracts_unified.core.state_handler.local_handler import LocalStateHandler from contracts_unified.library.c3types import ( AccountAddress, Amount, InstrumentId, SignedAmount, SignedInstrumentBasket, UserInstrumentData, ) from contracts_unified.library.signed_math import signed_add, signed_ltz, signed_neg
2,783
"""Utility functions to move assets between and within accounts""" @ABIReturnSubroutine def signed_add_to_cash( account: AccountAddress, instrument_id: InstrumentId, amount: Amount, ) -> Expr: """Adds amount to the user's asset balance""" data = UserInstrumentData()
"""Utility functions to move assets between and within accounts""" @ABIReturnSubroutine def signed_add_to_cash( account: AccountAddress, instrument_id: InstrumentId, amount: Amount, ) -> Expr: """Adds amount to the user's asset balance""" data = UserInstrumentData()
new_cash = SignedAmount()
2
2023-11-17 20:54:15+00:00
4k
gunderson-dettmer/CE2OCF
CE2OCF/datamap/loaders.py
[ { "identifier": "IssuerDataMap", "path": "CE2OCF/ocf/datamaps.py", "snippet": "class IssuerDataMap(FieldPostProcessorModel):\n id: Union[str, OverridableStringField] = Field(default_factory=lambda: {\"static\": uuid.uuid4().__str__()})\n legal_name: Union[str, OverridableStringField]\n dba: Uni...
import json from pathlib import Path from typing import Optional from CE2OCF.ocf.datamaps import ( IssuerDataMap, RepeatableFullyVestedStockIssuanceDataMap, RepeatableStockholderDataMap, RepeatableVestingEventDriversDataMap, RepeatableVestingScheduleDriversDataMap, RepeatableVestingStockIssuanceDataMap, StockClassDataMap, StockLegendDataMap, StockPlanDataMap, ) from CE2OCF.types.dictionaries import ( CicEventDefinition, TerminationDetails, )
3,156
config/defaults. WARNING - DEFAULT IS FOR COMMON Args: source_json: son configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_COMMON_STOCK_CLASS_ONLY_PATH Returns: StockClassDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_COMMON_STOCK_CLASS_ONLY_PATH return StockClassDataMap.parse_file(source_json) def load_ce_to_ocf_stock_legend_datamap(source_json: Optional[Path] = None) -> StockLegendDataMap: """ Loads a StockLegendDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. WARNING - DEFAULT IS FOR GUNDERSON COMMON LEGENDS Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_DATAMAP_COMMON_STOCK_LEGEND_ONLY_PATH Returns: StockLegendDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_DATAMAP_COMMON_STOCK_LEGEND_ONLY_PATH return StockLegendDataMap.parse_file(source_json) def load_ce_to_ocf_stock_plan_datamap(source_json: Optional[Path] = None) -> StockPlanDataMap: """ Loads a StockPlanDataMap from a json configuration file at source_json. Defaults to the default datamap in config/defaults. :param source_json:Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_STOCK_PLAN_ONLY_PATH :return: StockPlanDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_STOCK_PLAN_ONLY_PATH return StockPlanDataMap.parse_file(source_json) def load_ce_to_ocf_stakeholder_datamap(source_json: Optional[Path] = None) -> RepeatableStockholderDataMap: """ Loads a RepeatableStockholderDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_STOCKHOLDERS_ONLY_PATH Returns: RepeatableStockholderDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_STOCKHOLDERS_ONLY_PATH return RepeatableStockholderDataMap.parse_file(source_json) def load_ce_to_ocf_vesting_issuances_datamap( source_json: Optional[Path] = None, ) -> RepeatableVestingStockIssuanceDataMap: """ Loads a RepeatableVestingStockIssuanceDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. Meant for use with issuances that can vest. Typically founder common. Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_COMMON_STOCK_ISSUANCE_ONLY_PATH Returns: RepeatableVestingStockIssuanceDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_COMMON_STOCK_ISSUANCE_ONLY_PATH return RepeatableVestingStockIssuanceDataMap.parse_file(source_json) def load_ce_to_ocf_vested_issuances_datamap( source_json: Optional[Path] = None, ) -> RepeatableFullyVestedStockIssuanceDataMap: """ Loads a RepeatableFullyVestedStockIssuanceDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. Meant for use with issuances that don't vest. Typically, founder preferred. Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_PREFERRED_STOCK_ISSUANCE_ONLY_PATH Returns: RepeatableFullyVestedStockIssuanceDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_PREFERRED_STOCK_ISSUANCE_ONLY_PATH return RepeatableFullyVestedStockIssuanceDataMap.parse_file(source_json) def load_vesting_schedule_driving_enums_datamap( source_jsons: Optional[Path] = None, ) -> RepeatableVestingScheduleDriversDataMap: """ Loads a RepeatableVestingScheduleDriversDataMap from data map in source_jsons path. If none provided, use the default datamap in DEFAULT_CE_ENUMS_TO_OCF_VESTING_SCHEDULE_ONLY_PATH. Args: source_jsons: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_ENUMS_TO_OCF_VESTING_SCHEDULE_ONLY_PATH Returns: RepeatableVestingScheduleDriversDataMap """ if source_jsons is None: source_jsons = DEFAULT_CE_ENUMS_TO_OCF_VESTING_SCHEDULE_ONLY_PATH return RepeatableVestingScheduleDriversDataMap.parse_file(source_jsons) def load_vesting_events_driving_enums_datamap( source_jsons: Optional[Path] = None,
MODULE_PATH = Path(__file__).parent DEFAULTS_PATH = MODULE_PATH / "defaults" # Default Configuration File Locations DEFAULT_CIC_DEFS_PATH = DEFAULTS_PATH / "cic_event_definition.json" DEFAULT_SINGLE_TRIG_DEFS_PATH = DEFAULTS_PATH / "single_trigger_acceleration.json" DEFAULT_DOUBLE_TRIG_DEFS_PATH = DEFAULTS_PATH / "double_trigger_acceleration.json" DEFAULT_CE_TO_OCF_COMMON_STOCK_CLASS_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_common_stock_class_only.json" DEFAULT_CE_TO_OCF_COMMON_STOCK_ISSUANCE_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_common_stock_issuance_only.json" DEFAULT_CE_TO_OCF_DATAMAP_COMMON_STOCK_LEGEND_ONLY_PATH = ( DEFAULTS_PATH / "ce_to_ocf_datamap_common_stock_legend_only.json" ) DEFAULT_CE_TO_OCF_DATAMAP_PREFERRED_STOCK_LEGEND_ONLY_PATH = ( DEFAULTS_PATH / "ce_to_ocf_datamap_preferred_stock_legend_only.json" ) DEFAULT_CE_TO_OCF_ISSUER_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_issuer_only.json" DEFAULT_CE_TO_OCF_PREFERRED_STOCK_CLASS_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_preferred_stock_class_only.json" DEFAULT_CE_TO_OCF_PREFERRED_STOCK_ISSUANCE_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_preferred_stock_issuance_only.json" DEFAULT_CE_TO_OCF_STOCK_PLAN_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_stock_plan_only.json" DEFAULT_CE_TO_OCF_STOCKHOLDERS_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_stockholders_only.json" DEFAULT_CE_ENUMS_TO_OCF_VESTING_SCHEDULE_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_vesting_enums_events_only.json" DEFAULT_CE_ENUMS_TO_OCF_VESTING_EVENTS_ONLY_PATH = DEFAULTS_PATH / "ce_to_ocf_vesting_enums_events_only.json" ######################################################################################################################## # Configuration File Loaders - Primary natural language definitions and quantitative cutoffs required to generate ocf ######################################################################################################################## def load_cic_event_definition(source_json: Path = DEFAULT_CIC_DEFS_PATH) -> CicEventDefinition: with source_json.open("r") as config_file: return json.loads(config_file.read()) def load_double_trigger_definitions( source_json: Path = DEFAULT_DOUBLE_TRIG_DEFS_PATH, ) -> dict[str, Optional[TerminationDetails]]: with source_json.open("r") as config_file: return json.loads(config_file.read()) def load_single_trigger_definitions( source_json: Path = DEFAULT_SINGLE_TRIG_DEFS_PATH, ) -> dict[str, Optional[CicEventDefinition]]: with source_json.open("r") as config_file: return json.loads(config_file.read()) ######################################################################################################################## # Datamap Loaders ######################################################################################################################## def load_ce_to_ocf_issuer_datamap(source_json: Optional[Path] = None) -> IssuerDataMap: if source_json is None: source_json = DEFAULT_CE_TO_OCF_ISSUER_ONLY_PATH return IssuerDataMap.parse_file(source_json) def load_ce_to_ocf_stock_class_datamap(source_json: Optional[Path] = None) -> StockClassDataMap: """ Loads a StockClassDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. WARNING - DEFAULT IS FOR COMMON Args: source_json: son configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_COMMON_STOCK_CLASS_ONLY_PATH Returns: StockClassDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_COMMON_STOCK_CLASS_ONLY_PATH return StockClassDataMap.parse_file(source_json) def load_ce_to_ocf_stock_legend_datamap(source_json: Optional[Path] = None) -> StockLegendDataMap: """ Loads a StockLegendDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. WARNING - DEFAULT IS FOR GUNDERSON COMMON LEGENDS Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_DATAMAP_COMMON_STOCK_LEGEND_ONLY_PATH Returns: StockLegendDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_DATAMAP_COMMON_STOCK_LEGEND_ONLY_PATH return StockLegendDataMap.parse_file(source_json) def load_ce_to_ocf_stock_plan_datamap(source_json: Optional[Path] = None) -> StockPlanDataMap: """ Loads a StockPlanDataMap from a json configuration file at source_json. Defaults to the default datamap in config/defaults. :param source_json:Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_STOCK_PLAN_ONLY_PATH :return: StockPlanDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_STOCK_PLAN_ONLY_PATH return StockPlanDataMap.parse_file(source_json) def load_ce_to_ocf_stakeholder_datamap(source_json: Optional[Path] = None) -> RepeatableStockholderDataMap: """ Loads a RepeatableStockholderDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_STOCKHOLDERS_ONLY_PATH Returns: RepeatableStockholderDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_STOCKHOLDERS_ONLY_PATH return RepeatableStockholderDataMap.parse_file(source_json) def load_ce_to_ocf_vesting_issuances_datamap( source_json: Optional[Path] = None, ) -> RepeatableVestingStockIssuanceDataMap: """ Loads a RepeatableVestingStockIssuanceDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. Meant for use with issuances that can vest. Typically founder common. Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_COMMON_STOCK_ISSUANCE_ONLY_PATH Returns: RepeatableVestingStockIssuanceDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_COMMON_STOCK_ISSUANCE_ONLY_PATH return RepeatableVestingStockIssuanceDataMap.parse_file(source_json) def load_ce_to_ocf_vested_issuances_datamap( source_json: Optional[Path] = None, ) -> RepeatableFullyVestedStockIssuanceDataMap: """ Loads a RepeatableFullyVestedStockIssuanceDataMap from a json configuration file at source_json. Defaults to the defaults in config/defaults. Meant for use with issuances that don't vest. Typically, founder preferred. Args: source_json: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_TO_OCF_PREFERRED_STOCK_ISSUANCE_ONLY_PATH Returns: RepeatableFullyVestedStockIssuanceDataMap """ if source_json is None: source_json = DEFAULT_CE_TO_OCF_PREFERRED_STOCK_ISSUANCE_ONLY_PATH return RepeatableFullyVestedStockIssuanceDataMap.parse_file(source_json) def load_vesting_schedule_driving_enums_datamap( source_jsons: Optional[Path] = None, ) -> RepeatableVestingScheduleDriversDataMap: """ Loads a RepeatableVestingScheduleDriversDataMap from data map in source_jsons path. If none provided, use the default datamap in DEFAULT_CE_ENUMS_TO_OCF_VESTING_SCHEDULE_ONLY_PATH. Args: source_jsons: Json configuration file mapping ocf fields to ce json data fields. Defaults to DEFAULT_CE_ENUMS_TO_OCF_VESTING_SCHEDULE_ONLY_PATH Returns: RepeatableVestingScheduleDriversDataMap """ if source_jsons is None: source_jsons = DEFAULT_CE_ENUMS_TO_OCF_VESTING_SCHEDULE_ONLY_PATH return RepeatableVestingScheduleDriversDataMap.parse_file(source_jsons) def load_vesting_events_driving_enums_datamap( source_jsons: Optional[Path] = None,
) -> RepeatableVestingEventDriversDataMap:
3
2023-11-13 15:50:53+00:00
4k
Hellohistory/EbookDataRename.py
main.py
[ { "identifier": "queryDatabaseForFileNames", "path": "model/database_handler.py", "snippet": "def queryDatabaseForFileNames(db_folder_path, folder_path, tableWidget):\n try:\n db_files = get_files_from_directory(db_folder_path, recursive=True)\n db_files = [f for f in db_files if f.ends...
import sys from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QProgressBar, QTableWidget, QRadioButton, QCheckBox, QFileDialog, QTableWidgetItem) from PyQt5.QtCore import QSize from opencc import OpenCC from model.database_handler import queryDatabaseForFileNames from model.file_handler import get_files_from_directory from model.rename_handler import startRenamingFiles
1,740
class MainGUI(QMainWindow): def __init__(self): super().__init__() self.cc = OpenCC('s2t') self.original_names = {} self.initUI() def applyTraditionalSimplifiedConversion(self): total_rows = self.tableWidget.rowCount() for row in range(total_rows): original_text_item = self.tableWidget.item(row, 1) if original_text_item: if self.traditionalSimplifiedCheckBox.isChecked(): if row not in self.original_names: self.original_names[row] = original_text_item.text() converted_text = self.cc.convert(self.original_names[row]) self.tableWidget.setItem(row, 1, QTableWidgetItem(converted_text)) else: if row in self.original_names: self.tableWidget.setItem(row, 1, QTableWidgetItem(self.original_names[row])) def initUI(self): self.setWindowTitle('EbookDataRename V0.0.1') self.setMinimumSize(QSize(800, 600)) centralWidget = QWidget(self) self.setCentralWidget(centralWidget) mainLayout = QVBoxLayout(centralWidget) self.setupLayout(mainLayout) self.applyMaterialDesignStyle() def initiateDatabaseQuery(self): db_path = self.local_db_lineedit.text() folder_path = self.targetFolderLineEdit.text() queryDatabaseForFileNames(db_path, folder_path, self.tableWidget) def setupLayout(self, mainLayout): modeLayout = QHBoxLayout() self.localModeRadioButton = QRadioButton('本地模式') self.remoteModeRadioButton = QRadioButton('远程模式') self.localModeRadioButton.setChecked(True) modeLayout.addWidget(self.localModeRadioButton) modeLayout.addWidget(self.remoteModeRadioButton) mainLayout.addLayout(modeLayout) self.targetFolderLineEdit = QLineEdit() self.selectTargetFolderButton = QPushButton('选择目标文件夹') self.selectTargetFolderButton.clicked.connect(self.selectTargetFolder) targetFolderLayout = QHBoxLayout() targetFolderLayout.addWidget(self.targetFolderLineEdit) targetFolderLayout.addWidget(self.selectTargetFolderButton) mainLayout.addLayout(targetFolderLayout) self.localModeRadioButton.toggled.connect(self.onModeChanged) self.local_db_lineedit = QLineEdit() self.selectFolderButton = QPushButton('选择文件夹') self.selectFolderButton.clicked.connect(self.selectDatabase) folderLayout = QHBoxLayout() folderLayout.addWidget(self.local_db_lineedit) folderLayout.addWidget(self.selectFolderButton) mainLayout.addLayout(folderLayout) self.remote_url_lineedit = QLineEdit() self.remote_url_lineedit.setPlaceholderText("输入API地址") mainLayout.addWidget(self.remote_url_lineedit) self.changeExtensionCheckBox = QCheckBox("将 .uvz 改为 .zip") self.traditionalSimplifiedCheckBox = QCheckBox("呈现效果为繁体书名") self.traditionalSimplifiedCheckBox.stateChanged.connect(self.applyTraditionalSimplifiedConversion) checkBoxLayout = QHBoxLayout() checkBoxLayout.addWidget(self.changeExtensionCheckBox) checkBoxLayout.addWidget(self.traditionalSimplifiedCheckBox) mainLayout.addLayout(checkBoxLayout) self.tableWidget = QTableWidget() self.tableWidget.setColumnCount(3) self.tableWidget.setHorizontalHeaderLabels(['文件名', '重命名后文件名', '状态']) mainLayout.addWidget(self.tableWidget) self.queryButton = QPushButton('查询文件名') self.queryButton.clicked.connect(self.initiateDatabaseQuery) mainLayout.addWidget(self.queryButton) self.renameButton = QPushButton('开始重命名') self.renameButton.clicked.connect(self.initiateRenaming) mainLayout.addWidget(self.renameButton) self.progressBar = QProgressBar() mainLayout.addWidget(self.progressBar) self.onModeChanged() def onModeChanged(self): isLocalMode = self.localModeRadioButton.isChecked() self.local_db_lineedit.setVisible(isLocalMode) self.selectFolderButton.setVisible(isLocalMode) self.remote_url_lineedit.setVisible(not isLocalMode) def selectDatabase(self): folder_path = QFileDialog.getExistingDirectory(self, "选择数据库文件夹") if folder_path: self.local_db_lineedit.setText(folder_path) def updateTableWithFiles(self, folder_path):
class MainGUI(QMainWindow): def __init__(self): super().__init__() self.cc = OpenCC('s2t') self.original_names = {} self.initUI() def applyTraditionalSimplifiedConversion(self): total_rows = self.tableWidget.rowCount() for row in range(total_rows): original_text_item = self.tableWidget.item(row, 1) if original_text_item: if self.traditionalSimplifiedCheckBox.isChecked(): if row not in self.original_names: self.original_names[row] = original_text_item.text() converted_text = self.cc.convert(self.original_names[row]) self.tableWidget.setItem(row, 1, QTableWidgetItem(converted_text)) else: if row in self.original_names: self.tableWidget.setItem(row, 1, QTableWidgetItem(self.original_names[row])) def initUI(self): self.setWindowTitle('EbookDataRename V0.0.1') self.setMinimumSize(QSize(800, 600)) centralWidget = QWidget(self) self.setCentralWidget(centralWidget) mainLayout = QVBoxLayout(centralWidget) self.setupLayout(mainLayout) self.applyMaterialDesignStyle() def initiateDatabaseQuery(self): db_path = self.local_db_lineedit.text() folder_path = self.targetFolderLineEdit.text() queryDatabaseForFileNames(db_path, folder_path, self.tableWidget) def setupLayout(self, mainLayout): modeLayout = QHBoxLayout() self.localModeRadioButton = QRadioButton('本地模式') self.remoteModeRadioButton = QRadioButton('远程模式') self.localModeRadioButton.setChecked(True) modeLayout.addWidget(self.localModeRadioButton) modeLayout.addWidget(self.remoteModeRadioButton) mainLayout.addLayout(modeLayout) self.targetFolderLineEdit = QLineEdit() self.selectTargetFolderButton = QPushButton('选择目标文件夹') self.selectTargetFolderButton.clicked.connect(self.selectTargetFolder) targetFolderLayout = QHBoxLayout() targetFolderLayout.addWidget(self.targetFolderLineEdit) targetFolderLayout.addWidget(self.selectTargetFolderButton) mainLayout.addLayout(targetFolderLayout) self.localModeRadioButton.toggled.connect(self.onModeChanged) self.local_db_lineedit = QLineEdit() self.selectFolderButton = QPushButton('选择文件夹') self.selectFolderButton.clicked.connect(self.selectDatabase) folderLayout = QHBoxLayout() folderLayout.addWidget(self.local_db_lineedit) folderLayout.addWidget(self.selectFolderButton) mainLayout.addLayout(folderLayout) self.remote_url_lineedit = QLineEdit() self.remote_url_lineedit.setPlaceholderText("输入API地址") mainLayout.addWidget(self.remote_url_lineedit) self.changeExtensionCheckBox = QCheckBox("将 .uvz 改为 .zip") self.traditionalSimplifiedCheckBox = QCheckBox("呈现效果为繁体书名") self.traditionalSimplifiedCheckBox.stateChanged.connect(self.applyTraditionalSimplifiedConversion) checkBoxLayout = QHBoxLayout() checkBoxLayout.addWidget(self.changeExtensionCheckBox) checkBoxLayout.addWidget(self.traditionalSimplifiedCheckBox) mainLayout.addLayout(checkBoxLayout) self.tableWidget = QTableWidget() self.tableWidget.setColumnCount(3) self.tableWidget.setHorizontalHeaderLabels(['文件名', '重命名后文件名', '状态']) mainLayout.addWidget(self.tableWidget) self.queryButton = QPushButton('查询文件名') self.queryButton.clicked.connect(self.initiateDatabaseQuery) mainLayout.addWidget(self.queryButton) self.renameButton = QPushButton('开始重命名') self.renameButton.clicked.connect(self.initiateRenaming) mainLayout.addWidget(self.renameButton) self.progressBar = QProgressBar() mainLayout.addWidget(self.progressBar) self.onModeChanged() def onModeChanged(self): isLocalMode = self.localModeRadioButton.isChecked() self.local_db_lineedit.setVisible(isLocalMode) self.selectFolderButton.setVisible(isLocalMode) self.remote_url_lineedit.setVisible(not isLocalMode) def selectDatabase(self): folder_path = QFileDialog.getExistingDirectory(self, "选择数据库文件夹") if folder_path: self.local_db_lineedit.setText(folder_path) def updateTableWithFiles(self, folder_path):
file_list = get_files_from_directory(folder_path)
1
2023-11-10 19:42:58+00:00
4k
debbiemarkslab/popEVE
train_popEVE.py
[ { "identifier": "PGLikelihood", "path": "popEVE/popEVE.py", "snippet": "class PGLikelihood(gpytorch.likelihoods._OneDimensionalLikelihood):\n \"\"\"\n PGLikelihood: Custom likelihood for Gaussian process classification with Pòlya-Gamma data augmentation.\n\n This likelihood is based on the pape...
import argparse import torch import pandas as pd import gpytorch from tqdm import trange from popEVE.popEVE import PGLikelihood, GPModel from utils.helpers import *
1,688
# TODO Have to stop as Luis is awake. # What is currently here is the code from the tutorial # You need to now merge this with other cells from the tutorial to do with handling the data, cuda etc. # You need to also include the bits from the old script that are not present in the turorial # You need to account for changes of file names etc if torch.cuda.is_available(): print("GPU is available!") else: print("GPU is not available. CPU will be used.") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("Device:", device) if __name__=='__main__': parser = argparse.ArgumentParser(description='VAE') parser.add_argument('--mapping_file', type=str, help='List of genes and corresponding training data file path') parser.add_argument('--gene_index', type=int, help='Row index of gene in gene_list') parser.add_argument('--losses_dir', type=str, help='File path for saving losses and lengthscales') parser.add_argument('--scores_dir', type=str, help='File path for saving scores') parser.add_argument('--model_states_dir', type=str, help='File path for model states') parser.add_argument('--seed', type=int, default=42, help='Random seed') args = parser.parse_args() mapping_file = pd.read_csv(args.mapping_file) pid = mapping_file['protein_id'][args.gene_index] unique_id = mapping_file['unique_id'][args.gene_index] training_data_df = pd.read_csv(mapping_file['file_path'][args.gene_index]) losses_and_scales_directory = args.losses_dir scores_directory = args.scores_dir states_directory = args.model_states_dir train_x, train_y, train_variants, heldout_x, heldout_y, heldout_variants, X_min, X_max = get_training_and_holdout_data_from_processed_file(training_data_df, device = device) unique_train_output = train_y.unique(return_counts = True) unique_test_output = heldout_y.unique(return_counts = True) print(f"pid = {pid}") print(f"Tain: y unique = {unique_train_output[0]}, y counts = {unique_train_output[1]}") print(f"Holdout: y unique = {unique_test_output[0]}, y counts = {unique_test_output[1]}") # Initialize the model with M = 20 inducing points M = 20 inducing_points = torch.linspace(0, 1, M, dtype=train_x.dtype, device=train_x.device).unsqueeze(-1)
# TODO Have to stop as Luis is awake. # What is currently here is the code from the tutorial # You need to now merge this with other cells from the tutorial to do with handling the data, cuda etc. # You need to also include the bits from the old script that are not present in the turorial # You need to account for changes of file names etc if torch.cuda.is_available(): print("GPU is available!") else: print("GPU is not available. CPU will be used.") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("Device:", device) if __name__=='__main__': parser = argparse.ArgumentParser(description='VAE') parser.add_argument('--mapping_file', type=str, help='List of genes and corresponding training data file path') parser.add_argument('--gene_index', type=int, help='Row index of gene in gene_list') parser.add_argument('--losses_dir', type=str, help='File path for saving losses and lengthscales') parser.add_argument('--scores_dir', type=str, help='File path for saving scores') parser.add_argument('--model_states_dir', type=str, help='File path for model states') parser.add_argument('--seed', type=int, default=42, help='Random seed') args = parser.parse_args() mapping_file = pd.read_csv(args.mapping_file) pid = mapping_file['protein_id'][args.gene_index] unique_id = mapping_file['unique_id'][args.gene_index] training_data_df = pd.read_csv(mapping_file['file_path'][args.gene_index]) losses_and_scales_directory = args.losses_dir scores_directory = args.scores_dir states_directory = args.model_states_dir train_x, train_y, train_variants, heldout_x, heldout_y, heldout_variants, X_min, X_max = get_training_and_holdout_data_from_processed_file(training_data_df, device = device) unique_train_output = train_y.unique(return_counts = True) unique_test_output = heldout_y.unique(return_counts = True) print(f"pid = {pid}") print(f"Tain: y unique = {unique_train_output[0]}, y counts = {unique_train_output[1]}") print(f"Holdout: y unique = {unique_test_output[0]}, y counts = {unique_test_output[1]}") # Initialize the model with M = 20 inducing points M = 20 inducing_points = torch.linspace(0, 1, M, dtype=train_x.dtype, device=train_x.device).unsqueeze(-1)
model = GPModel(inducing_points=inducing_points)
1
2023-11-17 16:24:18+00:00
4k
fleet-ai/code-pilot
responder.py
[ { "identifier": "get_token", "path": "auth.py", "snippet": "def get_token(installation_id):\n private_key = Path(PRIVATE_KEY_PATH).read_text(encoding=\"utf8\")\n\n # Generate the JWT\n payload = {\n \"iat\": int(time.time()),\n \"exp\": int(time.time()) + (10 * 60),\n \"iss...
import os import json import uuid import asyncio import requests import pinecone from openai import OpenAI from fastapi import APIRouter, Request, Response from auth import get_token from utils.utils import batch from utils.chunk import chunk_nltk from utils.embed import embed_chunks from utils.query import query_index, parse_results from constants import ( MODEL, PROMPT, EMBEDDINGS_MODEL, MAX_CONTEXT_LENGTH_EMBEDDINGS, INDEX_NAME, INDEX_ENVIRONMENT, NAMESPACE, BOT_NAME, ) from dotenv import load_dotenv
1,943
# pylint: disable=unused-argument load_dotenv() router = APIRouter() client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) PINECONE_API_KEY = os.getenv("PINECONE_API_KEY") pinecone.init(api_key=PINECONE_API_KEY, environment=INDEX_ENVIRONMENT) index = pinecone.Index(INDEX_NAME) async def embed_issues(issues): vectors = [] for issue in issues:
# pylint: disable=unused-argument load_dotenv() router = APIRouter() client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) PINECONE_API_KEY = os.getenv("PINECONE_API_KEY") pinecone.init(api_key=PINECONE_API_KEY, environment=INDEX_ENVIRONMENT) index = pinecone.Index(INDEX_NAME) async def embed_issues(issues): vectors = [] for issue in issues:
chunks = chunk_nltk(issue["body"])
2
2023-11-14 01:45:16+00:00
4k
bithuanglq/APF_RL
DQN_variant.py
[ { "identifier": "RelativePosition", "path": "gym_examples/wrappers/relative_position.py", "snippet": "class RelativePosition(gym.ObservationWrapper):\n def __init__(self, env):\n super().__init__(env)\n self.observation_space = spaces.Box(shape=(2+25*6,), low=-np.inf, high=np.inf)\n\n\n...
import argparse import os import random import time import gym import numpy as np import tensorflow as tf import tensorlayer as tl from tqdm import tqdm from gym_examples.wrappers import RelativePosition from prioritized_memory import Memory
3,084
for var in layer.trainable_weights: noise = tf.random.normal(tf.shape(var), 0, self.noise_scale) noises.append(noise) var.assign_add(noise) qvalue = self.qvalue(self.preq(feature)) svalue = self.svalue(self.pres(feature)) if self.noise_scale != 0: idx = 0 for layer in [self.preq, self.qvalue, self.pres, self.svalue]: for var in layer.trainable_weights: var.assign_sub(noises[idx]) idx += 1 if dueling: # dueling network return svalue + qvalue - tf.reduce_mean(qvalue, 1, keepdims=True) else: return qvalue # ############################## Original Replay Buffer #################################### class ReplayBuffer(object): def __init__(self, size): self._storage = [] #保存的容器 self._maxsize = size #容器最大的size self._next_idx = 0 #指针,表示当前新增位置 #查询这个容器的大小 def __len__(self): return len(self._storage) #把信息放入buffer def add(self, *args): r = args[2] #如果当前指针大于容器目前大小,那么扩展容器,append数据 if self._next_idx >= len(self._storage): self._storage.append(args) #如果不是,直接写进去就可以了。 else: self._storage[self._next_idx] = args #这是一个循环指针 self._next_idx = (self._next_idx + 1) % self._maxsize #对 def _encode_sample(self, idxes): b_o, b_a, b_r, b_o_, b_d = [], [], [], [], [] for i in idxes: o, a, r, o_, d = self._storage[i] b_o.append(o) b_a.append(a) b_r.append(r) b_o_.append(o_) b_d.append(d) return ( np.stack(b_o).astype('float32') * ob_scale, np.stack(b_a).astype('int32'), np.stack(b_r).astype('float32'), np.stack(b_o_).astype('float32') * ob_scale, np.stack(b_d).astype('float32'), ) #抽取数据 def sample(self, batch_size): indexes = [i for i in range(len(self._storage))] idxes = [random.choice(indexes) for _ in range(batch_size)] return self._encode_sample(idxes) # ############################# Functions ################################### def huber_loss(x): """Loss function for value""" return tf.where(tf.abs(x) < 1, tf.square(x) * 0.5, tf.abs(x) - 0.5) def sync(net, net_tar): """Copy q network to target q network""" for var, var_tar in zip(net.trainable_weights, net_tar.trainable_weights): var_tar.assign(var) def log_softmax(x, dim): temp = x - np.max(x, dim, keepdims=True) return temp - np.log(np.exp(temp).sum(dim, keepdims=True)) def softmax(x, dim): temp = np.exp(x - np.max(x, dim, keepdims=True)) return temp / temp.sum(dim, keepdims=True) ##################### DQN with PER ########################## class DQN(object): def __init__(self): model = MLP if qnet_type == 'MLP' else CNN self.qnet = model('q') if args.mode == 'train': self.qnet.train() self.targetqnet = model('targetq') self.targetqnet.infer() sync(self.qnet, self.targetqnet) else: self.qnet.infer() print("Begin loading ... \n\n") tl.files.load_and_assign_npz_dict(name=args.save_path, network=self.qnet) print("Successfully loaded ... \n\n") self.niter = 0 if clipnorm is not None: self.optimizer = tf.optimizers.Adam(learning_rate=lr, clipnorm=clipnorm) else: self.optimizer = tf.optimizers.Adam(learning_rate=lr) self.noise_scale = noise_scale
''' 调试日志 1. 适配版本 https://medium.com/mlearning-ai/how-to-install-tensorflow-2-x-with-cuda-and-cudnn-on-ubuntu-20-04-lts-b73c209d8e88 2. 要用save_npz_dict 保存模型而不是 save_npz; 加载时同理 3. 用 APF 代替部分随机探索效果要好很多 4. 加入了PER: (https://blog.csdn.net/abcdefg90876/article/details/106270925), 也可以只用Original Replay Buffer 5. 超参数参考模块: hyper parameters ''' ''' GridWorld-v0: @Action -- 0 right, 1 up, 2 left, 3 down @Observation -- {[x1, y1], [x2, y2], 25 vector(6,)}, agent_loc, target_loc and surrounding states. @Info -- distance between agent and target ''' parser = argparse.ArgumentParser() parser.add_argument('--mode', help='train or test', default='train') parser.add_argument( '--save_path', default='dqn_variants', help='folder to save if mode == train else model path,' 'qnet will be saved once target net update' ) parser.add_argument('--seed', help='random seed', type=int, default=0) parser.add_argument('--noisy_scale', type=float, default=1e-2) parser.add_argument('--disable_double', action='store_false', default=True) parser.add_argument('--disable_dueling', action='store_false', default=False) args = parser.parse_args() if args.mode == 'train': os.makedirs(args.save_path, exist_ok=True) random.seed(args.seed) np.random.seed(args.seed) tf.random.set_seed(args.seed) # reproducible noise_scale = args.noisy_scale double = not args.disable_double dueling = not args.disable_dueling env = gym.make('gym_examples/GridWorld-v0', render_mode='human') env = RelativePosition(env) # refer to gym_examples/wrappers/relative_position.py, observation space has changed! # #################### hyper parameters #################### qnet_type = 'MLP' number_timesteps = 10000 # total number of time steps to train on test_number_timesteps = 1000 # in test phase explore_timesteps = number_timesteps # epsilon-greedy schedule, final exploit prob is 0.99 epsilon = lambda i_iter: (1 - 0.99 * min(1, i_iter / explore_timesteps)) * 0.8 lr = 5e-3 # learning rate buffer_size = explore_timesteps//10*200 # replay buffer size target_q_update_freq = 100 # how frequency target q net update ob_scale = 1.0 # scale observations clipnorm = None in_dim = env.observation_space.shape out_dim = env.action_space.n reward_gamma = 0.99 # reward discount batch_size = 128 # batch size for sampling from replay buffer warm_start = batch_size*2 # sample times befor learning noise_update_freq = 50 # how frequency param noise net update # ############################## Network #################################### class MLP(tl.models.Model): def __init__(self, name): super(MLP, self).__init__(name=name) hidden_dim = 256 self.h1 = tl.layers.Dense(hidden_dim, tf.nn.tanh, in_channels=in_dim[0]) self.qvalue = tl.layers.Dense(out_dim, in_channels=hidden_dim, name='q', W_init=tf.initializers.GlorotUniform(), b_init=tf.constant_initializer(0.1)) self.svalue = tl.layers.Dense(1, in_channels=hidden_dim, name='s', W_init=tf.initializers.GlorotUniform(), b_init=tf.constant_initializer(0.1)) self.noise_scale = 0 def forward(self, ni): feature = self.h1(ni) # apply noise to all linear layer if self.noise_scale != 0: noises = [] for layer in [self.qvalue, self.svalue]: for var in layer.trainable_weights: noise = tf.random.normal(tf.shape(var), 0, self.noise_scale) noises.append(noise) var.assign_add(noise) qvalue = self.qvalue(feature) svalue = self.svalue(feature) if self.noise_scale != 0: idx = 0 for layer in [self.qvalue, self.svalue]: for var in layer.trainable_weights: var.assign_sub(noises[idx]) idx += 1 if dueling: # dueling network return svalue + qvalue - tf.reduce_mean(qvalue, 1, keepdims=True) else: return qvalue class CNN(tl.models.Model): def __init__(self, name): super(CNN, self).__init__(name=name) h, w, in_channels = in_dim dense_in_channels = 64 * ((h - 28) // 8) * ((w - 28) // 8) self.conv1 = tl.layers.Conv2d( 32, (8, 8), (4, 4), tf.nn.relu, 'VALID', in_channels=in_channels, name='conv2d_1', W_init=tf.initializers.GlorotUniform() ) self.conv2 = tl.layers.Conv2d( 64, (4, 4), (2, 2), tf.nn.relu, 'VALID', in_channels=32, name='conv2d_2', W_init=tf.initializers.GlorotUniform() ) self.conv3 = tl.layers.Conv2d( 64, (3, 3), (1, 1), tf.nn.relu, 'VALID', in_channels=64, name='conv2d_3', W_init=tf.initializers.GlorotUniform() ) self.flatten = tl.layers.Flatten(name='flatten') self.preq = tl.layers.Dense( 256, tf.nn.relu, in_channels=dense_in_channels, name='pre_q', W_init=tf.initializers.GlorotUniform() ) self.qvalue = tl.layers.Dense(out_dim, in_channels=256, name='q', W_init=tf.initializers.GlorotUniform()) self.pres = tl.layers.Dense( 256, tf.nn.relu, in_channels=dense_in_channels, name='pre_s', W_init=tf.initializers.GlorotUniform() ) self.svalue = tl.layers.Dense(1, in_channels=256, name='state', W_init=tf.initializers.GlorotUniform()) self.noise_scale = 0 def forward(self, ni): feature = self.flatten(self.conv3(self.conv2(self.conv1(ni)))) # apply noise to all linear layer if self.noise_scale != 0: noises = [] for layer in [self.preq, self.qvalue, self.pres, self.svalue]: for var in layer.trainable_weights: noise = tf.random.normal(tf.shape(var), 0, self.noise_scale) noises.append(noise) var.assign_add(noise) qvalue = self.qvalue(self.preq(feature)) svalue = self.svalue(self.pres(feature)) if self.noise_scale != 0: idx = 0 for layer in [self.preq, self.qvalue, self.pres, self.svalue]: for var in layer.trainable_weights: var.assign_sub(noises[idx]) idx += 1 if dueling: # dueling network return svalue + qvalue - tf.reduce_mean(qvalue, 1, keepdims=True) else: return qvalue # ############################## Original Replay Buffer #################################### class ReplayBuffer(object): def __init__(self, size): self._storage = [] #保存的容器 self._maxsize = size #容器最大的size self._next_idx = 0 #指针,表示当前新增位置 #查询这个容器的大小 def __len__(self): return len(self._storage) #把信息放入buffer def add(self, *args): r = args[2] #如果当前指针大于容器目前大小,那么扩展容器,append数据 if self._next_idx >= len(self._storage): self._storage.append(args) #如果不是,直接写进去就可以了。 else: self._storage[self._next_idx] = args #这是一个循环指针 self._next_idx = (self._next_idx + 1) % self._maxsize #对 def _encode_sample(self, idxes): b_o, b_a, b_r, b_o_, b_d = [], [], [], [], [] for i in idxes: o, a, r, o_, d = self._storage[i] b_o.append(o) b_a.append(a) b_r.append(r) b_o_.append(o_) b_d.append(d) return ( np.stack(b_o).astype('float32') * ob_scale, np.stack(b_a).astype('int32'), np.stack(b_r).astype('float32'), np.stack(b_o_).astype('float32') * ob_scale, np.stack(b_d).astype('float32'), ) #抽取数据 def sample(self, batch_size): indexes = [i for i in range(len(self._storage))] idxes = [random.choice(indexes) for _ in range(batch_size)] return self._encode_sample(idxes) # ############################# Functions ################################### def huber_loss(x): """Loss function for value""" return tf.where(tf.abs(x) < 1, tf.square(x) * 0.5, tf.abs(x) - 0.5) def sync(net, net_tar): """Copy q network to target q network""" for var, var_tar in zip(net.trainable_weights, net_tar.trainable_weights): var_tar.assign(var) def log_softmax(x, dim): temp = x - np.max(x, dim, keepdims=True) return temp - np.log(np.exp(temp).sum(dim, keepdims=True)) def softmax(x, dim): temp = np.exp(x - np.max(x, dim, keepdims=True)) return temp / temp.sum(dim, keepdims=True) ##################### DQN with PER ########################## class DQN(object): def __init__(self): model = MLP if qnet_type == 'MLP' else CNN self.qnet = model('q') if args.mode == 'train': self.qnet.train() self.targetqnet = model('targetq') self.targetqnet.infer() sync(self.qnet, self.targetqnet) else: self.qnet.infer() print("Begin loading ... \n\n") tl.files.load_and_assign_npz_dict(name=args.save_path, network=self.qnet) print("Successfully loaded ... \n\n") self.niter = 0 if clipnorm is not None: self.optimizer = tf.optimizers.Adam(learning_rate=lr, clipnorm=clipnorm) else: self.optimizer = tf.optimizers.Adam(learning_rate=lr) self.noise_scale = noise_scale
self.memory = Memory(buffer_size)
1
2023-11-10 02:45:37+00:00
4k
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,581
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)
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(
0
2023-11-18 05:42:54+00:00
4k
cyberark/ark-sdk-python
tests/unit/auth/test_ark_isp_auth.py
[ { "identifier": "ArkISPAuth", "path": "ark_sdk_python/auth/ark_isp_auth.py", "snippet": "class ArkISPAuth(ArkAuth):\n def __perform_identity_authentication(\n self, profile: ArkProfile, auth_profile: ArkAuthProfile, secret: Optional[ArkSecret], force: bool\n ) -> ArkToken:\n try:\n ...
import os import pytest from datetime import datetime, timedelta from unittest.mock import MagicMock from pytest_mock import MockerFixture from requests.auth import HTTPBasicAuth from ark_sdk_python.auth import ArkISPAuth from ark_sdk_python.models.auth import ArkAuthMethod, ArkSecret, ArkToken from tests.unit.helpers import ( ADVANCE_AUTH_SUCCESS_RESPONSE, OAUTH_AUTHORIZE_SUCCESS_RESPONSE, OAUTH_TOKEN_SUCCESS_RESPONSE, START_AUTH_SUCCESS_RESPONSE, generate_auth_profile_for, generate_profile_for, )
2,882
class TestArkISPAuth: @pytest.fixture(scope='module', autouse=True) def env_config(self): os.environ.update({'DEPLOY_ENV': 'prod'}) @pytest.mark.parametrize('auth_method', [ArkAuthMethod.Default, ArkAuthMethod.Identity]) @pytest.mark.parametrize('from_profile', ['Yes', 'No', 'Both']) def test_identity_auth_method(self, mocker: MockerFixture, auth_method: ArkAuthMethod, from_profile: str): tenant_fqdn_mock = mocker.patch( 'ark_sdk_python.auth.identity.ark_identity_fqdn_resolver.ArkIdentityFQDNResolver.resolve_tenant_fqdn_from_tenant_suffix' ) tenant_fqdn_mock.return_value = 'https://url.com' session_mock = mocker.patch('ark_sdk_python.auth.identity.ark_identity.Session') session_mock.return_value.post = MagicMock()
class TestArkISPAuth: @pytest.fixture(scope='module', autouse=True) def env_config(self): os.environ.update({'DEPLOY_ENV': 'prod'}) @pytest.mark.parametrize('auth_method', [ArkAuthMethod.Default, ArkAuthMethod.Identity]) @pytest.mark.parametrize('from_profile', ['Yes', 'No', 'Both']) def test_identity_auth_method(self, mocker: MockerFixture, auth_method: ArkAuthMethod, from_profile: str): tenant_fqdn_mock = mocker.patch( 'ark_sdk_python.auth.identity.ark_identity_fqdn_resolver.ArkIdentityFQDNResolver.resolve_tenant_fqdn_from_tenant_suffix' ) tenant_fqdn_mock.return_value = 'https://url.com' session_mock = mocker.patch('ark_sdk_python.auth.identity.ark_identity.Session') session_mock.return_value.post = MagicMock()
session_mock.return_value.post.side_effect = [START_AUTH_SUCCESS_RESPONSE, ADVANCE_AUTH_SUCCESS_RESPONSE]
4
2023-11-13 09:24:31+00:00
4k
Infineon/pharaoh-dev
src/pharaoh/templating/first_level/render.py
[ { "identifier": "find_template", "path": "src/pharaoh/templating/first_level/find.py", "snippet": "def find_template(template: str) -> Path:\n from pharaoh.plugins.plugin_manager import PM\n\n templates = PM.pharaoh_collect_l1_templates()\n if isinstance(template, str):\n if template in ...
import ast import json import tempfile import typing as t from pathlib import Path from .find import find_template from .scaffolder import Scaffolder
1,988
from __future__ import annotations def render_template(template_path: Path, outputdir: Path, context: dict | None = None) -> Path: if template_path.is_dir(): return render_template_directory(template_path, outputdir, context) if template_path.is_file(): return render_template_file(template_path, outputdir, context) raise NotImplementedError def render_template_directory(template_path: Path, outputdir: Path, context: dict | None = None) -> Path: outputdir.mkdir(parents=True, exist_ok=True) assert template_path.is_dir(), f"{template_path} is not a directory!" Scaffolder(source_dir=template_path, target_dir=outputdir, render_context=context).run() if isinstance(context, dict): context_dump_file = outputdir / ".template_context.json" context_dump_file.write_text(json.dumps(context, indent=2)) return outputdir def render_template_file(template_path: Path, outputdir: Path, context: dict | None = None) -> Path: if [suffix.lower() for suffix in template_path.suffixes] != [".pharaoh", ".py"]: msg = "If template_path is a file, only files with .pharaoh.py suffix are supported!" raise ValueError(msg) with tempfile.TemporaryDirectory(prefix="pharaoh_") as tdir: tempdir = Path(tdir) template_content = template_path.read_text(encoding="utf-8") tree = ast.parse(template_content) module_docstring = (ast.get_docstring(tree) or "").strip() stem = ".".join(template_path.name.split(".")[:-2]) asset_scripts = tempdir / "asset_scripts" asset_scripts.mkdir() (asset_scripts / f"{stem}.py").write_text(template_content, encoding="utf-8") if module_docstring: (tempdir / f"index_{stem}.rst").write_text(module_docstring, encoding="utf-8") return render_template_directory(tempdir, outputdir, context) def render_sphinx_base_project(outputdir: Path, templates: t.Iterable[str], context: dict | None = None): for templ in templates: render_template_directory(
from __future__ import annotations def render_template(template_path: Path, outputdir: Path, context: dict | None = None) -> Path: if template_path.is_dir(): return render_template_directory(template_path, outputdir, context) if template_path.is_file(): return render_template_file(template_path, outputdir, context) raise NotImplementedError def render_template_directory(template_path: Path, outputdir: Path, context: dict | None = None) -> Path: outputdir.mkdir(parents=True, exist_ok=True) assert template_path.is_dir(), f"{template_path} is not a directory!" Scaffolder(source_dir=template_path, target_dir=outputdir, render_context=context).run() if isinstance(context, dict): context_dump_file = outputdir / ".template_context.json" context_dump_file.write_text(json.dumps(context, indent=2)) return outputdir def render_template_file(template_path: Path, outputdir: Path, context: dict | None = None) -> Path: if [suffix.lower() for suffix in template_path.suffixes] != [".pharaoh", ".py"]: msg = "If template_path is a file, only files with .pharaoh.py suffix are supported!" raise ValueError(msg) with tempfile.TemporaryDirectory(prefix="pharaoh_") as tdir: tempdir = Path(tdir) template_content = template_path.read_text(encoding="utf-8") tree = ast.parse(template_content) module_docstring = (ast.get_docstring(tree) or "").strip() stem = ".".join(template_path.name.split(".")[:-2]) asset_scripts = tempdir / "asset_scripts" asset_scripts.mkdir() (asset_scripts / f"{stem}.py").write_text(template_content, encoding="utf-8") if module_docstring: (tempdir / f"index_{stem}.rst").write_text(module_docstring, encoding="utf-8") return render_template_directory(tempdir, outputdir, context) def render_sphinx_base_project(outputdir: Path, templates: t.Iterable[str], context: dict | None = None): for templ in templates: render_template_directory(
template_path=find_template(templ),
0
2023-11-10 11:33:02+00:00
4k
eblume/TyperAssistant
src/typerassistant/typer.py
[ { "identifier": "Assistant", "path": "src/typerassistant/assistant.py", "snippet": "MAX_RUN_ITERATIONS = 20\nRUN_ITERATION_SLEEP = 3\nclass Assistant:\n def from_id(cls: Type[AssistantT], assistant_id: str, client: Optional[OpenAI] = None) -> AssistantT:\n def assistant(self) -> RemoteAssistant:\n...
import sys import typer from dataclasses import KW_ONLY, dataclass, field from typing import Callable, Iterable, Optional, Type from openai import OpenAI from typer.main import get_command_from_info from .assistant import Assistant, AssistantT from .spec import FunctionSpec, ParameterSpec
1,785
from __future__ import annotations @dataclass class TyperAssistant(Assistant): """An Assistant generated from a Typer app.""" app: typer.Typer _: KW_ONLY instructions: str = "The agent is an interface to a python Typer CLI. The tools available correspond to typer commands. Please help the user with their queries, executing CLI functions as needed. Be concise, but don't shorten the function names even if they look like file paths." name: str = field(init=False) def __post_init__(self): # In AppAssistant, we always infer the name self.name = self.app.info.name or sys.argv[0] @classmethod def from_id(cls: Type[AssistantT], assistant_id: str, client: Optional[OpenAI] = None) -> AssistantT: """from_id is disabled for TyperAssistant, use from_id_with_app instead.""" # TODO this is ugly and bad but I could not find a way to satisfy LSP. # Even uglier: to get the unused variable warning to go away, these two asserts: assert client or True assert assistant_id or True # Just an ugly, ugly function. Two out of five stars. I'm sorry. raise NotImplementedError("from_id is disabled for TyperAssistant, use from_id_with_app instead.") @classmethod def from_id_with_app(cls, assistant_id: str, app: typer.Typer, client: Optional[OpenAI] = None) -> TyperAssistant: if client is None: client = OpenAI() assistant = client.beta.assistants.retrieve(assistant_id) return TyperAssistant( app=app, client=client, instructions=assistant.instructions or cls.instructions, _assistant=assistant ) def functions(self) -> Iterable[FunctionSpec]: """Generate FunctionSpecs from the Typer app.""" yield from super().functions() # currently a non-op but may be useful to others for func in typerfunc(self.app): yield func def register_assistant( app: typer.Typer, command_name: str = "ask", client: Optional[OpenAI] = None, client_factory: Optional[Callable[[], OpenAI]] = None, ) -> None: """Create a command for the typer application that queries an automatically generated assistant.""" if client is not None and client_factory is not None: raise ValueError("Cannot specify both client and client_factory") if client_factory is not None: client = client_factory() elif client is None: client = OpenAI() def _ask_command( query: str, use_commands: bool = True, confirm_commands: bool = False, replace_assistant: bool = False ): """Ask an assistant for help, optionally using other commands from this application.""" assistant = TyperAssistant(app=app, replace=replace_assistant) print(assistant.ask(query, use_commands=use_commands, confirm_commands=confirm_commands)) app.command(command_name, context_settings={"obj": {"omit_from_assistant": True}})(_ask_command) def typerfunc(app: typer.Typer, command_prefix: Optional[str] = None) -> list[FunctionSpec]: """Returns a list of FunctionSpecs describing the CLI of app. This function recurses on command groups, with a command_prefix appended to the beginning of each command name in that group. Omits commands with context_settings['omit_from_assistant'] set to True. """ if command_prefix is None: if isinstance(app.info.name, str): command_prefix = app.info.name else: command_prefix = sys.argv[0] functions: list[FunctionSpec] = [] for command_info in app.registered_commands or []: if command_info.context_settings and command_info.context_settings.get("omit_from_assistant", False): continue command = get_command_from_info( command_info=command_info, pretty_exceptions_short=app.pretty_exceptions_short, rich_markup_mode=app.rich_markup_mode, ) assert command.name is not None # I'm not sure where it happens, but it's documented here: https://typer.tiangolo.com/tutorial/commands/name/ # "Note that any underscores in the function name will be replaced with dashes." # Therefore, convert all dashes back to underscores. *shrug* fullname = f"{command_prefix}.{command.name.replace('-', '_')}" # Extract callback signature for parameters. params = [] for param in command.params: descr = getattr(param, "help", "None") assert param.name is not None
from __future__ import annotations @dataclass class TyperAssistant(Assistant): """An Assistant generated from a Typer app.""" app: typer.Typer _: KW_ONLY instructions: str = "The agent is an interface to a python Typer CLI. The tools available correspond to typer commands. Please help the user with their queries, executing CLI functions as needed. Be concise, but don't shorten the function names even if they look like file paths." name: str = field(init=False) def __post_init__(self): # In AppAssistant, we always infer the name self.name = self.app.info.name or sys.argv[0] @classmethod def from_id(cls: Type[AssistantT], assistant_id: str, client: Optional[OpenAI] = None) -> AssistantT: """from_id is disabled for TyperAssistant, use from_id_with_app instead.""" # TODO this is ugly and bad but I could not find a way to satisfy LSP. # Even uglier: to get the unused variable warning to go away, these two asserts: assert client or True assert assistant_id or True # Just an ugly, ugly function. Two out of five stars. I'm sorry. raise NotImplementedError("from_id is disabled for TyperAssistant, use from_id_with_app instead.") @classmethod def from_id_with_app(cls, assistant_id: str, app: typer.Typer, client: Optional[OpenAI] = None) -> TyperAssistant: if client is None: client = OpenAI() assistant = client.beta.assistants.retrieve(assistant_id) return TyperAssistant( app=app, client=client, instructions=assistant.instructions or cls.instructions, _assistant=assistant ) def functions(self) -> Iterable[FunctionSpec]: """Generate FunctionSpecs from the Typer app.""" yield from super().functions() # currently a non-op but may be useful to others for func in typerfunc(self.app): yield func def register_assistant( app: typer.Typer, command_name: str = "ask", client: Optional[OpenAI] = None, client_factory: Optional[Callable[[], OpenAI]] = None, ) -> None: """Create a command for the typer application that queries an automatically generated assistant.""" if client is not None and client_factory is not None: raise ValueError("Cannot specify both client and client_factory") if client_factory is not None: client = client_factory() elif client is None: client = OpenAI() def _ask_command( query: str, use_commands: bool = True, confirm_commands: bool = False, replace_assistant: bool = False ): """Ask an assistant for help, optionally using other commands from this application.""" assistant = TyperAssistant(app=app, replace=replace_assistant) print(assistant.ask(query, use_commands=use_commands, confirm_commands=confirm_commands)) app.command(command_name, context_settings={"obj": {"omit_from_assistant": True}})(_ask_command) def typerfunc(app: typer.Typer, command_prefix: Optional[str] = None) -> list[FunctionSpec]: """Returns a list of FunctionSpecs describing the CLI of app. This function recurses on command groups, with a command_prefix appended to the beginning of each command name in that group. Omits commands with context_settings['omit_from_assistant'] set to True. """ if command_prefix is None: if isinstance(app.info.name, str): command_prefix = app.info.name else: command_prefix = sys.argv[0] functions: list[FunctionSpec] = [] for command_info in app.registered_commands or []: if command_info.context_settings and command_info.context_settings.get("omit_from_assistant", False): continue command = get_command_from_info( command_info=command_info, pretty_exceptions_short=app.pretty_exceptions_short, rich_markup_mode=app.rich_markup_mode, ) assert command.name is not None # I'm not sure where it happens, but it's documented here: https://typer.tiangolo.com/tutorial/commands/name/ # "Note that any underscores in the function name will be replaced with dashes." # Therefore, convert all dashes back to underscores. *shrug* fullname = f"{command_prefix}.{command.name.replace('-', '_')}" # Extract callback signature for parameters. params = [] for param in command.params: descr = getattr(param, "help", "None") assert param.name is not None
param_spec = ParameterSpec(
2
2023-11-17 19:43:55+00:00
4k
Mat931/digitalstrom-homeassistant
custom_components/digitalstrom/sensor.py
[ { "identifier": "CONF_DSUID", "path": "custom_components/digitalstrom/const.py", "snippet": "CONF_DSUID: str = \"dsuid\"" }, { "identifier": "DOMAIN", "path": "custom_components/digitalstrom/const.py", "snippet": "DOMAIN = \"digitalstrom\"" }, { "identifier": "DigitalstromEntity"...
import logging from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, DEGREE, LIGHT_LUX, PERCENTAGE, UnitOfApparentPower, UnitOfElectricCurrent, UnitOfEnergy, UnitOfLength, UnitOfMass, UnitOfPower, UnitOfPressure, UnitOfSoundPressure, UnitOfSpeed, UnitOfTemperature, UnitOfTime, UnitOfVolume, UnitOfVolumeFlowRate, UnitOfVolumetricFlux, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import CONF_DSUID, DOMAIN from .entity import DigitalstromEntity
2,579
state_class=SensorStateClass.MEASUREMENT, ), 50: SensorEntityDescription( key="50", name="Room Temperature Set Point", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), 51: SensorEntityDescription( key="51", name="Room Temperature Control Variable", native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, ), 64: SensorEntityDescription( key="64", name="Output Current", native_unit_of_measurement=UnitOfElectricCurrent.MILLIAMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, ), 65: SensorEntityDescription( key="65", name="Apparent Power", native_unit_of_measurement=UnitOfApparentPower.VOLT_AMPERE, device_class=SensorDeviceClass.APPARENT_POWER, state_class=SensorStateClass.MEASUREMENT, ), 66: SensorEntityDescription( key="66", name="Temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), 67: SensorEntityDescription( key="67", name="Brightness", native_unit_of_measurement=LIGHT_LUX, device_class=SensorDeviceClass.ILLUMINANCE, state_class=SensorStateClass.MEASUREMENT, ), 68: SensorEntityDescription( key="68", name="Relative Humidity", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, ), 69: SensorEntityDescription( key="69", name="Generated Active Power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), 70: SensorEntityDescription( key="70", name="Generated Energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), 71: SensorEntityDescription( key="71", name="Water Quantity", native_unit_of_measurement=UnitOfVolume.LITERS, device_class=SensorDeviceClass.WATER, state_class=SensorStateClass.MEASUREMENT, ), 72: SensorEntityDescription( key="72", name="Water Flow Rate", # Conversion from "L/s" to CUBIC_METERS_PER_HOUR: (value * 3.6) native_unit_of_measurement=UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR, state_class=SensorStateClass.MEASUREMENT, ), 73: SensorEntityDescription( key="73", name="Length", native_unit_of_measurement=UnitOfLength.METERS, device_class=SensorDeviceClass.DISTANCE, state_class=SensorStateClass.MEASUREMENT, ), 74: SensorEntityDescription( key="74", name="Mass", native_unit_of_measurement=UnitOfMass.GRAMS, device_class=SensorDeviceClass.WEIGHT, state_class=SensorStateClass.MEASUREMENT, ), 75: SensorEntityDescription( key="75", name="Time", native_unit_of_measurement=UnitOfTime.SECONDS, device_class=SensorDeviceClass.DURATION, state_class=SensorStateClass.MEASUREMENT, ), 76: SensorEntityDescription( key="76", name="Sun azimuth", native_unit_of_measurement=DEGREE, state_class=SensorStateClass.MEASUREMENT, ), 77: SensorEntityDescription( key="77", name="Sun elevation", native_unit_of_measurement=DEGREE, state_class=SensorStateClass.MEASUREMENT, ), } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the sensor platform."""
_LOGGER = logging.getLogger(__name__) SENSORS_MAP: dict[int, SensorEntityDescription] = { -1: SensorEntityDescription( key="unknown", name="Unknown sensor", ), 4: SensorEntityDescription( key="4", name="Active Power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), 5: SensorEntityDescription( key="5", name="Output Current", native_unit_of_measurement=UnitOfElectricCurrent.MILLIAMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, ), 6: SensorEntityDescription( key="6", name="Energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), 9: SensorEntityDescription( key="9", name="Room Temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), 10: SensorEntityDescription( key="10", name="Outdoor Temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), 11: SensorEntityDescription( key="11", name="Room Brightness", native_unit_of_measurement=LIGHT_LUX, device_class=SensorDeviceClass.ILLUMINANCE, state_class=SensorStateClass.MEASUREMENT, ), 12: SensorEntityDescription( key="12", name="Outdoor Brightness", native_unit_of_measurement=LIGHT_LUX, device_class=SensorDeviceClass.ILLUMINANCE, state_class=SensorStateClass.MEASUREMENT, ), 13: SensorEntityDescription( key="13", name="Room Relative Humidity", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, ), 14: SensorEntityDescription( key="14", name="Outdoor Relative Humidity", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, ), 15: SensorEntityDescription( key="15", name="Air pressure", native_unit_of_measurement=UnitOfPressure.HPA, device_class=SensorDeviceClass.ATMOSPHERIC_PRESSURE, state_class=SensorStateClass.MEASUREMENT, ), 16: SensorEntityDescription( key="16", name="Wind gust speed", native_unit_of_measurement=UnitOfSpeed.METERS_PER_SECOND, device_class=SensorDeviceClass.WIND_SPEED, state_class=SensorStateClass.MEASUREMENT, ), 17: SensorEntityDescription( key="17", name="Wind gust direction", native_unit_of_measurement=DEGREE, state_class=SensorStateClass.MEASUREMENT, ), 18: SensorEntityDescription( key="18", name="Wind speed average", native_unit_of_measurement=UnitOfSpeed.METERS_PER_SECOND, device_class=SensorDeviceClass.WIND_SPEED, state_class=SensorStateClass.MEASUREMENT, ), 19: SensorEntityDescription( key="19", name="Wind direction", native_unit_of_measurement=DEGREE, state_class=SensorStateClass.MEASUREMENT, ), 20: SensorEntityDescription( key="20", name="Precipitation intensity of last hour", native_unit_of_measurement=UnitOfVolumetricFlux.MILLIMETERS_PER_HOUR, device_class=SensorDeviceClass.PRECIPITATION_INTENSITY, state_class=SensorStateClass.MEASUREMENT, ), 21: SensorEntityDescription( key="21", name="Room Carbon Dioxide Concentration", native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION, device_class=SensorDeviceClass.CO2, state_class=SensorStateClass.MEASUREMENT, ), 22: SensorEntityDescription( key="22", name="Room Carbon Monoxide Concentration", native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION, device_class=SensorDeviceClass.CO, state_class=SensorStateClass.MEASUREMENT, ), 25: SensorEntityDescription( key="25", name="Sound Pressure Level", native_unit_of_measurement=UnitOfSoundPressure.DECIBEL, device_class=SensorDeviceClass.SOUND_PRESSURE, state_class=SensorStateClass.MEASUREMENT, ), 50: SensorEntityDescription( key="50", name="Room Temperature Set Point", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), 51: SensorEntityDescription( key="51", name="Room Temperature Control Variable", native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, ), 64: SensorEntityDescription( key="64", name="Output Current", native_unit_of_measurement=UnitOfElectricCurrent.MILLIAMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, ), 65: SensorEntityDescription( key="65", name="Apparent Power", native_unit_of_measurement=UnitOfApparentPower.VOLT_AMPERE, device_class=SensorDeviceClass.APPARENT_POWER, state_class=SensorStateClass.MEASUREMENT, ), 66: SensorEntityDescription( key="66", name="Temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), 67: SensorEntityDescription( key="67", name="Brightness", native_unit_of_measurement=LIGHT_LUX, device_class=SensorDeviceClass.ILLUMINANCE, state_class=SensorStateClass.MEASUREMENT, ), 68: SensorEntityDescription( key="68", name="Relative Humidity", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, ), 69: SensorEntityDescription( key="69", name="Generated Active Power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), 70: SensorEntityDescription( key="70", name="Generated Energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), 71: SensorEntityDescription( key="71", name="Water Quantity", native_unit_of_measurement=UnitOfVolume.LITERS, device_class=SensorDeviceClass.WATER, state_class=SensorStateClass.MEASUREMENT, ), 72: SensorEntityDescription( key="72", name="Water Flow Rate", # Conversion from "L/s" to CUBIC_METERS_PER_HOUR: (value * 3.6) native_unit_of_measurement=UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR, state_class=SensorStateClass.MEASUREMENT, ), 73: SensorEntityDescription( key="73", name="Length", native_unit_of_measurement=UnitOfLength.METERS, device_class=SensorDeviceClass.DISTANCE, state_class=SensorStateClass.MEASUREMENT, ), 74: SensorEntityDescription( key="74", name="Mass", native_unit_of_measurement=UnitOfMass.GRAMS, device_class=SensorDeviceClass.WEIGHT, state_class=SensorStateClass.MEASUREMENT, ), 75: SensorEntityDescription( key="75", name="Time", native_unit_of_measurement=UnitOfTime.SECONDS, device_class=SensorDeviceClass.DURATION, state_class=SensorStateClass.MEASUREMENT, ), 76: SensorEntityDescription( key="76", name="Sun azimuth", native_unit_of_measurement=DEGREE, state_class=SensorStateClass.MEASUREMENT, ), 77: SensorEntityDescription( key="77", name="Sun elevation", native_unit_of_measurement=DEGREE, state_class=SensorStateClass.MEASUREMENT, ), } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the sensor platform."""
apartment = hass.data[DOMAIN][config_entry.data[CONF_DSUID]]["apartment"]
0
2023-11-10 16:42:38+00:00
4k
mohenghui/detectAuto_v8
ultralytics/nn/modules/block.py
[ { "identifier": "Conv", "path": "ultralytics/nn/modules/conv.py", "snippet": "class Conv(nn.Module):\n \"\"\"Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation).\"\"\"\n default_act = nn.SiLU() # default activation\n\n def __init__(self, c1, c2,...
import torch import torch.nn as nn import torch.nn.functional as F from .conv import Conv, DWConv, GhostConv, LightConv, RepConv from .transformer import TransformerBlock
2,735
# Ultralytics YOLO 🚀, AGPL-3.0 license """Block modules.""" __all__ = ('DFL', 'HGBlock', 'HGStem', 'SPP', 'SPPF', 'C1', 'C2', 'C3', 'C2f', 'C3x', 'C3TR', 'C3Ghost', 'GhostBottleneck', 'Bottleneck', 'BottleneckCSP', 'Proto', 'RepC3') class DFL(nn.Module): """ Integral module of Distribution Focal Loss (DFL). Proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391 """ def __init__(self, c1=16): """Initialize a convolutional layer with a given number of input channels.""" super().__init__() self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False) x = torch.arange(c1, dtype=torch.float) self.conv.weight.data[:] = nn.Parameter(x.view(1, c1, 1, 1)) self.c1 = c1 def forward(self, x): """Applies a transformer layer on input tensor 'x' and returns a tensor.""" b, c, a = x.shape # batch, channels, anchors return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a) # return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a) class Proto(nn.Module): """YOLOv8 mask Proto module for segmentation models.""" def __init__(self, c1, c_=256, c2=32): """ Initializes the YOLOv8 mask Proto module with specified number of protos and masks. Input arguments are ch_in, number of protos, number of masks. """ super().__init__()
# Ultralytics YOLO 🚀, AGPL-3.0 license """Block modules.""" __all__ = ('DFL', 'HGBlock', 'HGStem', 'SPP', 'SPPF', 'C1', 'C2', 'C3', 'C2f', 'C3x', 'C3TR', 'C3Ghost', 'GhostBottleneck', 'Bottleneck', 'BottleneckCSP', 'Proto', 'RepC3') class DFL(nn.Module): """ Integral module of Distribution Focal Loss (DFL). Proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391 """ def __init__(self, c1=16): """Initialize a convolutional layer with a given number of input channels.""" super().__init__() self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False) x = torch.arange(c1, dtype=torch.float) self.conv.weight.data[:] = nn.Parameter(x.view(1, c1, 1, 1)) self.c1 = c1 def forward(self, x): """Applies a transformer layer on input tensor 'x' and returns a tensor.""" b, c, a = x.shape # batch, channels, anchors return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a) # return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a) class Proto(nn.Module): """YOLOv8 mask Proto module for segmentation models.""" def __init__(self, c1, c_=256, c2=32): """ Initializes the YOLOv8 mask Proto module with specified number of protos and masks. Input arguments are ch_in, number of protos, number of masks. """ super().__init__()
self.cv1 = Conv(c1, c_, k=3)
0
2023-11-16 12:49:59+00:00
4k
i-super/Saleor
saleor/graphql/translations/mutations/category_translate.py
[ { "identifier": "SitePermissions", "path": "saleor/permission/enums.py", "snippet": "class SitePermissions(BasePermissionEnum):\n MANAGE_SETTINGS = \"site.manage_settings\"\n MANAGE_TRANSLATIONS = \"site.manage_translations\"" }, { "identifier": "models", "path": "saleor/product/models...
import graphene from ....permission.enums import SitePermissions from ....product import models as product_models from ...core.enums import LanguageCodeEnum from ...core.types import TranslationError from ...product.types import Category from .utils import BaseTranslateMutation, TranslationInput
3,228
class CategoryTranslate(BaseTranslateMutation): class Arguments: id = graphene.ID( required=True, description="Category ID or CategoryTranslatableContent ID.", ) language_code = graphene.Argument( LanguageCodeEnum, required=True, description="Translation language code." ) input = TranslationInput( required=True, description="Fields required to update category translations.", ) class Meta: description = "Creates/updates translations for a category."
class CategoryTranslate(BaseTranslateMutation): class Arguments: id = graphene.ID( required=True, description="Category ID or CategoryTranslatableContent ID.", ) language_code = graphene.Argument( LanguageCodeEnum, required=True, description="Translation language code." ) input = TranslationInput( required=True, description="Fields required to update category translations.", ) class Meta: description = "Creates/updates translations for a category."
model = product_models.Category
0
2023-11-13 05:00:35+00:00
4k
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,482
OCR_EQUAL = 0 OCR_CONTAINS = 1 OCR_SIMILAR = 2 class OcrResultButton:
OCR_EQUAL = 0 OCR_CONTAINS = 1 OCR_SIMILAR = 2 class OcrResultButton:
def __init__(self, boxed_result: BoxedResult, matched_keyword: Optional[Keyword]):
5
2023-11-12 09:33:35+00:00
4k
medkit-lib/medkit
medkit/io/medkit_json/text.py
[ { "identifier": "TextAnnotation", "path": "medkit/core/text/annotation.py", "snippet": "class TextAnnotation(abc.ABC, dict_conv.SubclassMapping):\n \"\"\"Base abstract class for all text annotations\n\n Attributes\n ----------\n uid:\n Unique identifier of the annotation.\n label:\...
import json import warnings from pathlib import Path from typing import Iterable, Iterator, Optional, Union from medkit.core.text import TextAnnotation, TextDocument from medkit.io.medkit_json._common import ContentType, build_header, check_header
2,939
__all__ = [ "load_text_document", "load_text_documents", "load_text_anns", "save_text_document", "save_text_documents", "save_text_anns", ] _DOC_ANNS_SUFFIX = "_anns.jsonl" def load_text_document( input_file: Union[str, Path], anns_input_file: Optional[Union[str, Path]] = None, encoding: Optional[str] = "utf-8", ) -> TextDocument: """ Load a text document from a medkit-json file generated with :func:`~medkit.io.medkit_json.save_text_document`. Parameters ---------- input_file: Path to the medkit-json file containing the document anns_input_file: Optional medkit-json file containing separate annotations of the document. encoding: Optional encoding of `input_file` and `anns_input_file` Returns ------- TextDocument The text document in the file """ input_file = Path(input_file) with open(input_file, encoding=encoding) as fp: data = json.load(fp) check_header(data, ContentType.TEXT_DOCUMENT) doc = TextDocument.from_dict(data["content"]) if anns_input_file is not None: for ann in load_text_anns(anns_input_file, encoding=encoding): doc.anns.add(ann) return doc def load_text_documents(input_file: Union[str, Path], encoding: Optional[str] = "utf-8") -> Iterator[TextDocument]: """ Returns an iterator on text documents loaded from a medkit-json file generated with :func:`~medkit.io.medkit_json.save_text_documents` Parameters ---------- input_file: Path to the medkit-json file containing the documents encoding: Optional encoding of `input_file` Returns ------- Iterator[TextDocument] An iterator to the text documents in the file """ input_file = Path(input_file) with open(input_file, encoding=encoding) as fp: line = fp.readline() data = json.loads(line) check_header(data, ContentType.TEXT_DOCUMENT_LIST) for line in fp: doc_data = json.loads(line) doc = TextDocument.from_dict(doc_data) yield doc
__all__ = [ "load_text_document", "load_text_documents", "load_text_anns", "save_text_document", "save_text_documents", "save_text_anns", ] _DOC_ANNS_SUFFIX = "_anns.jsonl" def load_text_document( input_file: Union[str, Path], anns_input_file: Optional[Union[str, Path]] = None, encoding: Optional[str] = "utf-8", ) -> TextDocument: """ Load a text document from a medkit-json file generated with :func:`~medkit.io.medkit_json.save_text_document`. Parameters ---------- input_file: Path to the medkit-json file containing the document anns_input_file: Optional medkit-json file containing separate annotations of the document. encoding: Optional encoding of `input_file` and `anns_input_file` Returns ------- TextDocument The text document in the file """ input_file = Path(input_file) with open(input_file, encoding=encoding) as fp: data = json.load(fp) check_header(data, ContentType.TEXT_DOCUMENT) doc = TextDocument.from_dict(data["content"]) if anns_input_file is not None: for ann in load_text_anns(anns_input_file, encoding=encoding): doc.anns.add(ann) return doc def load_text_documents(input_file: Union[str, Path], encoding: Optional[str] = "utf-8") -> Iterator[TextDocument]: """ Returns an iterator on text documents loaded from a medkit-json file generated with :func:`~medkit.io.medkit_json.save_text_documents` Parameters ---------- input_file: Path to the medkit-json file containing the documents encoding: Optional encoding of `input_file` Returns ------- Iterator[TextDocument] An iterator to the text documents in the file """ input_file = Path(input_file) with open(input_file, encoding=encoding) as fp: line = fp.readline() data = json.loads(line) check_header(data, ContentType.TEXT_DOCUMENT_LIST) for line in fp: doc_data = json.loads(line) doc = TextDocument.from_dict(doc_data) yield doc
def load_text_anns(input_file: Union[str, Path], encoding: Optional[str] = "utf-8") -> Iterator[TextAnnotation]:
0
2023-11-13 16:28:56+00:00
4k
donahowe/VE-MLD
src_files/models/tresnet/tresnet.py
[ { "identifier": "AntiAliasDownsampleLayer", "path": "src_files/models/tresnet/layers/anti_aliasing.py", "snippet": "class AntiAliasDownsampleLayer(nn.Module):\n def __init__(self, filt_size: int = 3, stride: int = 2,\n channels: int = 0):\n super(AntiAliasDownsampleLayer, self)...
import torch import torch.nn as nn from torch.nn import Module as Module from collections import OrderedDict from .layers.anti_aliasing import AntiAliasDownsampleLayer from .layers.avg_pool import FastAvgPool2d from src_files.ml_decoder.ml_decoder import MLDecoder from .layers.general_layers import SEModule, SpaceToDepthModule from inplace_abn import InPlaceABN, ABN
2,789
activation_param=module.activation_param) for key in module.state_dict(): module_new.state_dict()[key].copy_(module.state_dict()[key]) module_new.training = module.training module_new.weight.data = module_new.weight.abs() + module_new.eps return module_new for name, child in reversed(module._modules.items()): new_child = InplacABN_to_ABN(child) if new_child != child: module._modules[name] = new_child return module def conv2d(ni, nf, stride): return nn.Sequential( nn.Conv2d(ni, nf, kernel_size=3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(nf), nn.ReLU(inplace=True) ) def conv2d_ABN(ni, nf, stride, activation="leaky_relu", kernel_size=3, activation_param=1e-2, groups=1): return nn.Sequential( nn.Conv2d(ni, nf, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, groups=groups, bias=False), InPlaceABN(num_features=nf, activation=activation, activation_param=activation_param) ) class BasicBlock(Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None): super(BasicBlock, self).__init__() if stride == 1: self.conv1 = conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3) else: if anti_alias_layer is None: self.conv1 = conv2d_ABN(inplanes, planes, stride=2, activation_param=1e-3) else: self.conv1 = nn.Sequential(conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3), anti_alias_layer(channels=planes, filt_size=3, stride=2)) self.conv2 = conv2d_ABN(planes, planes, stride=1, activation="identity") self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride reduce_layer_planes = max(planes * self.expansion // 4, 64) self.se = SEModule(planes * self.expansion, reduce_layer_planes) if use_se else None def forward(self, x): if self.downsample is not None: residual = self.downsample(x) else: residual = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out += residual out = self.relu(out) return out class Bottleneck(Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None): super(Bottleneck, self).__init__() self.conv1 = conv2d_ABN(inplanes, planes, kernel_size=1, stride=1, activation="leaky_relu", activation_param=1e-3) if stride == 1: self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=1, activation="leaky_relu", activation_param=1e-3) else: if anti_alias_layer is None: self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=2, activation="leaky_relu", activation_param=1e-3) else: self.conv2 = nn.Sequential(conv2d_ABN(planes, planes, kernel_size=3, stride=1, activation="leaky_relu", activation_param=1e-3), anti_alias_layer(channels=planes, filt_size=3, stride=2)) self.conv3 = conv2d_ABN(planes, planes * self.expansion, kernel_size=1, stride=1, activation="identity") self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride reduce_layer_planes = max(planes * self.expansion // 8, 64) self.se = SEModule(planes, reduce_layer_planes) if use_se else None def forward(self, x): if self.downsample is not None: residual = self.downsample(x) else: residual = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.conv3(out) out = out + residual # no inplace out = self.relu(out) return out class TResNet(Module): def __init__(self, layers, in_chans=3, num_classes=1000, width_factor=1.0, first_two_layers=BasicBlock): super(TResNet, self).__init__() # JIT layers space_to_depth = SpaceToDepthModule()
def InplacABN_to_ABN(module: nn.Module) -> nn.Module: # convert all InplaceABN layer to bit-accurate ABN layers. if isinstance(module, InPlaceABN): module_new = ABN(module.num_features, activation=module.activation, activation_param=module.activation_param) for key in module.state_dict(): module_new.state_dict()[key].copy_(module.state_dict()[key]) module_new.training = module.training module_new.weight.data = module_new.weight.abs() + module_new.eps return module_new for name, child in reversed(module._modules.items()): new_child = InplacABN_to_ABN(child) if new_child != child: module._modules[name] = new_child return module def conv2d(ni, nf, stride): return nn.Sequential( nn.Conv2d(ni, nf, kernel_size=3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(nf), nn.ReLU(inplace=True) ) def conv2d_ABN(ni, nf, stride, activation="leaky_relu", kernel_size=3, activation_param=1e-2, groups=1): return nn.Sequential( nn.Conv2d(ni, nf, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, groups=groups, bias=False), InPlaceABN(num_features=nf, activation=activation, activation_param=activation_param) ) class BasicBlock(Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None): super(BasicBlock, self).__init__() if stride == 1: self.conv1 = conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3) else: if anti_alias_layer is None: self.conv1 = conv2d_ABN(inplanes, planes, stride=2, activation_param=1e-3) else: self.conv1 = nn.Sequential(conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3), anti_alias_layer(channels=planes, filt_size=3, stride=2)) self.conv2 = conv2d_ABN(planes, planes, stride=1, activation="identity") self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride reduce_layer_planes = max(planes * self.expansion // 4, 64) self.se = SEModule(planes * self.expansion, reduce_layer_planes) if use_se else None def forward(self, x): if self.downsample is not None: residual = self.downsample(x) else: residual = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out += residual out = self.relu(out) return out class Bottleneck(Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None): super(Bottleneck, self).__init__() self.conv1 = conv2d_ABN(inplanes, planes, kernel_size=1, stride=1, activation="leaky_relu", activation_param=1e-3) if stride == 1: self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=1, activation="leaky_relu", activation_param=1e-3) else: if anti_alias_layer is None: self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=2, activation="leaky_relu", activation_param=1e-3) else: self.conv2 = nn.Sequential(conv2d_ABN(planes, planes, kernel_size=3, stride=1, activation="leaky_relu", activation_param=1e-3), anti_alias_layer(channels=planes, filt_size=3, stride=2)) self.conv3 = conv2d_ABN(planes, planes * self.expansion, kernel_size=1, stride=1, activation="identity") self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride reduce_layer_planes = max(planes * self.expansion // 8, 64) self.se = SEModule(planes, reduce_layer_planes) if use_se else None def forward(self, x): if self.downsample is not None: residual = self.downsample(x) else: residual = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.conv3(out) out = out + residual # no inplace out = self.relu(out) return out class TResNet(Module): def __init__(self, layers, in_chans=3, num_classes=1000, width_factor=1.0, first_two_layers=BasicBlock): super(TResNet, self).__init__() # JIT layers space_to_depth = SpaceToDepthModule()
anti_alias_layer = AntiAliasDownsampleLayer
0
2023-11-13 04:12:26+00:00
4k
interpretml/LLM-Tabular-Memorization-Checker
tabmemcheck/chat_completion.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 numpy as np import pandas as pd import tabmemcheck.utils as utils from tabmemcheck.llm import LLM_Interface, send_chat_completion, send_completion
2,051
# this is implemented by replacing few_shot and fs_cond_feature_names with the appropriate lists if isinstance(few_shot, int): few_shot = [csv_file for _ in range(few_shot)] fs_cond_feature_names = [cond_feature_names for _ in range(len(few_shot))] # issue a warning if conditional_sampling, but no fs_cond_feature_names if conditional_sampling and len(few_shot) > 0 and len(fs_cond_feature_names) == 0: print( llm.bcolors.WARNING + "WARNING: feature_chat_completion: Conditional sampling, but no conditional feature names for the few-shot examples provided." + llm.bcolors.ENDC ) # prefixes and suffixes for the main dataset if conditional_sampling: prefixes, samples = utils.load_cond_samples( csv_file, cond_feature_names, add_description=add_description ) else: prefix, samples = utils.load_samples(csv_file) prefixes = [prefix] * len(samples) # prefixes and suffixes for the few-shot examples few_shot_prefixes_suffixes = [] for fs_idx, fs_csv_file in enumerate(few_shot): if conditional_sampling: fs_prefixes, fs_samples = utils.load_cond_samples( fs_csv_file, fs_cond_feature_names[fs_idx], add_description=add_description, ) few_shot_prefixes_suffixes.append((fs_prefixes, fs_samples)) else: fs_prefix, fs_samples = utils.load_samples(fs_csv_file) few_shot_prefixes_suffixes.append( ([fs_prefix] * len(fs_samples), fs_samples) ) # execute chat queries test_prefixes, test_suffixes, responses = prefix_suffix_chat_completion( llm, prefixes, samples, system_prompt, few_shot=few_shot_prefixes_suffixes, num_queries=num_queries, out_file=out_file, ) return test_prefixes, test_suffixes, responses #################################################################################### # The row chat completion task. This task ask the LLM to predict the next row in the # csv file, given the previous rows. This task is the basis for the row completion # test, and also for the first token test. #################################################################################### def row_chat_completion( llm, csv_file, system_prompt, num_prefix_rows=10, num_queries=100, few_shot=7, out_file=None, ): """Row chat completion task. This task ask the LLM to predict the next row in the csv file, given the previous rows. This task is the basis for the row completion test, and also for the first token test. Uses prefix_suffix_chat_completion.""" # assert that few_shot is an integer assert isinstance(few_shot, int), "For row completion, few_shot must be an integer." # load the file as a list of strings rows = utils.load_csv_rows(csv_file) # prepare data prefixes = [] suffixes = [] for idx in range(len(rows) - num_prefix_rows): prefixes.append("\n".join(rows[idx : idx + num_prefix_rows])) suffixes.append(rows[idx + num_prefix_rows]) test_prefixes, test_suffixes, responses = prefix_suffix_chat_completion( llm, prefixes, suffixes, system_prompt, few_shot=few_shot, num_queries=num_queries, out_file=out_file, ) return test_prefixes, test_suffixes, responses def row_completion( llm, csv_file, num_prefix_rows=10, num_queries=100, out_file=None, # TODO support out_file ): """Plain language model variant of row_chat_completion""" # load the file as a list of strings rows = utils.load_csv_rows(csv_file) # choose num_queries rows to complete prefixes = [] suffixes = [] responses = [] for idx in np.random.choice( len(rows) - num_prefix_rows, num_queries, replace=False ): # prepare query prefix = "\n".join(rows[idx : idx + num_prefix_rows]) suffix = rows[idx + num_prefix_rows] # send query
#################################################################################### # This file contains different chat completion functions. # # The functions in this file generate, format and send prompts, based on # the provided csv files. They return the raw model responses, and do not # perform any tests or analysis. Different tests make use # of the same chat completion functions. # # In the end, almost everything is based on prefix_suffix_chat_completion. #################################################################################### #################################################################################### # Feature values chat completion function. This function is used for sampling, # conditional sampling, and prediction. #################################################################################### def feature_values_chat_completion( llm: LLM_Interface, csv_file: str, system_prompt, num_queries, few_shot=[], # list or integer cond_feature_names=[], fs_cond_feature_names=[], # a list of lists of conditional feature names for each few-shot example add_description=True, out_file=None, ): """Feature chat completion task. This task asks the LLM to complete the feature values of observations in the dataset. The prompt format is the following: System: <system_prompt> | | {few_shot} examples from other csv files. | User: Dataset: <dataset_name> Feature Names: Feature 1, Feature 2, ..., Feature n Feature Values: Feature 1 = value 1, Feature 2 = value 2, ..., Feature m = value m [Target: Feature k] Response: Feature m + 1 = value m + 1, ..., Feature n = value n [Feature k = value k] This can be modified in the following ways: - Remove dataset description and feature names ({add_description} parameter) - don't provide any conditional features - Don't use the feature names, but only the values. (TODO ? or maybe remove, latter for formatter class) Options: - few_shot: use few-shot examples from other csv files (list), or few_shot examples from the same csv file (int) - target & fs_targets: if target is not None, then the LLM is asked to complete only the value of the target feature. The feature names are ordered in the prompt as they are ordered in the csv file. In the future we might want to relax this. TODO test and debug this function """ # TODO assert that all the given feature names are valid (i.e. occur in the dataset, otherwise throw exception) dataset_name = utils.get_dataset_name(csv_file) conditional_sampling = ( cond_feature_names is not None and len(cond_feature_names) > 0 ) # if the few-shot argument is a list, then csv_file should not be in there # the current option is to remove it (TODO issue warning) if isinstance(few_shot, list): few_shot = [ x for x in few_shot if not dataset_name in utils.get_dataset_name(x) ] # if few-shot is an integer, then include few_shot examples from csv_file # this is implemented by replacing few_shot and fs_cond_feature_names with the appropriate lists if isinstance(few_shot, int): few_shot = [csv_file for _ in range(few_shot)] fs_cond_feature_names = [cond_feature_names for _ in range(len(few_shot))] # issue a warning if conditional_sampling, but no fs_cond_feature_names if conditional_sampling and len(few_shot) > 0 and len(fs_cond_feature_names) == 0: print( llm.bcolors.WARNING + "WARNING: feature_chat_completion: Conditional sampling, but no conditional feature names for the few-shot examples provided." + llm.bcolors.ENDC ) # prefixes and suffixes for the main dataset if conditional_sampling: prefixes, samples = utils.load_cond_samples( csv_file, cond_feature_names, add_description=add_description ) else: prefix, samples = utils.load_samples(csv_file) prefixes = [prefix] * len(samples) # prefixes and suffixes for the few-shot examples few_shot_prefixes_suffixes = [] for fs_idx, fs_csv_file in enumerate(few_shot): if conditional_sampling: fs_prefixes, fs_samples = utils.load_cond_samples( fs_csv_file, fs_cond_feature_names[fs_idx], add_description=add_description, ) few_shot_prefixes_suffixes.append((fs_prefixes, fs_samples)) else: fs_prefix, fs_samples = utils.load_samples(fs_csv_file) few_shot_prefixes_suffixes.append( ([fs_prefix] * len(fs_samples), fs_samples) ) # execute chat queries test_prefixes, test_suffixes, responses = prefix_suffix_chat_completion( llm, prefixes, samples, system_prompt, few_shot=few_shot_prefixes_suffixes, num_queries=num_queries, out_file=out_file, ) return test_prefixes, test_suffixes, responses #################################################################################### # The row chat completion task. This task ask the LLM to predict the next row in the # csv file, given the previous rows. This task is the basis for the row completion # test, and also for the first token test. #################################################################################### def row_chat_completion( llm, csv_file, system_prompt, num_prefix_rows=10, num_queries=100, few_shot=7, out_file=None, ): """Row chat completion task. This task ask the LLM to predict the next row in the csv file, given the previous rows. This task is the basis for the row completion test, and also for the first token test. Uses prefix_suffix_chat_completion.""" # assert that few_shot is an integer assert isinstance(few_shot, int), "For row completion, few_shot must be an integer." # load the file as a list of strings rows = utils.load_csv_rows(csv_file) # prepare data prefixes = [] suffixes = [] for idx in range(len(rows) - num_prefix_rows): prefixes.append("\n".join(rows[idx : idx + num_prefix_rows])) suffixes.append(rows[idx + num_prefix_rows]) test_prefixes, test_suffixes, responses = prefix_suffix_chat_completion( llm, prefixes, suffixes, system_prompt, few_shot=few_shot, num_queries=num_queries, out_file=out_file, ) return test_prefixes, test_suffixes, responses def row_completion( llm, csv_file, num_prefix_rows=10, num_queries=100, out_file=None, # TODO support out_file ): """Plain language model variant of row_chat_completion""" # load the file as a list of strings rows = utils.load_csv_rows(csv_file) # choose num_queries rows to complete prefixes = [] suffixes = [] responses = [] for idx in np.random.choice( len(rows) - num_prefix_rows, num_queries, replace=False ): # prepare query prefix = "\n".join(rows[idx : idx + num_prefix_rows]) suffix = rows[idx + num_prefix_rows] # send query
response = send_completion(llm, prefix, max_tokens=1 + len(suffix))
2
2023-11-14 18:34:51+00:00
4k
WindowsSov8forUs/bestdori_api
bestdori/songmeta.py
[ { "identifier": "API", "path": "bestdori/utils/utils.py", "snippet": "API = {\n 'user': {\n 'info': 'user',\n 'login': 'user/login',\n 'me': 'user/me'\n },\n 'post': {\n 'basic': 'post/basic',\n 'details': 'post/details',\n 'list': 'post/list',\n ...
from typing import Optional, Literal, Any from .utils.utils import API from .utils.network import Api
1,744
'''`bestdori.songmeta` BanG Dream! 歌曲 Meta 相关操作''' # 获取总歌曲 Meta 信息 def get_all(index: Literal[5]=5, proxy: Optional[str]=None) -> dict[str, dict[str, Any]]: '''获取总歌曲 Meta 信息 参数: index (Literal[5], optional): 指定获取哪种 `all.json` `5`: 获取所有已有歌曲 Meta 信息 `all.5.json` proxy (Optional[str], optional): 代理服务器 返回: dict[str, dict[str, Any]]: 获取到的总歌曲 Meta 信息 '''
'''`bestdori.songmeta` BanG Dream! 歌曲 Meta 相关操作''' # 获取总歌曲 Meta 信息 def get_all(index: Literal[5]=5, proxy: Optional[str]=None) -> dict[str, dict[str, Any]]: '''获取总歌曲 Meta 信息 参数: index (Literal[5], optional): 指定获取哪种 `all.json` `5`: 获取所有已有歌曲 Meta 信息 `all.5.json` proxy (Optional[str], optional): 代理服务器 返回: dict[str, dict[str, Any]]: 获取到的总歌曲 Meta 信息 '''
return Api(API['all']['meta'].format(index=index), proxy=proxy).request('get').json()
0
2023-11-16 13:09:20+00:00
4k
jidiai/Competition_OvercookedAI-2
run_log.py
[ { "identifier": "make", "path": "env/chooseenv.py", "snippet": "def make(env_type, seed=None, conf=None):\n file_path = os.path.join(os.path.dirname(__file__), 'config.json')\n if not conf:\n with open(file_path) as f:\n conf = json.load(f)[env_type]\n class_literal = conf['cl...
import os import time import json import numpy as np import argparse import sys from env.chooseenv import make from utils.get_logger import get_logger from env.obs_interfaces.observation import obs_type
2,072
action_space_list = [g.get_single_action_space(player_id) for player_id in players_id_list] actions_space.append(action_space_list) return players_id, actions_space def get_joint_action_eval(game, multi_part_agent_ids, policy_list, actions_spaces, all_observes): if len(policy_list) != len(game.agent_nums): error = "模型个数%d与玩家个数%d维度不正确!" % (len(policy_list), len(game.agent_nums)) raise Exception(error) # [[[0, 0, 0, 1]], [[0, 1, 0, 0]]] joint_action = [] for policy_i in range(len(policy_list)): if game.obs_type[policy_i] not in obs_type: raise Exception("可选obs类型:%s" % str(obs_type)) agents_id_list = multi_part_agent_ids[policy_i] action_space_list = actions_spaces[policy_i] function_name = 'm%d' % policy_i for i in range(len(agents_id_list)): agent_id = agents_id_list[i] a_obs = all_observes[agent_id] each = eval(function_name)(a_obs, action_space_list[i], game.is_act_continuous) joint_action.append(each) # print(joint_action) return joint_action def set_seed(g, env_name): if env_name.split("-")[0] in ['magent']: g.reset() seed = g.create_seed() g.set_seed(seed) def run_game(g, env_name, multi_part_agent_ids, actions_spaces, policy_list, render_mode): """ This function is used to generate log for Vue rendering. Saves .json file """ log_path = os.getcwd() + '/logs/' if not os.path.exists(log_path): os.mkdir(log_path) logger = get_logger(log_path, g.game_name, json_file=render_mode) set_seed(g, env_name) for i in range(len(policy_list)): if policy_list[i] not in get_valid_agents(): raise Exception("agent {} not valid!".format(policy_list[i])) file_path = os.path.dirname(os.path.abspath(__file__)) + "/agents/" + policy_list[i] + "/submission.py" if not os.path.exists(file_path): raise Exception("file {} not exist!".format(file_path)) import_path = '.'.join(file_path.split('/')[-3:])[:-3] function_name = 'm%d' % i import_name = "my_controller" import_s = "from %s import %s as %s" % (import_path, import_name, function_name) print(import_s) exec(import_s, globals()) st = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) game_info = {"game_name": env_name, "n_player": g.n_player, "board_height": g.board_height if hasattr(g, "board_height") else None, "board_width": g.board_width if hasattr(g, "board_width") else None, "init_info": g.init_info, "start_time": st, "mode": "terminal", "seed": g.seed if hasattr(g, "seed") else None, "map_size": g.map_size if hasattr(g, "map_size") else None} steps = [] all_observes = g.all_observes while not g.is_terminal(): step = "step%d" % g.step_cnt if g.step_cnt % 10 == 0: print(step) if render_mode and hasattr(g, "env_core"): if hasattr(g.env_core, "render"): g.env_core.render() elif render_mode and hasattr(g, 'render'): g.render() info_dict = {"time": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))} joint_act = get_joint_action_eval(g, multi_part_agent_ids, policy_list, actions_spaces, all_observes) all_observes, reward, done, info_before, info_after = g.step(joint_act) if env_name.split("-")[0] in ["magent"]: info_dict["joint_action"] = g.decode(joint_act) if info_before: info_dict["info_before"] = info_before info_dict["reward"] = reward if info_after: info_dict["info_after"] = info_after steps.append(info_dict) game_info["steps"] = steps game_info["winner"] = g.check_win() game_info["winner_information"] = g.won game_info["n_return"] = g.n_return ed = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) game_info["end_time"] = ed logs = json.dumps(game_info, ensure_ascii=False, cls=NpEncoder) logger.info(logs) def get_valid_agents(): dir_path = os.path.join(os.path.dirname(__file__), 'agents') return [f for f in os.listdir(dir_path) if f != "__pycache__"] if __name__ == "__main__": env_type = "overcookedai-integrated"
# -*- coding:utf-8 -*- sys.path.append("./olympics_engine") class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() else: return super(NpEncoder, self).default(obj) def get_players_and_action_space_list(g): if sum(g.agent_nums) != g.n_player: raise Exception("agent number = %d 不正确,与n_player = %d 不匹配" % (sum(g.agent_nums), g.n_player)) n_agent_num = list(g.agent_nums) for i in range(1, len(n_agent_num)): n_agent_num[i] += n_agent_num[i - 1] # 根据agent number 分配 player id players_id = [] actions_space = [] for policy_i in range(len(g.obs_type)): if policy_i == 0: players_id_list = range(n_agent_num[policy_i]) else: players_id_list = range(n_agent_num[policy_i - 1], n_agent_num[policy_i]) players_id.append(players_id_list) action_space_list = [g.get_single_action_space(player_id) for player_id in players_id_list] actions_space.append(action_space_list) return players_id, actions_space def get_joint_action_eval(game, multi_part_agent_ids, policy_list, actions_spaces, all_observes): if len(policy_list) != len(game.agent_nums): error = "模型个数%d与玩家个数%d维度不正确!" % (len(policy_list), len(game.agent_nums)) raise Exception(error) # [[[0, 0, 0, 1]], [[0, 1, 0, 0]]] joint_action = [] for policy_i in range(len(policy_list)): if game.obs_type[policy_i] not in obs_type: raise Exception("可选obs类型:%s" % str(obs_type)) agents_id_list = multi_part_agent_ids[policy_i] action_space_list = actions_spaces[policy_i] function_name = 'm%d' % policy_i for i in range(len(agents_id_list)): agent_id = agents_id_list[i] a_obs = all_observes[agent_id] each = eval(function_name)(a_obs, action_space_list[i], game.is_act_continuous) joint_action.append(each) # print(joint_action) return joint_action def set_seed(g, env_name): if env_name.split("-")[0] in ['magent']: g.reset() seed = g.create_seed() g.set_seed(seed) def run_game(g, env_name, multi_part_agent_ids, actions_spaces, policy_list, render_mode): """ This function is used to generate log for Vue rendering. Saves .json file """ log_path = os.getcwd() + '/logs/' if not os.path.exists(log_path): os.mkdir(log_path) logger = get_logger(log_path, g.game_name, json_file=render_mode) set_seed(g, env_name) for i in range(len(policy_list)): if policy_list[i] not in get_valid_agents(): raise Exception("agent {} not valid!".format(policy_list[i])) file_path = os.path.dirname(os.path.abspath(__file__)) + "/agents/" + policy_list[i] + "/submission.py" if not os.path.exists(file_path): raise Exception("file {} not exist!".format(file_path)) import_path = '.'.join(file_path.split('/')[-3:])[:-3] function_name = 'm%d' % i import_name = "my_controller" import_s = "from %s import %s as %s" % (import_path, import_name, function_name) print(import_s) exec(import_s, globals()) st = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) game_info = {"game_name": env_name, "n_player": g.n_player, "board_height": g.board_height if hasattr(g, "board_height") else None, "board_width": g.board_width if hasattr(g, "board_width") else None, "init_info": g.init_info, "start_time": st, "mode": "terminal", "seed": g.seed if hasattr(g, "seed") else None, "map_size": g.map_size if hasattr(g, "map_size") else None} steps = [] all_observes = g.all_observes while not g.is_terminal(): step = "step%d" % g.step_cnt if g.step_cnt % 10 == 0: print(step) if render_mode and hasattr(g, "env_core"): if hasattr(g.env_core, "render"): g.env_core.render() elif render_mode and hasattr(g, 'render'): g.render() info_dict = {"time": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))} joint_act = get_joint_action_eval(g, multi_part_agent_ids, policy_list, actions_spaces, all_observes) all_observes, reward, done, info_before, info_after = g.step(joint_act) if env_name.split("-")[0] in ["magent"]: info_dict["joint_action"] = g.decode(joint_act) if info_before: info_dict["info_before"] = info_before info_dict["reward"] = reward if info_after: info_dict["info_after"] = info_after steps.append(info_dict) game_info["steps"] = steps game_info["winner"] = g.check_win() game_info["winner_information"] = g.won game_info["n_return"] = g.n_return ed = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) game_info["end_time"] = ed logs = json.dumps(game_info, ensure_ascii=False, cls=NpEncoder) logger.info(logs) def get_valid_agents(): dir_path = os.path.join(os.path.dirname(__file__), 'agents') return [f for f in os.listdir(dir_path) if f != "__pycache__"] if __name__ == "__main__": env_type = "overcookedai-integrated"
game = make(env_type, seed=None)
0
2023-11-15 09:09:01+00:00
4k
kampta/asic
datasets/spair.py
[ { "identifier": "load_nbb", "path": "datasets/utils.py", "snippet": "def load_nbb(nbb_dir, img_paths, parts=None):\n img_paths = [Path(f) for f in img_paths]\n num_images = len(img_paths)\n\n matches = [[[] for _ in range(num_images)] for _ in range(num_images)]\n max_kps = 0\n for i in r...
import os import torch import numpy as np import json from torch.utils.data import Dataset from PIL import Image from glob import glob from torchvision import transforms from pathlib import Path from datasets.utils import load_nbb, preprocess_kps_pad, SquarePad from torchvision.datasets.utils import download_and_extract_archive from torchvision.utils import save_image from datasets.utils import Augmentor from commons.draw import splat_points
2,892
else: source_idx = files.index(source_fn) if target_fn not in files: files.append(target_fn) kps.append(torch.zeros(num_kps, 3)) thresholds.append(0) target_idx = len(files) - 1 else: target_idx = files.index(target_fn) kp_ixs = [int(id) for id in data["kps_ids"]] kp_ixs = torch.tensor(kp_ixs).view(-1, 1).repeat(1, 3) source_raw_kps = torch.cat([torch.tensor(data["src_kps"], dtype=torch.float), torch.ones(kp_ixs.size(0), 1)], 1) source_kps = blank_kps.scatter(dim=0, index=kp_ixs, src=source_raw_kps) source_kps, *_, scale_src = preprocess_kps_pad(source_kps, source_size[0], source_size[1], size) kps[source_idx] = source_kps target_raw_kps = torch.cat([torch.tensor(data["trg_kps"], dtype=torch.float), torch.ones(kp_ixs.size(0), 1)], 1) target_kps = blank_kps.scatter(dim=0, index=kp_ixs, src=target_raw_kps) target_kps, *_, scale_trg = preprocess_kps_pad(target_kps, target_size[0], target_size[1], size) kps[target_idx] = target_kps fixed_pairs.append([source_idx, target_idx]) threshold_src = max(source_bbox[3] - source_bbox[1], source_bbox[2] - source_bbox[0]) threshold_trg = max(target_bbox[3] - target_bbox[1], target_bbox[2] - target_bbox[0]) thresholds[source_idx] = threshold_src*scale_src thresholds[target_idx] = threshold_trg*scale_trg kps = torch.stack(kps) used_kps, = torch.where(kps[:, :, 2].any(dim=0)) kps = kps[:, used_kps, :] print(f'Final number of used key points: {kps.size(1)}') return files, kps, fixed_pairs, thresholds def download_spair(to_path): # Downloads and extracts the SPair-71K dataset spair_dir = f'{to_path}/SPair-71k' if not os.path.isdir(spair_dir): print(f'Downloading SPair-71k to {to_path}') spair_url = 'http://cvlab.postech.ac.kr/research/SPair-71k/data/SPair-71k.tar.gz' download_and_extract_archive(spair_url, to_path, remove_finished=True) else: print('Found pre-existing SPair-71K directory') return spair_dir class SpairDataset(Dataset): def __init__(self, data_dir, split='test', img_size=256, spair_cat='cat', flow_dir=None, padding_mode='edge', num_parts=0, mask_threshold=1, use_coseg_masks=False): super().__init__() self.img_size = img_size self.split = split self.cat = spair_cat self.padding_mode = padding_mode self.flow_dir = flow_dir self.num_parts = num_parts self.mask_threshold = mask_threshold normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) transform = transforms.Compose([ SquarePad(padding_mode), transforms.Resize(img_size), transforms.ToTensor(), normalize, ]) os.makedirs(data_dir, exist_ok=True) spair_dir = download_spair(data_dir) self.files, self.kps, fixed_pairs, thresholds = load_spair_data( spair_dir, size=img_size, split=split, category=spair_cat) imgs = [transform(Image.open(self.files[i]).convert('RGB')) for i in range(len(self))] self.imgs = torch.stack(imgs) self.fixed_pairs = np.array(fixed_pairs) self.thresholds = np.array(thresholds) self.masks = torch.ones(len(self), 1, img_size, img_size) self.pseudo_kps = None self.parts = None # Load masks if flow_dir is not None: if use_coseg_masks: mask_dir = Path(flow_dir) / 'masks_coseg' else: mask_dir = Path(flow_dir) / 'masks' assert mask_dir.exists(), f"{mask_dir} doesn't exist" masks = [] for i in range(0, len(self)): fname = mask_dir / f'{Path(self.files[i]).stem}.png' mask = np.array(Image.open(fname).convert('L')) masks.append(mask) self.masks = torch.from_numpy(np.stack(masks) >= mask_threshold).float() # Load parts if flow_dir is not None: parts_str = 'parts' if num_parts <=0 else f'parts_num{num_parts}' parts_dir = Path(flow_dir) / f'{parts_str}' if parts_dir.exists(): parts = [] for i in range(0, len(self)): fname = parts_dir / f'parts_s2_{Path(self.files[i]).stem}.npy' part = np.load(fname) parts.append(part) parts = np.stack(parts) num_parts = int(np.max(parts[~np.isnan(parts)])) + 1 parts[np.isnan(parts)] = num_parts self.parts = torch.from_numpy(parts.astype(np.int64)) else: print(f"{parts_dir} doesn't exist. Parts won't load.") self.num_parts = num_parts # self.parts = F.one_hot(parts, num_classes=num_parts+1).bool() # Load pseudo keypoints if flow_dir is not None: nbb_dir = Path(flow_dir) / 'nbb' if nbb_dir.exists():
def load_spair_data(path, size=256, category='cat', split='test', subsample=-1, seed=42): pairs = sorted(glob(f'{path}/PairAnnotation/{split}/*{category}.json')) assert len(pairs) > 0, '# of groundtruth image pairs must be > 0' if subsample > 0: np.random.seed(seed) pairs = [pairs[ix] for ix in np.random.choice(len(pairs), subsample)] print(f'Number of SPairs for {category} = {len(pairs)}') category_anno = list(glob(f'{path}/ImageAnnotation/{category}/*.json'))[0] with open(category_anno) as f: num_kps = len(json.load(f)['kps']) print(f'Number of SPair key points for {category} <= {num_kps}') files = [] kps = [] thresholds = [] blank_kps = torch.zeros(num_kps, 3) fixed_pairs = [] for pair in pairs: with open(pair) as f: data = json.load(f) assert category == data["category"] assert data["mirror"] == 0 source_fn = f'{path}/JPEGImages/{category}/{data["src_imname"]}' target_fn = f'{path}/JPEGImages/{category}/{data["trg_imname"]}' source_bbox = np.asarray(data["src_bndbox"]) target_bbox = np.asarray(data["trg_bndbox"]) source_size = data["src_imsize"][:2] # (W, H) target_size = data["trg_imsize"][:2] # (W, H) if source_fn not in files: files.append(source_fn) kps.append(torch.zeros(num_kps, 3)) thresholds.append(0) source_idx = len(files) - 1 else: source_idx = files.index(source_fn) if target_fn not in files: files.append(target_fn) kps.append(torch.zeros(num_kps, 3)) thresholds.append(0) target_idx = len(files) - 1 else: target_idx = files.index(target_fn) kp_ixs = [int(id) for id in data["kps_ids"]] kp_ixs = torch.tensor(kp_ixs).view(-1, 1).repeat(1, 3) source_raw_kps = torch.cat([torch.tensor(data["src_kps"], dtype=torch.float), torch.ones(kp_ixs.size(0), 1)], 1) source_kps = blank_kps.scatter(dim=0, index=kp_ixs, src=source_raw_kps) source_kps, *_, scale_src = preprocess_kps_pad(source_kps, source_size[0], source_size[1], size) kps[source_idx] = source_kps target_raw_kps = torch.cat([torch.tensor(data["trg_kps"], dtype=torch.float), torch.ones(kp_ixs.size(0), 1)], 1) target_kps = blank_kps.scatter(dim=0, index=kp_ixs, src=target_raw_kps) target_kps, *_, scale_trg = preprocess_kps_pad(target_kps, target_size[0], target_size[1], size) kps[target_idx] = target_kps fixed_pairs.append([source_idx, target_idx]) threshold_src = max(source_bbox[3] - source_bbox[1], source_bbox[2] - source_bbox[0]) threshold_trg = max(target_bbox[3] - target_bbox[1], target_bbox[2] - target_bbox[0]) thresholds[source_idx] = threshold_src*scale_src thresholds[target_idx] = threshold_trg*scale_trg kps = torch.stack(kps) used_kps, = torch.where(kps[:, :, 2].any(dim=0)) kps = kps[:, used_kps, :] print(f'Final number of used key points: {kps.size(1)}') return files, kps, fixed_pairs, thresholds def download_spair(to_path): # Downloads and extracts the SPair-71K dataset spair_dir = f'{to_path}/SPair-71k' if not os.path.isdir(spair_dir): print(f'Downloading SPair-71k to {to_path}') spair_url = 'http://cvlab.postech.ac.kr/research/SPair-71k/data/SPair-71k.tar.gz' download_and_extract_archive(spair_url, to_path, remove_finished=True) else: print('Found pre-existing SPair-71K directory') return spair_dir class SpairDataset(Dataset): def __init__(self, data_dir, split='test', img_size=256, spair_cat='cat', flow_dir=None, padding_mode='edge', num_parts=0, mask_threshold=1, use_coseg_masks=False): super().__init__() self.img_size = img_size self.split = split self.cat = spair_cat self.padding_mode = padding_mode self.flow_dir = flow_dir self.num_parts = num_parts self.mask_threshold = mask_threshold normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) transform = transforms.Compose([ SquarePad(padding_mode), transforms.Resize(img_size), transforms.ToTensor(), normalize, ]) os.makedirs(data_dir, exist_ok=True) spair_dir = download_spair(data_dir) self.files, self.kps, fixed_pairs, thresholds = load_spair_data( spair_dir, size=img_size, split=split, category=spair_cat) imgs = [transform(Image.open(self.files[i]).convert('RGB')) for i in range(len(self))] self.imgs = torch.stack(imgs) self.fixed_pairs = np.array(fixed_pairs) self.thresholds = np.array(thresholds) self.masks = torch.ones(len(self), 1, img_size, img_size) self.pseudo_kps = None self.parts = None # Load masks if flow_dir is not None: if use_coseg_masks: mask_dir = Path(flow_dir) / 'masks_coseg' else: mask_dir = Path(flow_dir) / 'masks' assert mask_dir.exists(), f"{mask_dir} doesn't exist" masks = [] for i in range(0, len(self)): fname = mask_dir / f'{Path(self.files[i]).stem}.png' mask = np.array(Image.open(fname).convert('L')) masks.append(mask) self.masks = torch.from_numpy(np.stack(masks) >= mask_threshold).float() # Load parts if flow_dir is not None: parts_str = 'parts' if num_parts <=0 else f'parts_num{num_parts}' parts_dir = Path(flow_dir) / f'{parts_str}' if parts_dir.exists(): parts = [] for i in range(0, len(self)): fname = parts_dir / f'parts_s2_{Path(self.files[i]).stem}.npy' part = np.load(fname) parts.append(part) parts = np.stack(parts) num_parts = int(np.max(parts[~np.isnan(parts)])) + 1 parts[np.isnan(parts)] = num_parts self.parts = torch.from_numpy(parts.astype(np.int64)) else: print(f"{parts_dir} doesn't exist. Parts won't load.") self.num_parts = num_parts # self.parts = F.one_hot(parts, num_classes=num_parts+1).bool() # Load pseudo keypoints if flow_dir is not None: nbb_dir = Path(flow_dir) / 'nbb' if nbb_dir.exists():
self.pseudo_kps = load_nbb(nbb_dir, self.files, self.parts)
0
2023-11-14 16:43:16+00:00
4k
DavinciEvans/minutes-GPT
MinutesGPT.py
[ { "identifier": "WhisperASR", "path": "ASR/WhisperASR.py", "snippet": "class WhisperASR:\n def __init__(\n self,\n device=None, \n max_new_tokens=128, \n language=\"english\", \n task=\"transcribe\", \n chunk_length_s=30, \n ...
from ASR import WhisperASR from GPT import ChatGPT from Role import MeetingSecretary, SummaryWriter, MeetingMinutesEditor from config import Config import argparse import os
1,638
MEETING_SECRETARY_PROMPT_FILE = "MeetingSecretaryPrompt.md" config = Config() client = ChatGPT(api_key=config.api_key) class NoAudioError: pass parser = argparse.ArgumentParser() parser.add_argument("--audio", help="The meeting record path. (Recommended .wav and .mp3)") parser.add_argument("--output_file", help="The output file path. default output.md") parser.add_argument("--language", help="The language of the record, default english.") parser.add_argument("--device", help="The automatic speed recognition model running on.") parser.add_argument("--batch_size", help="The batch size of asr model. default 16.") parser.add_argument("--clip_length", help="Length of each cut clip. default 6000.") parser.add_argument("--clip_abandoned", help="The length of the shortest clip, below which it will be discarded. default 1000.") parser.add_argument("--word_level_timestamps", help="Output word level timestamps. default false.") parser.add_argument("--no_cache", help="Results that are already cached without using ASR are also not generated. default false.") parser.add_argument("--minutes_template", help="Minutes template file path.") args = parser.parse_args() if args.audio is None: raise(NoAudioError("You must provide an audio file.")) audio = args.audio language = args.language output_file = args.output_file if args.output_file else "output.md" batch_size = int(args.batch_size) if args.batch_size else None device = args.device clip_length = int(args.clip_length) if args.clip_length else 6000 clip_abandoned = int(args.clip_abandoned) if args.clip_abandoned else 1000 word_level_timestamps = bool(args.word_level_timestamps) no_cache = bool(args.no_cache) minutes_template = args.minutes_template def write_output(text): print("Start to write the meeting minutes.")
MEETING_SECRETARY_PROMPT_FILE = "MeetingSecretaryPrompt.md" config = Config() client = ChatGPT(api_key=config.api_key) class NoAudioError: pass parser = argparse.ArgumentParser() parser.add_argument("--audio", help="The meeting record path. (Recommended .wav and .mp3)") parser.add_argument("--output_file", help="The output file path. default output.md") parser.add_argument("--language", help="The language of the record, default english.") parser.add_argument("--device", help="The automatic speed recognition model running on.") parser.add_argument("--batch_size", help="The batch size of asr model. default 16.") parser.add_argument("--clip_length", help="Length of each cut clip. default 6000.") parser.add_argument("--clip_abandoned", help="The length of the shortest clip, below which it will be discarded. default 1000.") parser.add_argument("--word_level_timestamps", help="Output word level timestamps. default false.") parser.add_argument("--no_cache", help="Results that are already cached without using ASR are also not generated. default false.") parser.add_argument("--minutes_template", help="Minutes template file path.") args = parser.parse_args() if args.audio is None: raise(NoAudioError("You must provide an audio file.")) audio = args.audio language = args.language output_file = args.output_file if args.output_file else "output.md" batch_size = int(args.batch_size) if args.batch_size else None device = args.device clip_length = int(args.clip_length) if args.clip_length else 6000 clip_abandoned = int(args.clip_abandoned) if args.clip_abandoned else 1000 word_level_timestamps = bool(args.word_level_timestamps) no_cache = bool(args.no_cache) minutes_template = args.minutes_template def write_output(text): print("Start to write the meeting minutes.")
meeting_secretary = MeetingSecretary(client, minutes_template)
2
2023-11-18 03:45:00+00:00
4k
AnonymGiant/ViLaM
train.py
[ { "identifier": "Config", "path": "lavis/common/config.py", "snippet": "class Config:\n def __init__(self, args):\n self.config = {}\n\n self.args = args\n\n # Register the config and configuration for setup\n registry.register(\"configuration\", self)\n\n user_conf...
import argparse import os import random import numpy as np import torch import torch.backends.cudnn as cudnn import lavis.tasks as tasks from lavis.common.config import Config from lavis.common.dist_utils import get_rank, init_distributed_mode from lavis.common.logger import setup_logger from lavis.common.optims import ( LinearWarmupCosineLRScheduler, LinearWarmupStepLRScheduler, ) from lavis.common.registry import registry from lavis.common.utils import now from lavis.datasets.builders import * from lavis.models import * from lavis.processors import * from lavis.runners import * from lavis.tasks import *
3,039
""" 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 """ # imports modules for registration def parse_args(): parser = argparse.ArgumentParser(description="Training") parser.add_argument("--cfg-path", default='', help="path to configuration file.") parser.add_argument( "--options", nargs="+", help="override some settings in the used config, the key-value pair " "in xxx=yyy format will be merged into config file (deprecate), " "change to --cfg-options instead.", ) args = parser.parse_args() # if 'LOCAL_RANK' not in os.environ: # os.environ['LOCAL_RANK'] = str(args.local_rank) return args def setup_seeds(config): seed = config.run_cfg.seed + get_rank() random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) cudnn.benchmark = False cudnn.deterministic = True def get_runner_class(cfg): """ Get runner class from config. Default to epoch-based runner. """ runner_cls = registry.get_runner_class(cfg.run_cfg.get("runner", "runner_base")) return runner_cls def main(): # allow auto-dl completes on main process without timeout when using NCCL backend. # os.environ["NCCL_BLOCKING_WAIT"] = "1" # set before init_distributed_mode() to ensure the same job_id shared across all ranks. job_id = now() cfg = Config(parse_args()) init_distributed_mode(cfg.run_cfg) setup_seeds(cfg) # set after init_distributed_mode() to only log on master.
""" 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 """ # imports modules for registration def parse_args(): parser = argparse.ArgumentParser(description="Training") parser.add_argument("--cfg-path", default='', help="path to configuration file.") parser.add_argument( "--options", nargs="+", help="override some settings in the used config, the key-value pair " "in xxx=yyy format will be merged into config file (deprecate), " "change to --cfg-options instead.", ) args = parser.parse_args() # if 'LOCAL_RANK' not in os.environ: # os.environ['LOCAL_RANK'] = str(args.local_rank) return args def setup_seeds(config): seed = config.run_cfg.seed + get_rank() random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) cudnn.benchmark = False cudnn.deterministic = True def get_runner_class(cfg): """ Get runner class from config. Default to epoch-based runner. """ runner_cls = registry.get_runner_class(cfg.run_cfg.get("runner", "runner_base")) return runner_cls def main(): # allow auto-dl completes on main process without timeout when using NCCL backend. # os.environ["NCCL_BLOCKING_WAIT"] = "1" # set before init_distributed_mode() to ensure the same job_id shared across all ranks. job_id = now() cfg = Config(parse_args()) init_distributed_mode(cfg.run_cfg) setup_seeds(cfg) # set after init_distributed_mode() to only log on master.
setup_logger()
3
2023-11-14 08:57:59+00:00
4k
MorrisNein/pecapiku
pecapiku/cache_dict.py
[ { "identifier": "BaseCache", "path": "pecapiku/base_cache.py", "snippet": "class omnimethod(Generic[DecoratedCallable]):\nclass BaseCache(ABC):\n def __init__(self, func: DecoratedCallable):\n def __get__(self, instance, owner) -> DecoratedCallable:\n def __init__(self, file_path: os.PathLike |...
import logging import os from collections import defaultdict from functools import partial, wraps from inspect import getcallargs, ismethod, signature from typing import Any, Callable, Generic, Hashable from pecapiku.base_cache import BaseCache, DecoratedCallable, Decorator, omnimethod from pecapiku.cache_access import COMP_CACHE_FILE_NAME, CacheAccess, _initialize_cache, _resolve_filepath, update_cache from pecapiku.hash import get_hash from pecapiku.no_cache import NoCache
1,696
""" def get(self, __key): return self.__getitem__(__key) def __repr__(self): return dict.__repr__(self) def initialize_cache_dict(file_path: os.PathLike) -> MyDefaultDict: cache_dict = _initialize_cache(file_path) if isinstance(cache_dict, NoCache): logger.info('Creating a new cache dict...') cache_dict = MyDefaultDict(NoCache) elif not isinstance(cache_dict, MyDefaultDict): raise ValueError(f'File "{file_path}" contains value of type "{type(cache_dict)}", not MyDefaultDict.' ' Rename or delete it beforehand.') return cache_dict def parse_key(callable_or_code: Callable[[Any], Hashable] | str, func: Callable, *args, **kwargs) -> Hashable: if callable(callable_or_code): sign_params = signature(callable_or_code).parameters elif isinstance(callable_or_code, str): sign_params = callable_or_code else: raise ValueError(f'Inner key should be either string or callable, got {type(callable_or_code)}.') if 'args' in sign_params or 'kwargs' in sign_params: input_kwargs = dict(args=args, kwargs=kwargs) else: input_kwargs = getcallargs(func, *args, **kwargs) if callable(callable_or_code): key = callable_or_code(**input_kwargs) else: key = eval(callable_or_code, None, input_kwargs) return key class CacheDict(BaseCache, Generic[DecoratedCallable]): """ Decorator/context manager for caching of evaluation results. Creates a "pickle" file at disk space on a specified path. If used as a context, provides a dictionary to put/read values in. To do so, use the syntax "with *instance*: ...". If used as a decorator, wraps a function and stores its execution results in s dictionary. To do so, use the method ``CacheDict.decorate()``. Args: file_path - a path to an existing or non-existent pickle file. If a relative path or a filename is given, puts it into the framework cache directory. access - cache access indicators. The string may include the following indicators: - ``r`` - read - grants access to read the cache file content - ``e`` - execute/evaluate - grants access to evaluate the decorated function (if such is present) - ``w`` - write - grants access to modify the cache file content Examples -------- Example 1: >>> with CacheDict('example_cache_dict.pkl') as cache_dict: ... x = np.array([[1, 2], [3, 4]]) ... x_T = cache_dict['x_T'] # Read the cache first ... if isinstance(x_T, NoCache): # If cache not found, ... x_T = x.T # then execute the value ... cache_dict['x_T'] = x_T # Put the value in cache ... print(cache_dict) ... {'x_T': array([[1, 3], [2, 4]])} Example 2: >>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6], [7, 8]]) >>> cached_mult = CacheDict.decorate(np.multiply,file_path='np_multiplication.pkl') # Retrieve hashable representation of args. ... >>> cached_mult(a, b) array([[ 5, 12], [21, 32]]) """ @classmethod def _get_default_file_path(cls): return COMP_CACHE_FILE_NAME def __init__(self, file_path: os.PathLike | str | None = None, access: CacheAccess = 'rew'): super().__init__(file_path, access) self.cache_dict = None def __call__(self, func: DecoratedCallable | None = None, outer_key: Hashable | None = None, inner_key: str | Callable[[Any], Hashable] | None = None) -> DecoratedCallable | Decorator: return self.decorate(func=func, outer_key=outer_key, inner_key=inner_key) def _get_cache_val(self, key: Hashable) -> Any: initialize_cache_dict(self.file_path) return self.cache_dict[key] def _put_cache_val(self, key: Hashable, value: Any) -> None: self.cache_dict[key] = value def _key_func(self, func, func_agrs, func_kwargs, inner_key, outer_key) -> Hashable: if outer_key is not None: key = outer_key elif inner_key is not None: key = parse_key(inner_key, func, *func_agrs, **func_kwargs) else: hash_objects = [func.__name__, func_agrs, func_kwargs] if ismethod(func): hash_objects.insert(0, func.__self__)
from __future__ import annotations logger = logging.getLogger(__file__) class MyDefaultDict(defaultdict): """ A more consistent type of ``defaultdict`` that returns default value on ``get()``, unlike native ``defaultdict``. """ def get(self, __key): return self.__getitem__(__key) def __repr__(self): return dict.__repr__(self) def initialize_cache_dict(file_path: os.PathLike) -> MyDefaultDict: cache_dict = _initialize_cache(file_path) if isinstance(cache_dict, NoCache): logger.info('Creating a new cache dict...') cache_dict = MyDefaultDict(NoCache) elif not isinstance(cache_dict, MyDefaultDict): raise ValueError(f'File "{file_path}" contains value of type "{type(cache_dict)}", not MyDefaultDict.' ' Rename or delete it beforehand.') return cache_dict def parse_key(callable_or_code: Callable[[Any], Hashable] | str, func: Callable, *args, **kwargs) -> Hashable: if callable(callable_or_code): sign_params = signature(callable_or_code).parameters elif isinstance(callable_or_code, str): sign_params = callable_or_code else: raise ValueError(f'Inner key should be either string or callable, got {type(callable_or_code)}.') if 'args' in sign_params or 'kwargs' in sign_params: input_kwargs = dict(args=args, kwargs=kwargs) else: input_kwargs = getcallargs(func, *args, **kwargs) if callable(callable_or_code): key = callable_or_code(**input_kwargs) else: key = eval(callable_or_code, None, input_kwargs) return key class CacheDict(BaseCache, Generic[DecoratedCallable]): """ Decorator/context manager for caching of evaluation results. Creates a "pickle" file at disk space on a specified path. If used as a context, provides a dictionary to put/read values in. To do so, use the syntax "with *instance*: ...". If used as a decorator, wraps a function and stores its execution results in s dictionary. To do so, use the method ``CacheDict.decorate()``. Args: file_path - a path to an existing or non-existent pickle file. If a relative path or a filename is given, puts it into the framework cache directory. access - cache access indicators. The string may include the following indicators: - ``r`` - read - grants access to read the cache file content - ``e`` - execute/evaluate - grants access to evaluate the decorated function (if such is present) - ``w`` - write - grants access to modify the cache file content Examples -------- Example 1: >>> with CacheDict('example_cache_dict.pkl') as cache_dict: ... x = np.array([[1, 2], [3, 4]]) ... x_T = cache_dict['x_T'] # Read the cache first ... if isinstance(x_T, NoCache): # If cache not found, ... x_T = x.T # then execute the value ... cache_dict['x_T'] = x_T # Put the value in cache ... print(cache_dict) ... {'x_T': array([[1, 3], [2, 4]])} Example 2: >>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6], [7, 8]]) >>> cached_mult = CacheDict.decorate(np.multiply,file_path='np_multiplication.pkl') # Retrieve hashable representation of args. ... >>> cached_mult(a, b) array([[ 5, 12], [21, 32]]) """ @classmethod def _get_default_file_path(cls): return COMP_CACHE_FILE_NAME def __init__(self, file_path: os.PathLike | str | None = None, access: CacheAccess = 'rew'): super().__init__(file_path, access) self.cache_dict = None def __call__(self, func: DecoratedCallable | None = None, outer_key: Hashable | None = None, inner_key: str | Callable[[Any], Hashable] | None = None) -> DecoratedCallable | Decorator: return self.decorate(func=func, outer_key=outer_key, inner_key=inner_key) def _get_cache_val(self, key: Hashable) -> Any: initialize_cache_dict(self.file_path) return self.cache_dict[key] def _put_cache_val(self, key: Hashable, value: Any) -> None: self.cache_dict[key] = value def _key_func(self, func, func_agrs, func_kwargs, inner_key, outer_key) -> Hashable: if outer_key is not None: key = outer_key elif inner_key is not None: key = parse_key(inner_key, func, *func_agrs, **func_kwargs) else: hash_objects = [func.__name__, func_agrs, func_kwargs] if ismethod(func): hash_objects.insert(0, func.__self__)
key = get_hash(hash_objects)
2
2023-11-17 12:10:01+00:00
4k
mmjing/BalancedOSDA
demo.py
[ { "identifier": "get_mini_batches", "path": "data.py", "snippet": "def get_mini_batches(X, Y, mini_batch_size):\n shuffles = shuffle(X, Y)\n num_examples = shuffles[\"X_shuffle\"].shape[0]\n num_complete = num_examples // mini_batch_size\n mini_batches = []\n for i in range(num_complete)...
import argparse import torch.nn.functional as F import torchvision.transforms as transforms import numpy as np import os import time import gc import torch import torch.optim as optim import torch.nn as nn import random import sys import mymodels from pickle import dump, load from torch.optim.lr_scheduler import StepLR from utils import * from utils2 import * from data import get_mini_batches from FeatureLoader import myPairedData from basenet import *
1,714
from __future__ import print_function def GetNowTime(): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) def getTimestamp(): return time.strftime("%m%d%H%M%S", time.localtime(time.time())) parser = argparse.ArgumentParser(description='PyTorch Openset DA') parser.add_argument('--dataset', type=str, default='image-clef') parser.add_argument('--source', type=str, default='c') parser.add_argument('--target', type=str, default='b') parser.add_argument('--batch_size', type=int, default=256) parser.add_argument('--test_batch_size', type=int, default=8) parser.add_argument('--log_inter', type=int, default=10) parser.add_argument('--mintail', type=int, default=2) parser.add_argument('--decay', type=float, default=0.8) parser.add_argument('--end_iter', type=int, default=8000) parser.add_argument('--tailsize', type=float, default=0.02) parser.add_argument('--margin', type=float, default=2.5) parser.add_argument('--loss_ca', type=float, default=1.0) parser.add_argument('--loss_cnp', type=float, default=1.0) parser.add_argument('--h_dim', type=int, default=256) parser.add_argument('--z_dim', type=int, default=128) parser.add_argument('--lr_enc', type=float, default=4e-4) parser.add_argument('--lr_dec', type=float, default=4e-4) parser.add_argument('--lr_cls', type=float, default=1e-3) args = parser.parse_args() args.cuda = True print(GetNowTime()) print('Begin run!!!') since = time.time() root = './features/' source_train_feat = np.load(root+args.source+'_source_train_feature.npy').astype('float32') source_train_label = np.load(root+args.source+'_source_train_label.npy').astype('int') target_train_feat = np.load(root+args.target+'_target_train_feature.npy').astype('float32') target_train_label = np.load(root+args.target+'_target_train_label.npy').astype('int') source_test_feat = np.load(root+args.source+'_source_test_feature.npy').astype('float32') source_test_label = np.load(root+args.source+'_source_test_label.npy').astype('int') target_test_feat = np.load(root+args.target+'_target_test_feature.npy').astype('float32') target_test_label = np.load(root+args.target+'_target_test_label.npy').astype('int') train_loader = myPairedData(source_train_feat,source_train_label,target_train_feat,target_train_label,args.batch_size) batch_size = args.batch_size
from __future__ import print_function def GetNowTime(): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) def getTimestamp(): return time.strftime("%m%d%H%M%S", time.localtime(time.time())) parser = argparse.ArgumentParser(description='PyTorch Openset DA') parser.add_argument('--dataset', type=str, default='image-clef') parser.add_argument('--source', type=str, default='c') parser.add_argument('--target', type=str, default='b') parser.add_argument('--batch_size', type=int, default=256) parser.add_argument('--test_batch_size', type=int, default=8) parser.add_argument('--log_inter', type=int, default=10) parser.add_argument('--mintail', type=int, default=2) parser.add_argument('--decay', type=float, default=0.8) parser.add_argument('--end_iter', type=int, default=8000) parser.add_argument('--tailsize', type=float, default=0.02) parser.add_argument('--margin', type=float, default=2.5) parser.add_argument('--loss_ca', type=float, default=1.0) parser.add_argument('--loss_cnp', type=float, default=1.0) parser.add_argument('--h_dim', type=int, default=256) parser.add_argument('--z_dim', type=int, default=128) parser.add_argument('--lr_enc', type=float, default=4e-4) parser.add_argument('--lr_dec', type=float, default=4e-4) parser.add_argument('--lr_cls', type=float, default=1e-3) args = parser.parse_args() args.cuda = True print(GetNowTime()) print('Begin run!!!') since = time.time() root = './features/' source_train_feat = np.load(root+args.source+'_source_train_feature.npy').astype('float32') source_train_label = np.load(root+args.source+'_source_train_label.npy').astype('int') target_train_feat = np.load(root+args.target+'_target_train_feature.npy').astype('float32') target_train_label = np.load(root+args.target+'_target_train_label.npy').astype('int') source_test_feat = np.load(root+args.source+'_source_test_feature.npy').astype('float32') source_test_label = np.load(root+args.source+'_source_test_label.npy').astype('int') target_test_feat = np.load(root+args.target+'_target_test_feature.npy').astype('float32') target_test_label = np.load(root+args.target+'_target_test_label.npy').astype('int') train_loader = myPairedData(source_train_feat,source_train_label,target_train_feat,target_train_label,args.batch_size) batch_size = args.batch_size
data_test_target = get_mini_batches(target_test_feat, target_test_label, batch_size)
0
2023-11-13 09:00:25+00:00
4k
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
3,401
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),
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),
0
2023-11-12 22:52:06+00:00
4k
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
3,576
### # 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"],
### # 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,
3
2023-11-13 21:47:18+00:00
4k
isLinXu/onnx-explorer
estimate.py
[ { "identifier": "estimate_memory", "path": "onnx_explorer/utils/estimate_memory.py", "snippet": "class ModelEstimate:\n def __init__(self, model_file_path=None, model_type='onnx', manual_num_params=None, total_memory=4, total_memory_unit='GB'):\n def get_num_params_onnx(self):\n def get_num_par...
import argparse from onnx_explorer.utils import estimate_memory from onnx_explorer.utils.estimate_memory import ModelEstimate
2,051
if __name__ == '__main__': # 使用 argparse 解析命令行参数 parser = argparse.ArgumentParser(description="Analyze ONNX model.") parser.add_argument("-m", "--model-path", help="Path to the ONNX model file.") parser.add_argument("-t", "--model-type", default='onnx', help="Type of the model. Supported types are 'onnx' and 'pt'.") parser.add_argument("-n", "--num_memory", default=4, help="Total memory size.") parser.add_argument("-u", "--unit_memory", default='GB', help="Total memory unit.") parser.add_argument("-p", "--manual_params", default=500000000, type=int, help="Number of parameters in the model.") args = parser.parse_args() model_path = args.model_path model_type = args.model_type num_memory = args.num_memory unit_memory = args.unit_memory manual_params = args.manual_params if unit_memory not in ['B', 'KB', 'MB', 'GB']: raise ValueError("Invalid memory unit. Supported units are 'B', 'KB', 'MB', 'GB'.") if model_path is None: print("manual_params:", manual_params)
if __name__ == '__main__': # 使用 argparse 解析命令行参数 parser = argparse.ArgumentParser(description="Analyze ONNX model.") parser.add_argument("-m", "--model-path", help="Path to the ONNX model file.") parser.add_argument("-t", "--model-type", default='onnx', help="Type of the model. Supported types are 'onnx' and 'pt'.") parser.add_argument("-n", "--num_memory", default=4, help="Total memory size.") parser.add_argument("-u", "--unit_memory", default='GB', help="Total memory unit.") parser.add_argument("-p", "--manual_params", default=500000000, type=int, help="Number of parameters in the model.") args = parser.parse_args() model_path = args.model_path model_type = args.model_type num_memory = args.num_memory unit_memory = args.unit_memory manual_params = args.manual_params if unit_memory not in ['B', 'KB', 'MB', 'GB']: raise ValueError("Invalid memory unit. Supported units are 'B', 'KB', 'MB', 'GB'.") if model_path is None: print("manual_params:", manual_params)
model = ModelEstimate(total_memory=num_memory,
1
2023-11-15 03:34:22+00:00
4k
doodledood/chat-flock
chatflock/participants/langchain.py
[ { "identifier": "execute_chat_model_messages", "path": "chatflock/ai_utils.py", "snippet": "def execute_chat_model_messages(\n chat_model: BaseChatModel,\n messages: Sequence[BaseMessage],\n chat_model_args: Optional[Dict[str, Any]] = None,\n tools: Optional[Sequence[BaseTool]] = None,\n ...
from typing import Any, Dict, List, Optional, Sequence from datetime import datetime from halo import Halo from langchain.chat_models.base import BaseChatModel from langchain.schema import AIMessage, BaseMessage, BaseRetriever, Document, HumanMessage, SystemMessage from langchain.tools import BaseTool from chatflock.ai_utils import execute_chat_model_messages from chatflock.base import ActiveChatParticipant, Chat, ChatMessage from chatflock.structured_string import Section, StructuredString
3,188
class LangChainBasedAIChatParticipant(ActiveChatParticipant): class Config: arbitrary_types_allowed = True def __init__( self, name: str, chat_model: BaseChatModel, symbol: str = "🤖", role: str = "AI Assistant", personal_mission: str = "Be a helpful AI assistant.", other_prompt_sections: Optional[List[Section]] = None, retriever: Optional[BaseRetriever] = None, tools: Optional[List[BaseTool]] = None, chat_model_args: Optional[Dict[str, Any]] = None, spinner: Optional[Halo] = None, ignore_group_chat_environment: bool = False, include_timestamp_in_messages: bool = False, **kwargs: Any, ): super().__init__(name=name, symbol=symbol, **kwargs) self.role = role self.chat_model = chat_model self.chat_model_args = chat_model_args or {} self.other_prompt_sections = other_prompt_sections or [] self.ignore_group_chat_environment = ignore_group_chat_environment self.include_timestamp_in_messages = include_timestamp_in_messages self.retriever = retriever self.tools = tools self.spinner = spinner self.personal_mission = personal_mission def create_system_message(self, chat: "Chat", relevant_docs: Sequence[Document]) -> str: now = datetime.now() pretty_datetime = now.strftime("%m-%d-%Y %H:%M:%S") base_sections = [ Section(name="Current Time", text=pretty_datetime), Section(name="Name", text=self.name), Section(name="Role", text=self.role), Section(name="Personal Mission", text=self.personal_mission), Section( name="Additional Context for Response", text="None" if len(relevant_docs) == 0 else "The following documents may be relevant for your response, only use " "them for context for a better response, if applicable", sub_sections=[ Section(name=f"Document {i + 1}", text=f"```{doc.page_content}```") for i, doc in enumerate(relevant_docs) ], ), Section( name="Response Message Format", list=[ "Your response should be the message you want to send to the group chat as your own name, " "role, and personal mission.", "Must not include any prefix (e.g., timestamp, sender name, etc.).", "Response must be a message as will be shown in the chat (timestamp and sender name are " "system-generated for you).", ], sub_sections=[ Section(name="Well-Formatted Chat Response Examples", list=['"Hello, how are you?"']), Section( name="Badly-Formatted Chat Response Examples", list=[ ( '"[TIMESTAMP] John: Hello, how are you?"' if self.include_timestamp_in_messages else '"John: Hello, how are you?"' ), ], ), ], ), ] active_participants = chat.get_active_participants() if self.ignore_group_chat_environment:
class LangChainBasedAIChatParticipant(ActiveChatParticipant): class Config: arbitrary_types_allowed = True def __init__( self, name: str, chat_model: BaseChatModel, symbol: str = "🤖", role: str = "AI Assistant", personal_mission: str = "Be a helpful AI assistant.", other_prompt_sections: Optional[List[Section]] = None, retriever: Optional[BaseRetriever] = None, tools: Optional[List[BaseTool]] = None, chat_model_args: Optional[Dict[str, Any]] = None, spinner: Optional[Halo] = None, ignore_group_chat_environment: bool = False, include_timestamp_in_messages: bool = False, **kwargs: Any, ): super().__init__(name=name, symbol=symbol, **kwargs) self.role = role self.chat_model = chat_model self.chat_model_args = chat_model_args or {} self.other_prompt_sections = other_prompt_sections or [] self.ignore_group_chat_environment = ignore_group_chat_environment self.include_timestamp_in_messages = include_timestamp_in_messages self.retriever = retriever self.tools = tools self.spinner = spinner self.personal_mission = personal_mission def create_system_message(self, chat: "Chat", relevant_docs: Sequence[Document]) -> str: now = datetime.now() pretty_datetime = now.strftime("%m-%d-%Y %H:%M:%S") base_sections = [ Section(name="Current Time", text=pretty_datetime), Section(name="Name", text=self.name), Section(name="Role", text=self.role), Section(name="Personal Mission", text=self.personal_mission), Section( name="Additional Context for Response", text="None" if len(relevant_docs) == 0 else "The following documents may be relevant for your response, only use " "them for context for a better response, if applicable", sub_sections=[ Section(name=f"Document {i + 1}", text=f"```{doc.page_content}```") for i, doc in enumerate(relevant_docs) ], ), Section( name="Response Message Format", list=[ "Your response should be the message you want to send to the group chat as your own name, " "role, and personal mission.", "Must not include any prefix (e.g., timestamp, sender name, etc.).", "Response must be a message as will be shown in the chat (timestamp and sender name are " "system-generated for you).", ], sub_sections=[ Section(name="Well-Formatted Chat Response Examples", list=['"Hello, how are you?"']), Section( name="Badly-Formatted Chat Response Examples", list=[ ( '"[TIMESTAMP] John: Hello, how are you?"' if self.include_timestamp_in_messages else '"John: Hello, how are you?"' ), ], ), ], ), ] active_participants = chat.get_active_participants() if self.ignore_group_chat_environment:
system_message = StructuredString(sections=[*base_sections, *self.other_prompt_sections])
5
2023-11-12 11:10:58+00:00
4k
phidatahq/junior-de
app/pages/1_PyGPT.py
[ { "identifier": "get_openai_key", "path": "app/openai_key.py", "snippet": "def get_openai_key() -> Optional[str]:\n \"\"\"Sidebar component to get OpenAI API key\"\"\"\n\n # Get OpenAI API key from environment variable\n openai_key: Optional[str] = getenv(\"OPENAI_API_KEY\")\n # If not found...
from typing import List from phi.conversation import Conversation from app.openai_key import get_openai_key from app.password import check_password from app.reload import reload_button from app.user_name import get_user_name from llm.conversations.pygpt import get_pygpt_conversation from utils.log import logger import streamlit as st
2,188
st.title(":snowman: PyGPT") st.markdown('<a href="https://github.com/phidatahq/phidata"><h4>by phidata</h4></a>', unsafe_allow_html=True) def restart_conversation(): st.session_state["py_conversation"] = None st.session_state["py_conversation_id"] = None st.rerun() def main() -> None: # Get users OpenAI API key get_openai_key() # Get user name
st.title(":snowman: PyGPT") st.markdown('<a href="https://github.com/phidatahq/phidata"><h4>by phidata</h4></a>', unsafe_allow_html=True) def restart_conversation(): st.session_state["py_conversation"] = None st.session_state["py_conversation_id"] = None st.rerun() def main() -> None: # Get users OpenAI API key get_openai_key() # Get user name
user_name = get_user_name()
3
2023-11-14 10:44:20+00:00
4k
KaiTownsend/focusmode
main.py
[ { "identifier": "PomodoroTimer", "path": "pomodoro.py", "snippet": "class PomodoroTimer:\n # A Pomodoro timer that uses a separate thread to count down time.\n\n def __init__(self, transition_callback=None):\n # Initialize the timer with default work time and no active thread.\n\n se...
from pomodoro import PomodoroTimer from sound_manager import SoundManager import threading import tkinter import tkinter.messagebox import customtkinter import json import os import sys import time
1,657
# Copyright 2023 Kai Townsend # 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. class FocusModeApp: def __init__(self): # Initialize the PomodoroTimer self.timer = PomodoroTimer(transition_callback=self.on_timer_transition) # Initialize the SoundManager
# Copyright 2023 Kai Townsend # 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. class FocusModeApp: def __init__(self): # Initialize the PomodoroTimer self.timer = PomodoroTimer(transition_callback=self.on_timer_transition) # Initialize the SoundManager
self.sound_manager = SoundManager()
1
2023-11-12 20:56:06+00:00
4k
gunyu1019/async-client-decorator
async_client_decorator/request.py
[ { "identifier": "wraps", "path": "async_client_decorator/_functools.py", "snippet": "def wraps(wrapped, assigned=_WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES):\n return partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)" }, { "identifier": "wrap_annotations", "p...
import copy import inspect import aiohttp from asyncio import iscoroutinefunction from typing import TypeVar, Optional, Any from ._functools import wraps, wrap_annotations from ._types import RequestFunction from .body import Body from .component import Component from .form import Form from .header import Header from .path import Path from .query import Query from .session import Session
3,018
"""MIT License Copyright (c) 2023 gunyu1019 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ T = TypeVar("T") def _get_kwarg_for_request( component: Component, path: str, request_kwargs: dict[str, Any], kwargs: dict[str, Any], ) -> tuple[str, dict[str, Any]]: # Header if "headers" not in request_kwargs.keys(): request_kwargs["headers"] = {} request_kwargs["headers"].update( component.fill_keyword_argument_to_component("header", kwargs) ) # Parameter if "params" not in request_kwargs.keys(): request_kwargs["params"] = {} request_kwargs["params"].update( component.fill_keyword_argument_to_component("query", kwargs) ) # Body if component.is_body(): if component.is_formal_form(): component.fill_keyword_argument_to_component("form", kwargs) body_type = component.body_type request_kwargs[body_type] = component.get_body() # Path path_data = component.fill_keyword_argument_to_component("path", kwargs) formatted_path = path.format(**path_data) return formatted_path, request_kwargs def _request( request_cls, path: str, directly_response: bool = False, header_parameter: list[str] = None, query_parameter: list[str] = None, form_parameter: list[str] = None, path_parameter: list[str] = None, body_parameter: Optional[str] = None, response_parameter: list[str] = None, **request_kwargs ): header_parameter = header_parameter or list() query_parameter = query_parameter or list() form_parameter = form_parameter or list() path_parameter = path_parameter or list() response_parameter = response_parameter or list() def decorator(func: RequestFunction): # method is related to Requestable class. signature = inspect.signature(func) func_parameters = signature.parameters if len(func_parameters) < 1: raise TypeError( "%s missing 1 required parameter: 'self(extends Session)'".format( func.__name__ ) ) if not iscoroutinefunction(func): raise TypeError("function %s must be coroutine.".format(func.__name__)) components = Component() components.header.update(getattr(func, Header.DEFAULT_KEY, dict())) components.query.update(getattr(func, Query.DEFAULT_KEY, dict()))
"""MIT License Copyright (c) 2023 gunyu1019 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ T = TypeVar("T") def _get_kwarg_for_request( component: Component, path: str, request_kwargs: dict[str, Any], kwargs: dict[str, Any], ) -> tuple[str, dict[str, Any]]: # Header if "headers" not in request_kwargs.keys(): request_kwargs["headers"] = {} request_kwargs["headers"].update( component.fill_keyword_argument_to_component("header", kwargs) ) # Parameter if "params" not in request_kwargs.keys(): request_kwargs["params"] = {} request_kwargs["params"].update( component.fill_keyword_argument_to_component("query", kwargs) ) # Body if component.is_body(): if component.is_formal_form(): component.fill_keyword_argument_to_component("form", kwargs) body_type = component.body_type request_kwargs[body_type] = component.get_body() # Path path_data = component.fill_keyword_argument_to_component("path", kwargs) formatted_path = path.format(**path_data) return formatted_path, request_kwargs def _request( request_cls, path: str, directly_response: bool = False, header_parameter: list[str] = None, query_parameter: list[str] = None, form_parameter: list[str] = None, path_parameter: list[str] = None, body_parameter: Optional[str] = None, response_parameter: list[str] = None, **request_kwargs ): header_parameter = header_parameter or list() query_parameter = query_parameter or list() form_parameter = form_parameter or list() path_parameter = path_parameter or list() response_parameter = response_parameter or list() def decorator(func: RequestFunction): # method is related to Requestable class. signature = inspect.signature(func) func_parameters = signature.parameters if len(func_parameters) < 1: raise TypeError( "%s missing 1 required parameter: 'self(extends Session)'".format( func.__name__ ) ) if not iscoroutinefunction(func): raise TypeError("function %s must be coroutine.".format(func.__name__)) components = Component() components.header.update(getattr(func, Header.DEFAULT_KEY, dict())) components.query.update(getattr(func, Query.DEFAULT_KEY, dict()))
components.form.update(getattr(func, Form.DEFAULT_KEY, dict()))
5
2023-11-14 06:41:19+00:00
4k
YusukeOhnishi/document_summarize
main.py
[ { "identifier": "Loader", "path": "src/load.py", "snippet": "class Loader:\n def load_pdf(file_path):\n reader = PdfReader(file_path)\n texts = \"\"\n for page in reader.pages:\n texts += page.extract_text()\n return texts\n\n def load_url(document_url):\n ...
from src.load import Loader from src.create_prompt import CreatePrompt from src.chat_model import ChatModel from src.utils import (clean_text, split_text) from data.model_info import ModelInfo from data.selection import GetList from component.main_page import (Setting,Content) from component.sidebar import Sidebar
1,696
Sidebar.show_init('# Cost') setting = Setting() setting.show_setting(GetList.get_model_list(), GetList.get_language_list()) model, language = setting.get_parameter() model_info = ModelInfo.get_model_info(model) max_word = int(model_info["max_token"]/3) chat_model = ChatModel(model_info["model_name"]) setting.show_upload_setting() content_source, content_type = setting.get_content() try: match content_type: case "pdf":
Sidebar.show_init('# Cost') setting = Setting() setting.show_setting(GetList.get_model_list(), GetList.get_language_list()) model, language = setting.get_parameter() model_info = ModelInfo.get_model_info(model) max_word = int(model_info["max_token"]/3) chat_model = ChatModel(model_info["model_name"]) setting.show_upload_setting() content_source, content_type = setting.get_content() try: match content_type: case "pdf":
text=Loader.load_pdf(content_source)
0
2023-11-18 10:29:25+00:00
4k
UWNetworksLab/adn-compiler
compiler/element/backend/envoy/wasmgen.py
[ { "identifier": "ELEMENT_LOG", "path": "compiler/element/logger.py", "snippet": "ELEMENT_LOG = logging.getLogger(\"ir\")" }, { "identifier": "Visitor", "path": "compiler/element/visitor.py", "snippet": "class Visitor(ABC):\n def visitNode(self, node: Node, ctx):\n raise Excepti...
from typing import Dict, List, Optional from compiler.element.backend.envoy import * from compiler.element.backend.envoy.wasmtype import * from compiler.element.logger import ELEMENT_LOG as LOG from compiler.element.node import * from compiler.element.visitor import Visitor
2,658
return f"Context.Explain:\n\t{self.internal_states}\n\t{self.name2var}\n\t{self.current_procedure}\n\t{self.params}\n\t{self.init_code}\n\t{self.req_code}\n\t{self.resp_code}" def gen_global_var_def(self) -> str: ret = "" for v in self.internal_states: if v.consistency == "strong": continue wrapped = WasmRwLock(v.type) ret = ( ret + f""" lazy_static! {{ static ref {v.name}: {str(wrapped)} = {wrapped.gen_init()}; }}\n """ ) return ret def gen_meta_get(self, field: str): assert field.startswith("meta") if field == "meta_status": if self.current_procedure == FUNC_REQ_BODY: # Meta status is only set in the response raise Exception("Should not read meta in request") if self.current_procedure == FUNC_RESP_BODY: self.resp_hdr_code.append( """ if let Some(status_code) = self.get_http_response_header(":status") { if status_code == "200" { self.meta_status = "success".to_string(); } else { self.meta_status = "failure".to_string(); } } else { panic!("No status code found in response headers"); } """ ) class WasmGenerator(Visitor): def __init__(self, placement: str) -> None: self.placement = placement if placement != "client" and placement != "server": raise Exception("placement should be sender or receiver") def visitNode(self, node: Node, ctx: WasmContext): return node.__class__.__name__ def visitProgram(self, node: Program, ctx: WasmContext) -> None: node.definition.accept(self, ctx) node.init.accept(self, ctx) for v in ctx.internal_states: if v.init == "" and v.consistency != "strong": v.init = v.type.gen_init() node.req.accept(self, ctx) node.resp.accept(self, ctx) def visitInternal(self, node: Internal, ctx: WasmContext) -> None: # Iterate through all internal state variables and declare them for (i, t, cons, comb, per) in node.internal: state_name = i.name state_wasm_type = t.accept(self, ctx) ctx.declare( state_name, state_wasm_type, False, True, cons.name, comb.name, per.name ) def visitProcedure(self, node: Procedure, ctx: WasmContext): # TODO: Add request and response header processing. match node.name: case "init": ctx.current_procedure = FUNC_INIT procedure_type = "init" # unused, make python happy case "req": ctx.current_procedure = FUNC_REQ_BODY procedure_type = "Request" case "resp": ctx.current_procedure = FUNC_RESP_BODY procedure_type = "Response" case _: raise Exception("unknown function") ctx.clear_temps() if node.name == "req": name = "request" elif node.name == "resp": name = "response" else: name = node.name if name != "init": ctx.declare(f"rpc_{name}", WasmRpcType(f"rpc_{name}", []), True, False) inners = ctx.gen_inners() ctx.push_code(inners) # Boilerplate code for decoding the RPC message prefix_decode_rpc = f""" if let Some(body) = self.get_http_{name}_body(0, body_size) {{ match {ctx.proto}::{ctx.method_name}{procedure_type}::decode(&body[5..]) {{ Ok(mut rpc_{name}) => {{ """ suffix_decode_rpc = f""" }} Err(e) => log::warn!("decode error: {{}}", e), }} }} """ # If the procedure does not access the RPC message, then we do not need to decode it if ctx.current_procedure != FUNC_INIT: if ctx.current_procedure == FUNC_REQ_BODY: if "rpc_req" in ctx.access_ops[ctx.current_procedure]: ctx.push_code(prefix_decode_rpc) elif ctx.current_procedure == FUNC_RESP_BODY: if "rpc_resp" in ctx.access_ops[ctx.current_procedure]: ctx.push_code(prefix_decode_rpc) for p in node.params: name = p.name if ctx.find_var(name) == None:
class WasmContext: def __init__(self, proto=None, method_name=None, element_name: str = "") -> None: self.internal_states: List[ WasmVariable ] = [] # List of internal state variables self.inners: List[ WasmVariable ] = [] # Inners are temp variables used to access state self.name2var: Dict[ str, WasmVariable ] = {} # Mapping from names to Wasm variables self.current_procedure: str = "unknown" # Name of the current procedure (i.e., init/req/resp) being processed self.params: List[WasmVariable] = [] # List of parameters for the function self.init_code: List[str] = [] # Code for initialization self.req_hdr_code: List[str] = [] # Code for request header processing self.resp_hdr_code: List[str] = [] # Code for response header processing self.req_body_code: List[str] = [] # Code for request body processing self.resp_body_code: List[str] = [] # Code for response body processing self.external_call_response_code: List[ str ] = [] # Code for handling external call responses (state sync) self.decode: bool = True # Flag to determine whether to decode the RPC self.proto: str = proto # Protobuf used self.method_name: str = method_name # Name of the RPC method self.element_name: str = element_name # Name of the generated element # Maps to store the state (incl. RPC) operations on request/response headers and bodies self.access_ops: Dict[str, Dict[str, MethodType]] = { FUNC_INIT: {}, FUNC_REQ_HEADER: {}, FUNC_REQ_BODY: {}, FUNC_RESP_HEADER: {}, FUNC_RESP_BODY: {}, } def declare( self, name: str, rtype: WasmType, temp_var: bool, atomic: bool, consistency: str = None, combiner: str = None, persistence: bool = False, ) -> None: # This method declares a new variable in the Wasm context and add it to the name2var mapping if name in self.name2var: # Check for duplicate variable names raise Exception(f"variable {name} already defined") else: # Create a new WasmVariable instance and add it to the name2var mapping var = WasmVariable( name, rtype, temp_var, name == "rpc_request" or name == "rpc_response", atomic, inner=False, consistency=consistency, combiner=combiner, persistence=persistence, ) if consistency == "strong": self.internal_states.append(var) self.name2var[name] = var elif not temp_var and not var.rpc and atomic: # If it's not a temp variable and does not belong to RPC request or response processing. var.init = rtype.gen_init() self.internal_states.append(var) # Create an inner variable for the declared variable v_inner = WasmVariable( name + "_inner", rtype, False, False, False, inner=True ) self.inners.append(v_inner) self.name2var[name] = v_inner elif name == "rpc_request": self.name2var["rpc_req"] = var elif name == "rpc_response": self.name2var["rpc_resp"] = var else: self.name2var[name] = var def gen_inners(self) -> str: ret = "" # Generate inners based on operations for v in self.internal_states: if v.consistency != "strong": if v.name in self.access_ops[self.current_procedure]: access_type = self.access_ops[self.current_procedure][v.name] if access_type == MethodType.GET: ret = ( ret + f"let mut {v.name}_inner = {v.name}.read().unwrap();\n" ) elif access_type == MethodType.SET: ret = ( ret + f"let mut {v.name}_inner = {v.name}.write().unwrap();\n" ) else: raise Exception("unknown method in gen_inners.") return ret def clear_temps(self) -> None: new_dic = {} for k, v in self.name2var.items(): if not v.temp: new_dic[k] = v self.name2var = new_dic def push_code(self, code: str) -> None: # This method appends the given code to the appropriate list based on the current function context if self.current_procedure == FUNC_INIT: self.init_code.append(code) elif self.current_procedure == FUNC_REQ_HEADER: self.req_hdr_code.append(code) elif self.current_procedure == FUNC_REQ_BODY: self.req_body_code.append(code) elif self.current_procedure == FUNC_RESP_HEADER: self.resp_hdr_code.append(code) elif self.current_procedure == FUNC_RESP_BODY: self.resp_body_code.append(code) elif self.current_procedure == FUNC_EXTERNAL_RESPONSE: self.external_call_response_code.append(code) else: raise Exception( "unknown function" ) # Raise an exception if the current function context is unknown def find_var(self, name: str) -> Optional[WasmVariable]: if name in self.name2var: return self.name2var[name] else: return None def explain(self) -> str: return f"Context.Explain:\n\t{self.internal_states}\n\t{self.name2var}\n\t{self.current_procedure}\n\t{self.params}\n\t{self.init_code}\n\t{self.req_code}\n\t{self.resp_code}" def gen_global_var_def(self) -> str: ret = "" for v in self.internal_states: if v.consistency == "strong": continue wrapped = WasmRwLock(v.type) ret = ( ret + f""" lazy_static! {{ static ref {v.name}: {str(wrapped)} = {wrapped.gen_init()}; }}\n """ ) return ret def gen_meta_get(self, field: str): assert field.startswith("meta") if field == "meta_status": if self.current_procedure == FUNC_REQ_BODY: # Meta status is only set in the response raise Exception("Should not read meta in request") if self.current_procedure == FUNC_RESP_BODY: self.resp_hdr_code.append( """ if let Some(status_code) = self.get_http_response_header(":status") { if status_code == "200" { self.meta_status = "success".to_string(); } else { self.meta_status = "failure".to_string(); } } else { panic!("No status code found in response headers"); } """ ) class WasmGenerator(Visitor): def __init__(self, placement: str) -> None: self.placement = placement if placement != "client" and placement != "server": raise Exception("placement should be sender or receiver") def visitNode(self, node: Node, ctx: WasmContext): return node.__class__.__name__ def visitProgram(self, node: Program, ctx: WasmContext) -> None: node.definition.accept(self, ctx) node.init.accept(self, ctx) for v in ctx.internal_states: if v.init == "" and v.consistency != "strong": v.init = v.type.gen_init() node.req.accept(self, ctx) node.resp.accept(self, ctx) def visitInternal(self, node: Internal, ctx: WasmContext) -> None: # Iterate through all internal state variables and declare them for (i, t, cons, comb, per) in node.internal: state_name = i.name state_wasm_type = t.accept(self, ctx) ctx.declare( state_name, state_wasm_type, False, True, cons.name, comb.name, per.name ) def visitProcedure(self, node: Procedure, ctx: WasmContext): # TODO: Add request and response header processing. match node.name: case "init": ctx.current_procedure = FUNC_INIT procedure_type = "init" # unused, make python happy case "req": ctx.current_procedure = FUNC_REQ_BODY procedure_type = "Request" case "resp": ctx.current_procedure = FUNC_RESP_BODY procedure_type = "Response" case _: raise Exception("unknown function") ctx.clear_temps() if node.name == "req": name = "request" elif node.name == "resp": name = "response" else: name = node.name if name != "init": ctx.declare(f"rpc_{name}", WasmRpcType(f"rpc_{name}", []), True, False) inners = ctx.gen_inners() ctx.push_code(inners) # Boilerplate code for decoding the RPC message prefix_decode_rpc = f""" if let Some(body) = self.get_http_{name}_body(0, body_size) {{ match {ctx.proto}::{ctx.method_name}{procedure_type}::decode(&body[5..]) {{ Ok(mut rpc_{name}) => {{ """ suffix_decode_rpc = f""" }} Err(e) => log::warn!("decode error: {{}}", e), }} }} """ # If the procedure does not access the RPC message, then we do not need to decode it if ctx.current_procedure != FUNC_INIT: if ctx.current_procedure == FUNC_REQ_BODY: if "rpc_req" in ctx.access_ops[ctx.current_procedure]: ctx.push_code(prefix_decode_rpc) elif ctx.current_procedure == FUNC_RESP_BODY: if "rpc_resp" in ctx.access_ops[ctx.current_procedure]: ctx.push_code(prefix_decode_rpc) for p in node.params: name = p.name if ctx.find_var(name) == None:
LOG.error(f"param {name} not found in VisitProcedure")
2
2023-11-13 07:31:52+00:00
4k
tyang816/ProtSSN
src/module/egnn/network.py
[ { "identifier": "EGNN_Sparse", "path": "src/module/egnn/egnn_pytorch_geometric.py", "snippet": "class EGNN_Sparse(MessagePassing):\n \"\"\" Different from the above since it separates the edge assignment\n from the computation (this allows for great reduction in time and \n computations...
from argparse import Namespace from src.module.egnn import EGNN_Sparse from src.module.egnn.utils import get_edge_feature_dims, get_node_feature_dims import torch import torch.nn as nn import torch.nn.functional as F
2,454
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class nodeEncoder(torch.nn.Module): def __init__(self, emb_dim): super(nodeEncoder, self).__init__() self.atom_embedding_list = torch.nn.ModuleList()
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. class nodeEncoder(torch.nn.Module): def __init__(self, emb_dim): super(nodeEncoder, self).__init__() self.atom_embedding_list = torch.nn.ModuleList()
self.node_feature_dim = get_node_feature_dims()
2
2023-11-10 07:21:37+00:00
4k
HypeboyJake/ReinforceTradeAI
sharing/agent.py
[ { "identifier": "DQN", "path": "sharing/models.py", "snippet": "class DQN(nn.Module):\r\n def __init__(self, input_dim, output_dim, shared_network=None):\r\n super().__init__()\r\n self.shared_network = shared_network\r\n\r\n if isinstance(input_dim, tuple):\r\n input_...
from sharing.models import DQN, A2C, PPO, LSTM, DNN, DDQN from sharing.models import ( optimize_dqn, optimize_ddqn, optimize_a2c, optimize_ppo, optimize_lstm, optimize_dnn, calculate_log_probs_and_values, ) import torch import torch.optim as optim import numpy as np
3,511
# "Please select the optimizer to use." optimizer_type='Adam', shared_network=False, clip_ratio=0.2, lr=0.0001, weight_decay=0, **kwargs): self.epsilon = epsilon self.gamma = gamma self.shared_network = shared_network self.clip_ratio = clip_ratio self.old_log_probs = [] self.ppo_values = [] self.value_loss_coef = 0.5 self.entropy_coef = 0.01 model_class = MODEL_MAPPING.get(agent_type) if not model_class: raise ValueError(f"Unsupported agent type: {agent_type}") self.model = model_class(input_dim, output_dim, shared_network) optimizer_class = OPTIMIZER_MAPPING.get(optimizer_type) if not optimizer_class: raise ValueError(f"Unsupported optimizer type: {optimizer_type}") self.optimizer = optimizer_class(self.model.parameters(), lr=lr, weight_decay=weight_decay, **kwargs) if agent_type in ['DQN', 'DDQN']: self.target_model = model_class(input_dim, output_dim, shared_network) self.target_model.load_state_dict(self.model.state_dict()) self.target_model.eval() def select_action(self, state): # 0 : Buy, 1 : Sell, 3 : Hold action_space = [0, 1, 2] state = state.float() # Epsilon-greedy if np.random.rand() < self.epsilon: return np.random.choice(action_space) else: if isinstance(self.model, DQN): with torch.no_grad(): model_output = self.model(state) max_value, max_index = model_output.max(0) return max_index.item() elif isinstance(self.model, DDQN): with torch.no_grad(): state = state.unsqueeze(0).float() q_values = self.model(state) return q_values.max(1)[1].item() elif isinstance(self.model, A2C): with torch.no_grad(): state = state.unsqueeze(0).float() policy, value = self.model(state) dist = torch.distributions.Categorical(policy) action = dist.sample() log_prob = dist.log_prob(action) self.last_log_prob = log_prob self.last_value = value return action.item() elif isinstance(self.model, PPO): with torch.no_grad(): policy, value = self.model(state) dist = torch.distributions.Categorical(policy) action = dist.sample() log_prob = dist.log_prob(action) self.old_log_probs.append(log_prob) self.ppo_values.append(value) return action.item() elif isinstance(self.model, LSTM): with torch.no_grad(): state = state.unsqueeze(0).unsqueeze(1) log_probs, _, _ = self.model(state) probs = torch.exp(log_probs) action = torch.multinomial(probs, 1).item() return action elif isinstance(self.model, DNN): with torch.no_grad(): model_output = self.model(state) max_value, max_index = model_output.max(0) return max_index.item() else: raise ValueError(f"Unsupported model type: {type(self.model)}") def learn(self, state, action, reward, next_state, done): if isinstance(self.model, DQN): state = state.unsqueeze(0) if state.dim() == 1 else state next_state = next_state.unsqueeze(0) if next_state.dim() == 1 else next_state action = torch.tensor([action], dtype=torch.int64).unsqueeze(0) reward = torch.tensor([reward], dtype=torch.float32).unsqueeze(0) done = torch.tensor([done], dtype=torch.float32).unsqueeze(0) dqn_batch = (state, action, reward, next_state, done) optimize_dqn(self.model, self.target_model, self.optimizer, dqn_batch, self.gamma) elif isinstance(self.model, DDQN): state = state.unsqueeze(0) if state.dim() == 1 else state next_state = next_state.unsqueeze(0) if next_state.dim() == 1 else next_state action = torch.tensor([action], dtype=torch.int64).unsqueeze(0) reward = torch.tensor([reward], dtype=torch.float32).unsqueeze(0) done = torch.tensor([done], dtype=torch.float32).unsqueeze(0) ddqn_batch = (state, action, reward, next_state, done) optimize_ddqn(self.model, self.target_model, self.optimizer, ddqn_batch, self.gamma) elif isinstance(self.model, A2C): reward_tensor = torch.tensor(reward).float() done_tensor = torch.tensor(done, dtype=torch.float32) state = state.float() action_tensor = torch.tensor(action).long() next_state = next_state.float() done_tensor = done_tensor.unsqueeze(0) if done_tensor.dim() == 0 else done_tensor log_probs, values = calculate_log_probs_and_values(self.model, state, action_tensor) a2c_batch = (state, action_tensor, reward_tensor, next_state, done_tensor, log_probs, values) optimize_a2c(self.model, self.optimizer, a2c_batch, self.gamma) elif isinstance(self.model, PPO): if not self.old_log_probs or not self.ppo_values: return old_log_probs = torch.stack(self.old_log_probs) ppo_values = torch.stack(self.ppo_values) ppo_batch = (state, action, reward, next_state, done, old_log_probs, ppo_values)
# 모델과 옵티마이저 매핑 MODEL_MAPPING = {'A2C': A2C, 'PPO': PPO, 'DDQN': DDQN, 'LSTM': LSTM, 'DNN': DNN, 'DQN': DQN} OPTIMIZER_MAPPING = {'Adam': optim.Adam, 'SGD': optim.SGD} class Agent: def __init__(self, input_dim, output_dim, epsilon, gamma, # "사용할 모델을 선택하세요" # "Please select the model to use." agent_type='PPO', # "사용할 옵티마이저를 선택하세요" # "Please select the optimizer to use." optimizer_type='Adam', shared_network=False, clip_ratio=0.2, lr=0.0001, weight_decay=0, **kwargs): self.epsilon = epsilon self.gamma = gamma self.shared_network = shared_network self.clip_ratio = clip_ratio self.old_log_probs = [] self.ppo_values = [] self.value_loss_coef = 0.5 self.entropy_coef = 0.01 model_class = MODEL_MAPPING.get(agent_type) if not model_class: raise ValueError(f"Unsupported agent type: {agent_type}") self.model = model_class(input_dim, output_dim, shared_network) optimizer_class = OPTIMIZER_MAPPING.get(optimizer_type) if not optimizer_class: raise ValueError(f"Unsupported optimizer type: {optimizer_type}") self.optimizer = optimizer_class(self.model.parameters(), lr=lr, weight_decay=weight_decay, **kwargs) if agent_type in ['DQN', 'DDQN']: self.target_model = model_class(input_dim, output_dim, shared_network) self.target_model.load_state_dict(self.model.state_dict()) self.target_model.eval() def select_action(self, state): # 0 : Buy, 1 : Sell, 3 : Hold action_space = [0, 1, 2] state = state.float() # Epsilon-greedy if np.random.rand() < self.epsilon: return np.random.choice(action_space) else: if isinstance(self.model, DQN): with torch.no_grad(): model_output = self.model(state) max_value, max_index = model_output.max(0) return max_index.item() elif isinstance(self.model, DDQN): with torch.no_grad(): state = state.unsqueeze(0).float() q_values = self.model(state) return q_values.max(1)[1].item() elif isinstance(self.model, A2C): with torch.no_grad(): state = state.unsqueeze(0).float() policy, value = self.model(state) dist = torch.distributions.Categorical(policy) action = dist.sample() log_prob = dist.log_prob(action) self.last_log_prob = log_prob self.last_value = value return action.item() elif isinstance(self.model, PPO): with torch.no_grad(): policy, value = self.model(state) dist = torch.distributions.Categorical(policy) action = dist.sample() log_prob = dist.log_prob(action) self.old_log_probs.append(log_prob) self.ppo_values.append(value) return action.item() elif isinstance(self.model, LSTM): with torch.no_grad(): state = state.unsqueeze(0).unsqueeze(1) log_probs, _, _ = self.model(state) probs = torch.exp(log_probs) action = torch.multinomial(probs, 1).item() return action elif isinstance(self.model, DNN): with torch.no_grad(): model_output = self.model(state) max_value, max_index = model_output.max(0) return max_index.item() else: raise ValueError(f"Unsupported model type: {type(self.model)}") def learn(self, state, action, reward, next_state, done): if isinstance(self.model, DQN): state = state.unsqueeze(0) if state.dim() == 1 else state next_state = next_state.unsqueeze(0) if next_state.dim() == 1 else next_state action = torch.tensor([action], dtype=torch.int64).unsqueeze(0) reward = torch.tensor([reward], dtype=torch.float32).unsqueeze(0) done = torch.tensor([done], dtype=torch.float32).unsqueeze(0) dqn_batch = (state, action, reward, next_state, done) optimize_dqn(self.model, self.target_model, self.optimizer, dqn_batch, self.gamma) elif isinstance(self.model, DDQN): state = state.unsqueeze(0) if state.dim() == 1 else state next_state = next_state.unsqueeze(0) if next_state.dim() == 1 else next_state action = torch.tensor([action], dtype=torch.int64).unsqueeze(0) reward = torch.tensor([reward], dtype=torch.float32).unsqueeze(0) done = torch.tensor([done], dtype=torch.float32).unsqueeze(0) ddqn_batch = (state, action, reward, next_state, done) optimize_ddqn(self.model, self.target_model, self.optimizer, ddqn_batch, self.gamma) elif isinstance(self.model, A2C): reward_tensor = torch.tensor(reward).float() done_tensor = torch.tensor(done, dtype=torch.float32) state = state.float() action_tensor = torch.tensor(action).long() next_state = next_state.float() done_tensor = done_tensor.unsqueeze(0) if done_tensor.dim() == 0 else done_tensor log_probs, values = calculate_log_probs_and_values(self.model, state, action_tensor) a2c_batch = (state, action_tensor, reward_tensor, next_state, done_tensor, log_probs, values) optimize_a2c(self.model, self.optimizer, a2c_batch, self.gamma) elif isinstance(self.model, PPO): if not self.old_log_probs or not self.ppo_values: return old_log_probs = torch.stack(self.old_log_probs) ppo_values = torch.stack(self.ppo_values) ppo_batch = (state, action, reward, next_state, done, old_log_probs, ppo_values)
optimize_ppo(self.model, self.optimizer, ppo_batch, self.clip_ratio)
9
2023-11-16 12:04:20+00:00
4k
sunholo-data/sunholo-py
sunholo/components/retriever.py
[ { "identifier": "setup_logging", "path": "sunholo/logging.py", "snippet": "def setup_logging(self, log_level=logging.INFO, logger_name=None):\n if log_level:\n self.log_level = log_level\n if logger_name:\n self.logger_name = logger_name\n\n try:\n caller_info = self._get_c...
from ..logging import setup_logging from .vectorstore import pick_vectorstore from ..utils import load_config_key from .llm import get_embeddings from ..utils.gcp import get_gcp_project from langchain.retrievers import MergerRetriever from langchain.retrievers import GoogleCloudEnterpriseSearchRetriever, GoogleVertexAISearchRetriever from langchain.document_transformers import ( EmbeddingsRedundantFilter, EmbeddingsClusteringFilter, ) from langchain.retrievers.document_compressors import DocumentCompressorPipeline from langchain.retrievers import ContextualCompressionRetriever
2,049
# Copyright [2023] [Holosun ApS] # # 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. logging = setup_logging() # https://python.langchain.com/docs/integrations/retrievers/merger_retriever def load_memories(vector_name): memories = load_config_key("memory", vector_name, filename="config/llm_config.yaml") logging.info(f"Found memory settings for {vector_name}: {memories}") if len(memories) == 0: logging.info(f"No memory settings found for {vector_name}") return None return memories def pick_retriever(vector_name, embeddings=None): memories = load_memories(vector_name) retriever_list = [] for memory in memories: # Iterate over the list for key, value in memory.items(): # Now iterate over the dictionary logging.info(f"Found memory {key}") vectorstore = value.get('vectorstore', None) if vectorstore is not None: logging.info(f"Found vectorstore {vectorstore}") if embeddings is None:
# Copyright [2023] [Holosun ApS] # # 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. logging = setup_logging() # https://python.langchain.com/docs/integrations/retrievers/merger_retriever def load_memories(vector_name): memories = load_config_key("memory", vector_name, filename="config/llm_config.yaml") logging.info(f"Found memory settings for {vector_name}: {memories}") if len(memories) == 0: logging.info(f"No memory settings found for {vector_name}") return None return memories def pick_retriever(vector_name, embeddings=None): memories = load_memories(vector_name) retriever_list = [] for memory in memories: # Iterate over the list for key, value in memory.items(): # Now iterate over the dictionary logging.info(f"Found memory {key}") vectorstore = value.get('vectorstore', None) if vectorstore is not None: logging.info(f"Found vectorstore {vectorstore}") if embeddings is None:
embeddings = get_embeddings(vector_name)
3
2023-11-14 14:53:19+00:00
4k
atlantic-quantum/Shipyard
shipyard/setup/external.py
[ { "identifier": "CoreType", "path": "shipyard/setup/instr_types.py", "snippet": "" }, { "identifier": "SetupInternal", "path": "shipyard/setup/internal.py", "snippet": "class SetupInternal(BaseModel):\n\n \"\"\"\n A Pydantic model containing the information required to compile an o...
from pathlib import Path from openpulse import ast from openpulse.printer import dumps from pydantic import BaseModel from .instr_types import CoreType, InstrumentType, instrument_type_info from .internal import SetupInternal import yaml
1,633
""" External representation of the setup, meant to be used by the user. and free the user from having to know the internal representation of the setup. This representation is purely a data model. """ __all__ = ["SetupExternal"] class SetupExternal(BaseModel): """ External representation of the setup, meant to be used by the user. and free the user from having to know the internal representation of the setup. This representation is purely a data model. Args: Frames (dict[str, Frame]): A dictionary of Frames, where the key is the name of the frame Instruments (dict[str, Instrument]): A dictionary of Instruments, where the key is the name of the instrument Ports (dict[str, Port]): A dictionary of Ports, where the key is the name of the port """ class Frame(BaseModel): """ Data model for a Frame Args: port (str): The name of the port the frame is connected to frequency (float): The frequency of the frame phase (float): The phase of the frame """ port: str frequency: float = 0.0 phase: float = 0.0 def __hash__(self) -> int: return hash(self.__class__) + hash(tuple(self.__dict__.values())) class Instrument(BaseModel): """ Data model for an Instrument Args: serial (str): The serial number of the instrument type (InstrumentType - Literal String): The type of the instrument, see shipyard.instr_types for details. """ serial: str
""" External representation of the setup, meant to be used by the user. and free the user from having to know the internal representation of the setup. This representation is purely a data model. """ __all__ = ["SetupExternal"] class SetupExternal(BaseModel): """ External representation of the setup, meant to be used by the user. and free the user from having to know the internal representation of the setup. This representation is purely a data model. Args: Frames (dict[str, Frame]): A dictionary of Frames, where the key is the name of the frame Instruments (dict[str, Instrument]): A dictionary of Instruments, where the key is the name of the instrument Ports (dict[str, Port]): A dictionary of Ports, where the key is the name of the port """ class Frame(BaseModel): """ Data model for a Frame Args: port (str): The name of the port the frame is connected to frequency (float): The frequency of the frame phase (float): The phase of the frame """ port: str frequency: float = 0.0 phase: float = 0.0 def __hash__(self) -> int: return hash(self.__class__) + hash(tuple(self.__dict__.values())) class Instrument(BaseModel): """ Data model for an Instrument Args: serial (str): The serial number of the instrument type (InstrumentType - Literal String): The type of the instrument, see shipyard.instr_types for details. """ serial: str
type: InstrumentType
0
2023-11-16 17:37:29+00:00
4k
PrAsAnNaRePo/LocalAgent
localagent/interpreter.py
[ { "identifier": "get_prompt_from_template", "path": "localagent/utils.py", "snippet": "def get_prompt_from_template(system, history, human_, assistant_, eos_token):\n for i in history:\n if i['role'] == 'user':\n system += f'{human_}{i[\"content\"]}{eos_token}'\n ...
import subprocess import sys from localagent.utils import get_prompt_from_template, internal_monologue from localagent.gen import run, stream_run, ollama_generate from rich.console import Console
1,637
console = Console() CODE_INTERPRETER = """You are Open Interpreter, a world-class programmer that can complete any goal by executing code. First, write a plan. **Always recap the plan between each code block**. When you execute code, it will be executed **on the user's machine**. The user has given you **full and complete permission** to execute any code necessary to complete the task. If you want to send data between programming languages, save the data to a txt or json. You can access the internet. Run **any code** to achieve the goal, and if at first you don't succeed, try again and again. You can install new packages. When a user refers to a filename, they're likely referring to an existing file in the directory you're currently executing code in. Write messages to the user in Markdown. In general, try to **make plans** with as few steps as possible. Remember that one code block is considered as a single file and you can't able to access the variable from first code blocks in the second one. You are capable of **any** task. Don't install libraries using '!' in the python code block instead use seperate bash code block. As a open interpreter you should mostly respond with codes more than a text. Always tries to print the things up so you can know them via output. """ def extract_code(string): code_blocks = [] parts = string.split("```") for i in range(1, len(parts), 2): lines = parts[i].split("\n") lang = lines[0] code = "\n".join(lines[1:]) code_blocks.append((lang, code)) return code_blocks class Interpreter: def __init__(self, exec, max_try, human_, assistant_, eos_token, stream=False) -> None: self.history = [] self.exec = exec self.max_try = max_try self.human_ = human_ self.assistant_ = assistant_ self.eos_token = eos_token self.stream = stream def execute_code(self, lang, code, timeout=10): if lang.lower() == 'python': try: output = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: print(f"Execution of Python code timed out after {timeout} seconds.") return None elif lang.lower() == 'bash': try: output = subprocess.run(code, shell=True, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: print(f"Execution of Bash code timed out after {timeout} seconds.") return None else: print('Only supported python and ') return None return output def __call__(self, task): print('\n') internal_monologue("Interpreter is executing the code...\n") self.history.append({'role':'user', 'content':task}) count = 1 while True and count <= self.max_try:
console = Console() CODE_INTERPRETER = """You are Open Interpreter, a world-class programmer that can complete any goal by executing code. First, write a plan. **Always recap the plan between each code block**. When you execute code, it will be executed **on the user's machine**. The user has given you **full and complete permission** to execute any code necessary to complete the task. If you want to send data between programming languages, save the data to a txt or json. You can access the internet. Run **any code** to achieve the goal, and if at first you don't succeed, try again and again. You can install new packages. When a user refers to a filename, they're likely referring to an existing file in the directory you're currently executing code in. Write messages to the user in Markdown. In general, try to **make plans** with as few steps as possible. Remember that one code block is considered as a single file and you can't able to access the variable from first code blocks in the second one. You are capable of **any** task. Don't install libraries using '!' in the python code block instead use seperate bash code block. As a open interpreter you should mostly respond with codes more than a text. Always tries to print the things up so you can know them via output. """ def extract_code(string): code_blocks = [] parts = string.split("```") for i in range(1, len(parts), 2): lines = parts[i].split("\n") lang = lines[0] code = "\n".join(lines[1:]) code_blocks.append((lang, code)) return code_blocks class Interpreter: def __init__(self, exec, max_try, human_, assistant_, eos_token, stream=False) -> None: self.history = [] self.exec = exec self.max_try = max_try self.human_ = human_ self.assistant_ = assistant_ self.eos_token = eos_token self.stream = stream def execute_code(self, lang, code, timeout=10): if lang.lower() == 'python': try: output = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: print(f"Execution of Python code timed out after {timeout} seconds.") return None elif lang.lower() == 'bash': try: output = subprocess.run(code, shell=True, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: print(f"Execution of Bash code timed out after {timeout} seconds.") return None else: print('Only supported python and ') return None return output def __call__(self, task): print('\n') internal_monologue("Interpreter is executing the code...\n") self.history.append({'role':'user', 'content':task}) count = 1 while True and count <= self.max_try:
prompt = get_prompt_from_template(CODE_INTERPRETER, self.history, self.human_, self.assistant_, self.eos_token)
0
2023-11-10 07:47:41+00:00
4k
ceterum1/llm-defender-subnet
scripts/prep.py
[ { "identifier": "YaraEngine", "path": "llm_defender/core/miners/engines/prompt_injection/yara.py", "snippet": "class YaraEngine(BaseEngine):\n \"\"\"This class implements the YARA engine.\n \n YARA is a powerful pattern matching tool that can be used to analyze\n strings based on boolean ope...
import sys 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
3,594
""" This script prepares the engines before miner is executed. """ def prepare_engines(): """Prepare the engines""" # Prepare text classification engine if not TextClassificationEngine().prepare(): print("Unable to prepare text classification engine") sys.exit(1) print("Prepared Text Classification engine") # Prepare vector search engine
""" This script prepares the engines before miner is executed. """ def prepare_engines(): """Prepare the engines""" # Prepare text classification engine if not TextClassificationEngine().prepare(): print("Unable to prepare text classification engine") sys.exit(1) print("Prepared Text Classification engine") # Prepare vector search engine
if not VectorEngine().prepare():
2
2023-11-14 18:10:35+00:00
4k
Cymaphore/orfodon-service
orfodon_service.py
[ { "identifier": "config", "path": "config.py", "snippet": "" }, { "identifier": "feeds", "path": "feeds.py", "snippet": "" }, { "identifier": "hashtag_replace", "path": "hashtag_modification.py", "snippet": "" }, { "identifier": "hashtag_blacklist", "path": "h...
import re import yaml import copy import feedparser import time import requests import hashlib from datetime import datetime from bs4 import BeautifulSoup from mastodon import Mastodon from pprint import pprint from config import config from credentials import credentials from feeds import feeds from hashtag_modification import hashtag_replace from hashtag_modification import hashtag_blacklist from hashtag_modification import category_aliases from hashtag_modification import oewa_sport_aliases from hashtag_modification import oewa_bypass
2,091
ttags = entry.get('orfon_oewacategory', {}).get("rdf:resource", '') if not ttags is None and not ttags == "": ttags = ttags.split(":")[3].split("/") if "enable_oewa_sport" in feed and feed["enable_oewa_sport"]: if not ttags[1] is None: category = ttags[1] category = oewa_sport_aliases.get(category, category) if not ttags[0] is None: hashtags.append('#{}'.format(ttags[0])) if not first_oewa: first_oewa = True category = ttags[0] #pprint(ttags[1]) except: () #category = entry.get("dc_subject", category) ttags = entry.get('tags') if not ttags is None: for tag1 in entry.get('tags'): for tag2 in tag1["term"].split(" "): tag = tag2 \ .replace(".", "") \ .replace("-", "") \ .replace("&", "") \ .replace("/", "") \ .replace(":", "") hashtags.append('#{}'.format(tag)) if "additional_hashtags" in feed: hashtags.extend(feed["additional_hashtags"]) try: for ht in hashtag_wordlist: if re.search(r"\b" + re.escape(ht) + r"\b", title): hashtags.append("#" + ht) except: () for tagi in range(len(hashtags)): if hashtags[tagi] in hashtag_replace: hashtags[tagi] = copy.copy(hashtag_replace[hashtags[tagi]]) hashtags = list(dict.fromkeys(hashtags)) try: hashtags.remove("#") except: () for bt in hashtag_blacklist: try: hashtags.remove(bt) except: () #pprint(hashtags) ts_story_details = 0 if "ts_story_details" in oldPosting: ts_story_details = oldPosting["ts_story_details"] ec_story_details = 0 if "ec_story_details" in oldPosting: ec_story_details = oldPosting["ec_story_details"] checksum_story_details = [] if "checksum_story_details" in oldPosting: checksum_story_details = oldPosting["checksum_story_details"] has_story_details = False if text and len(text) > 0: raw_posting = text post_type_text = True else: if "boost_target" in oldPosting and len(oldPosting["boost_target"]) > 0: boost_target = oldPosting["boost_target"] if "ts_story_details" in oldPosting: if ts_story_details < (ts() - 600): story_details = get_story_details(url) ts_story_details = ts() if len(story_details["text"]) >= len(title): raw_posting = story_details["text"] has_story_details = True else: raw_posting = title else: raw_posting = oldPosting["text"] elif "text" in oldPosting and len(oldPosting["text"]) > 0: raw_posting = oldPosting["text"] else: raw_posting = title else: story_details = get_story_details(url) ts_story_details = ts() boost_target = story_details["url"] if len(story_details["text"]) >= len(title): raw_posting = story_details["text"] has_story_details = True else: raw_posting = title post_type_text = False if "text" in oldPosting and raw_posting != oldPosting["text"]: if has_story_details and ec_story_details < 5: posting_checksum = hashlib.md5(raw_posting.encode("utf8")).hexdigest() if not posting_checksum in checksum_story_details: ec_story_details = ec_story_details + 1 edited = True checksum_story_details.append(posting_checksum) elif not has_story_details: edited = True if edited or not posted: cu_posting = cleanup(raw_posting, hashtags) hashtags = list(dict.fromkeys(hashtags))
## # @mainpage ORFodon service script # # Quick and dirty solution to turn ORF.at into a Mastodon-site # # @Warning this is tailormade for ORF.at and will not work without modification # with other RSS based news sites! # # Inspired by feediverse from Ed Summers # # Process configuration, fetch news entries and post them to different accounts # # Dependencies: # - bs4 # - feedparser # - yaml # - mastodon # # License: The MIT License (MIT) # Copyright: Martin Eitzenberger <x@cymaphore.net> # @cymaphore@i.cymaphore.net # https://cymaphore.net # # @todo Secondary urls like https://vorarlberg.orf.at/radio/stories/3231551/ https://steiermark.orf.at/magazin/stories/3232156/ # @todo Sort news in descending order by date when bulk processing <-- low prio, usually not an issue # @todo Account mentioner ("der Standard" --> @derStandard)? # @todo extract top hashtags from current posts and add them to profile # @todo ORF_Topos as channel # ############################################################################# # External components ############################################################################# # Configuration ############################################################################# # Current fetched articles / state global state # State from previous run cycle global oldState # Global hashtag wordlist global hashtag_wordlist state = {} oldState = {} hashtag_wordlist = [] ############################################################################# ## # Main function # Call all the stages in correct order def main(): # Load hashtag wordlists load_hashtags() # Load previous state, initialize new state load_state() # Load the configured feeds and preprocess text load_feeds() # Grab post references from other channels for boosting, keep id from oldState grab_posts() # Post newly generated articles to the channels post_feeds() # Save state for next cycle save_state() ############################################################################# ## # Load hashtag wordlists def load_hashtags(): hashtags_filename = config["files"]["global_hashtags"] if True: hashtags_file = open(hashtags_filename, "r") global hashtag_wordlist hashtag_wordlist = hashtags_file.read().splitlines() ############################################################################# ## # Load the configured feeds and preprocess text def load_state(): global state global oldState global hashtag_wordlist try: with open(config["files"]["state"]) as fh: oldState = yaml.load(fh, yaml.SafeLoader) except: oldState = {} for feed in feeds: if not feed["id"] in state: state[feed["id"]] = {} if not feed["id"] in oldState: oldState[feed["id"]] = {} ############################################################################# ## # Save state for next cycle def save_state(): with open(config["files"]["state"], 'w') as fh: fh.write(yaml.dump(state, default_flow_style=False)) ############################################################################# ## # Load the configured feeds and preprocess text def load_feeds(): global state global oldState for feed in feeds: feedStateOld = oldState[feed["id"]] feedState = state[feed["id"]] if "url" in feed: entries = feedparser.parse(feed["url"]).entries if len(entries) < 1: raise RuntimeError("No elements in feed " + feed["url"]) for entry in entries: title = entry.get('title') text = entry.get('summary') url = entry.get('link') category = entry.get('category') raw_posting = "" post_type_text = False hashtags = [] updated = entry.get('updated') boost_target = "" edited = False exists = False oldPosting = {} status_id = 0 posted = False post_text = "" boosted = False ref = "" if url in feedStateOld: exists = True oldPosting = feedStateOld[url] if "status_id" in oldPosting: status_id = oldPosting["status_id"] if "posted" in oldPosting: posted = oldPosting["posted"] if "boosted" in oldPosting: boosted = oldPosting["boosted"] first_oewa = False if "enable_oewa_sport" in feed and feed["enable_oewa_sport"]: first_oewa = True if not category in oewa_bypass: first_oewa = True try: ttags = entry.get('orfon_oewacategory', {}).get("rdf:resource", '') if not ttags is None and not ttags == "": ttags = ttags.split(":")[3].split("/") if "enable_oewa_sport" in feed and feed["enable_oewa_sport"]: if not ttags[1] is None: category = ttags[1] category = oewa_sport_aliases.get(category, category) if not ttags[0] is None: hashtags.append('#{}'.format(ttags[0])) if not first_oewa: first_oewa = True category = ttags[0] #pprint(ttags[1]) except: () #category = entry.get("dc_subject", category) ttags = entry.get('tags') if not ttags is None: for tag1 in entry.get('tags'): for tag2 in tag1["term"].split(" "): tag = tag2 \ .replace(".", "") \ .replace("-", "") \ .replace("&", "") \ .replace("/", "") \ .replace(":", "") hashtags.append('#{}'.format(tag)) if "additional_hashtags" in feed: hashtags.extend(feed["additional_hashtags"]) try: for ht in hashtag_wordlist: if re.search(r"\b" + re.escape(ht) + r"\b", title): hashtags.append("#" + ht) except: () for tagi in range(len(hashtags)): if hashtags[tagi] in hashtag_replace: hashtags[tagi] = copy.copy(hashtag_replace[hashtags[tagi]]) hashtags = list(dict.fromkeys(hashtags)) try: hashtags.remove("#") except: () for bt in hashtag_blacklist: try: hashtags.remove(bt) except: () #pprint(hashtags) ts_story_details = 0 if "ts_story_details" in oldPosting: ts_story_details = oldPosting["ts_story_details"] ec_story_details = 0 if "ec_story_details" in oldPosting: ec_story_details = oldPosting["ec_story_details"] checksum_story_details = [] if "checksum_story_details" in oldPosting: checksum_story_details = oldPosting["checksum_story_details"] has_story_details = False if text and len(text) > 0: raw_posting = text post_type_text = True else: if "boost_target" in oldPosting and len(oldPosting["boost_target"]) > 0: boost_target = oldPosting["boost_target"] if "ts_story_details" in oldPosting: if ts_story_details < (ts() - 600): story_details = get_story_details(url) ts_story_details = ts() if len(story_details["text"]) >= len(title): raw_posting = story_details["text"] has_story_details = True else: raw_posting = title else: raw_posting = oldPosting["text"] elif "text" in oldPosting and len(oldPosting["text"]) > 0: raw_posting = oldPosting["text"] else: raw_posting = title else: story_details = get_story_details(url) ts_story_details = ts() boost_target = story_details["url"] if len(story_details["text"]) >= len(title): raw_posting = story_details["text"] has_story_details = True else: raw_posting = title post_type_text = False if "text" in oldPosting and raw_posting != oldPosting["text"]: if has_story_details and ec_story_details < 5: posting_checksum = hashlib.md5(raw_posting.encode("utf8")).hexdigest() if not posting_checksum in checksum_story_details: ec_story_details = ec_story_details + 1 edited = True checksum_story_details.append(posting_checksum) elif not has_story_details: edited = True if edited or not posted: cu_posting = cleanup(raw_posting, hashtags) hashtags = list(dict.fromkeys(hashtags))
if category in category_aliases:
4
2023-11-10 10:25:43+00:00
4k
Vitesco-Technologies/ldap-password-rotation
tests/test_lambda.py
[ { "identifier": "lambda_function", "path": "src/lambda_function.py", "snippet": "SECRETS_MANAGER_KEY_USERNAME = (\n os.environ.get(\"SECRETS_MANAGER_KEY_USERNAME\") or \"username\"\n)\nSECRETS_MANAGER_KEY_PASSWORD = (\n os.environ.get(\"SECRETS_MANAGER_KEY_PASSWORD\") or \"password\"\n)\nSECRETS_M...
import json import logging import os import boto3 import ldap3 import mock import pytest from uuid import uuid4 from moto import mock_lambda, mock_secretsmanager from src import lambda_function from .utilities import lambda_util from .utilities.ldap_test import LdapServer
1,622
# Copyright 2023 Daniel Dias, Vitesco Technologies # # SPDX-License-Identifier: Apache-2.0 _region = "eu-central-1" # server is defined as global to allow us to update it when we mock # ldap3.extend.microsoft.modifyPassword.ad_modify_password with mock_ad_modify_password _server = LdapServer() logger = logging.getLogger() logger.setLevel(logging.INFO) ############ # fixtures # ############ @pytest.fixture(scope="function", autouse=True) def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ["AWS_ACCESS_KEY_ID"] = "testing" os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" os.environ["AWS_SECURITY_TOKEN"] = "testing" os.environ["AWS_SESSION_TOKEN"] = "testing" os.environ["AWS_DEFAULT_REGION"] = _region @pytest.fixture(scope="function", autouse=True) def lambda_env(): lambda_function.SECRETS_MANAGER_KEY_USERNAME = "bind_dn" lambda_function.SECRETS_MANAGER_KEY_PASSWORD = "password" lambda_function.SECRETS_MANAGER_REGION = _region lambda_function.EXCLUDE_CHARACTERS = "/'\"\\" lambda_function.LDAP_BASE_DN = "dc=example,dc=com" lambda_function.LDAP_USER_AUTH_ATTRIBUTE = "userPrincipalName" lambda_function.SECRETS_MANAGER_KEY_DN = "ldap_bind_dn" @pytest.fixture(scope="function", autouse=True) def lambda_ldap_env(ldap_config): lambda_function.LDAP_SERVER_LIST = '["localhost"]' lambda_function.LDAP_SERVER_PORT = ldap_config["port"] # Currently ldap_test doesn't support SSL lambda_function.LDAP_USE_SSL = False @pytest.fixture(scope="function") def ldap_server(config=None): if config is None: config = { "port": 10389, "bind_dn": "cn=admin,dc=example,dc=com", "password": "password", "base": { "attributes": {"dc": "example"}, "dn": "dc=example,dc=com", "objectclass": ["domain"], }, "entries": [ { "objectclass": "domain", "dn": "dc=users,dc=example,dc=com", "attributes": {"dc": "users"}, }, { "objectclass": "organization", "dn": "o=foocompany,dc=users,dc=example,dc=com", "attributes": {"o": "foocompany"}, }, { "objectclass": "user", "dn": "cn=users,dc=example,dc=com", "attributes": { "o": "foocompany", "userPrincipalName": "cn=admin,dc=example,dc=com", }, }, ], } global _server _server = LdapServer(config) _server.start() yield _server _server.stop() @pytest.fixture(scope="function") def ldap_config(ldap_server, lambda_env): config = ldap_server.config yield config @pytest.fixture(scope="function") def secretsmanager(aws_credentials): with mock_secretsmanager(): yield boto3.client("secretsmanager", region_name=_region) @pytest.fixture(scope="function") def lambda_conn(aws_credentials): with mock_lambda(): yield boto3.client("lambda", region_name=_region) @pytest.fixture(scope="function") def lambda_func(lambda_conn): func = lambda_conn.create_function( FunctionName="testFunction", Runtime="python3.9",
# Copyright 2023 Daniel Dias, Vitesco Technologies # # SPDX-License-Identifier: Apache-2.0 _region = "eu-central-1" # server is defined as global to allow us to update it when we mock # ldap3.extend.microsoft.modifyPassword.ad_modify_password with mock_ad_modify_password _server = LdapServer() logger = logging.getLogger() logger.setLevel(logging.INFO) ############ # fixtures # ############ @pytest.fixture(scope="function", autouse=True) def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ["AWS_ACCESS_KEY_ID"] = "testing" os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" os.environ["AWS_SECURITY_TOKEN"] = "testing" os.environ["AWS_SESSION_TOKEN"] = "testing" os.environ["AWS_DEFAULT_REGION"] = _region @pytest.fixture(scope="function", autouse=True) def lambda_env(): lambda_function.SECRETS_MANAGER_KEY_USERNAME = "bind_dn" lambda_function.SECRETS_MANAGER_KEY_PASSWORD = "password" lambda_function.SECRETS_MANAGER_REGION = _region lambda_function.EXCLUDE_CHARACTERS = "/'\"\\" lambda_function.LDAP_BASE_DN = "dc=example,dc=com" lambda_function.LDAP_USER_AUTH_ATTRIBUTE = "userPrincipalName" lambda_function.SECRETS_MANAGER_KEY_DN = "ldap_bind_dn" @pytest.fixture(scope="function", autouse=True) def lambda_ldap_env(ldap_config): lambda_function.LDAP_SERVER_LIST = '["localhost"]' lambda_function.LDAP_SERVER_PORT = ldap_config["port"] # Currently ldap_test doesn't support SSL lambda_function.LDAP_USE_SSL = False @pytest.fixture(scope="function") def ldap_server(config=None): if config is None: config = { "port": 10389, "bind_dn": "cn=admin,dc=example,dc=com", "password": "password", "base": { "attributes": {"dc": "example"}, "dn": "dc=example,dc=com", "objectclass": ["domain"], }, "entries": [ { "objectclass": "domain", "dn": "dc=users,dc=example,dc=com", "attributes": {"dc": "users"}, }, { "objectclass": "organization", "dn": "o=foocompany,dc=users,dc=example,dc=com", "attributes": {"o": "foocompany"}, }, { "objectclass": "user", "dn": "cn=users,dc=example,dc=com", "attributes": { "o": "foocompany", "userPrincipalName": "cn=admin,dc=example,dc=com", }, }, ], } global _server _server = LdapServer(config) _server.start() yield _server _server.stop() @pytest.fixture(scope="function") def ldap_config(ldap_server, lambda_env): config = ldap_server.config yield config @pytest.fixture(scope="function") def secretsmanager(aws_credentials): with mock_secretsmanager(): yield boto3.client("secretsmanager", region_name=_region) @pytest.fixture(scope="function") def lambda_conn(aws_credentials): with mock_lambda(): yield boto3.client("lambda", region_name=_region) @pytest.fixture(scope="function") def lambda_func(lambda_conn): func = lambda_conn.create_function( FunctionName="testFunction", Runtime="python3.9",
Role=lambda_util.get_role_name(),
1
2023-11-17 15:03:58+00:00
4k
MAGICS-LAB/SparseModernHopfield
real_world_mil.py
[ { "identifier": "load_data", "path": "datasets/loader.py", "snippet": "def load_data(args):\n features = []\n labels = []\n current_file = os.path.abspath(os.path.dirname(__file__))\n dataset = scipy.io.loadmat(current_file + '/mil_datasets/{args.dataset}_100x100_matlab.mat') # loads fox da...
import os import math import argparse import torch.nn.functional as F from torch.utils.data import DataLoader, random_split from layers import * from datasets.loader import load_data, DummyDataset, load_ucsb from sklearn.metrics import roc_auc_score from sklearn.model_selection import StratifiedKFold, train_test_split from ray import tune from ray.air import session, RunConfig from ray.tune.schedulers import ASHAScheduler
2,847
# Process data by Hopfield-based network. out = network(data, mask=mask) optimizer.zero_grad() loss = F.binary_cross_entropy_with_logits(input=out, target=target, reduction=r'mean') # Update network parameters. loss.backward() torch.nn.utils.clip_grad_norm_(parameters=network.parameters(), max_norm=1.0, norm_type=2) optimizer.step() # Compute performance measures of current model. accuracy = (out.sigmoid().round() == target).to(dtype=torch.float32).mean() accuracies.append(accuracy.detach().item()) losses.append(loss.detach().item()) # Report progress of training procedure. return sum(losses) / len(losses), sum(accuracies) / len(accuracies) def eval_iter(network: Module, data_loader: DataLoader, device ) -> Tuple[float, float, float]: """ Evaluate the current model. :param network: network instance to evaluate :param data_loader: data loader instance providing validation data :return: tuple comprising validation loss, validation error as well as accuracy """ network.eval() # p_bar = tqdm(data_loader, total=len(data_loader)) with torch.no_grad(): losses, errors, accuracies, rocs, probs, labels = [], [], [], [], [], [] for data, target, mask in data_loader: data, target, mask = data.to(device=device), target.to(device=device).float(), mask.to(device) # Process data by Hopfield-based network out = network(data, mask=mask) loss = F.binary_cross_entropy_with_logits(input=out, target=target, reduction=r'mean') # Compute performance measures of current model. probs = probs + (torch.sigmoid(out).squeeze(-1).tolist()) labels = labels + (target.squeeze(-1).tolist()) accuracy = (out.sigmoid().round() == target).to(dtype=torch.float32).mean() accuracies.append(accuracy.detach().item()) roc = roc_auc_score(target.squeeze().detach().cpu(), out.sigmoid().squeeze().detach().cpu()) rocs.append(roc) losses.append(loss.detach().item()) return sum(losses) / len(losses), sum(accuracies) / len(accuracies), sum(rocs)/len(rocs) def train(config, args, train_features, train_labels, testset): device = "cpu" if torch.cuda.is_available(): device = "cuda:0" skf_inner = StratifiedKFold(n_splits=5, random_state=args.rs, shuffle=True) train_subset_ids, val_subset_ids = next(skf_inner.split(train_features, train_labels)) train_subset_features, train_subset_labels = [train_features[id] for id in train_subset_ids] \ , [train_labels[id] for id in train_subset_ids] val_subset_features, val_subset_labels = [train_features[id] for id in val_subset_ids] \ , [train_labels[id] for id in val_subset_ids] train_subset, val_subset = DummyDataset(train_subset_features, train_subset_labels, args.max_len) \ , DummyDataset(val_subset_features, val_subset_labels, args.max_len) trainloader = torch.utils.data.DataLoader( train_subset, batch_size=int(config["batch_size"]), shuffle=True, num_workers=8, collate_fn=testset.collate ) valloader = torch.utils.data.DataLoader( val_subset, batch_size=len(val_subset), shuffle=True, num_workers=8, collate_fn=testset.collate ) testloader = torch.utils.data.DataLoader( testset, batch_size=len(testset), shuffle=False, num_workers=8, collate_fn=testset.collate ) # scaling_max = 1.0 # annealing_factor = math.pow(scaling_max/config["scaling_factor"], 1/10) net = HopfieldMIL(config, feat_dim=args.feat_dim, mode=args.mode, max_len=args.max_len) net.to(device) optimizer = torch.optim.AdamW(params=net.parameters(), lr=config['lr'], weight_decay=1e-4) early_stopper = EarlyStopper() best_auc = 0.0 for epoch in range(50): # loop over the dataset multiple times epoch_steps = 0 _ = train_epoch(net, optimizer, trainloader, device) # if net.mode == "sparse" and epoch%5==0: # net.hopfield_pooling.hopfield.set_scaling(net.hopfield_pooling.hopfield.scaling * annealing_factor) epoch_steps += 1 for g in optimizer.param_groups: g['lr'] *= config["lr_decay"] val_loss, val_acc, val_auc = eval_iter(net, valloader, device) if best_auc<val_auc: test_loss, test_acc, test_auc = eval_iter(net, testloader, device) if early_stopper.early_stop(val_auc): break session.report({"auc": early_stopper.max_validation_loss, "test_auc": test_auc}) def main(args, cpus_per_trial, gpus_per_trial, num_samples=1):
def get_args(): parser = argparse.ArgumentParser(description='Examples of MIL benchmarks:') parser.add_argument('--dataset', default='fox', type=str, choices=['fox', 'tiger', 'elephant','ucsb']) parser.add_argument('--mode', default='standard', type=str, choices=['standard', 'sparse']) parser.add_argument('--rs', help='random state', default=1111, type=int) parser.add_argument('--multiply', help='multiply features to get more columns', default=False, type=bool) parser.add_argument('--cpus_per_trial', default=4, type=int) parser.add_argument('--gpus_per_trial', default=0.0, type=float) parser.add_argument('--gpus_id', default="0", type=str) args = parser.parse_args() return args class EarlyStopper: def __init__(self, patience=5, min_delta=0.03): self.patience = patience self.min_delta = min_delta self.counter = 0 self.max_validation_auc = 0 def early_stop(self, validation_auc): if validation_auc > self.max_validation_auc: self.max_validation_loss = validation_auc self.counter = 0 elif validation_auc < (self.max_validation_loss - self.min_delta): self.counter += 1 if self.counter >= self.patience: return True return False class HopfieldMIL(nn.Module): def __init__(self, config, feat_dim, max_len, mode = 'standard'): super(HopfieldMIL, self).__init__() emb = [nn.Linear(feat_dim, config["emb_dims"]), nn.ReLU()] for i in range(config["emb_layers"] - 1): emb.append(nn.Linear(config["emb_dims"], config["emb_dims"])) emb.append(nn.ReLU()) self.emb = nn.ModuleList(emb) self.mode = mode if mode == 'standard': self.hopfield = Hopfield( d_model=config["emb_dims"], n_heads=config["num_heads"], d_keys = config["hid_dim"], d_values = config["hid_dim"], scale=config["scaling_factor"], dropout=config["dropout"], mode='softmax' ) elif mode == 'sparse': self.hopfield = Hopfield( d_model=config["emb_dims"], n_heads=config["num_heads"], d_keys = config["hid_dim"], d_values = config["hid_dim"], scale=config["scaling_factor"], dropout=config["dropout"], mode='sparsemax' ) self.classifier = nn.Sequential( nn.ReLU(), nn.Linear(config["emb_dims"], 1) ) self.max_len = max_len def forward(self, x, mask=None): H = x.float() for l in self.emb: H = l(H) H = self.hopfield(H, stored_pattern_padding_mask=mask) Y_prob = self.classifier(H).flatten() return Y_prob def train_epoch(network: Module, optimizer: torch.optim.AdamW, data_loader: DataLoader, device ) -> Tuple[float, float, float]: """ Execute one training epoch. :param network: network instance to train :param optimiser: optimiser instance responsible for updating network parameters :param data_loader: data loader instance providing training data :return: tuple comprising training loss, training error as well as accuracy """ network.train() losses, errors, accuracies, rocs = [], [], [], [] for data, target, mask in data_loader: data, target, mask = data.to(device=device), target.to(device=device).float(), mask.to(device) # Process data by Hopfield-based network. out = network(data, mask=mask) optimizer.zero_grad() loss = F.binary_cross_entropy_with_logits(input=out, target=target, reduction=r'mean') # Update network parameters. loss.backward() torch.nn.utils.clip_grad_norm_(parameters=network.parameters(), max_norm=1.0, norm_type=2) optimizer.step() # Compute performance measures of current model. accuracy = (out.sigmoid().round() == target).to(dtype=torch.float32).mean() accuracies.append(accuracy.detach().item()) losses.append(loss.detach().item()) # Report progress of training procedure. return sum(losses) / len(losses), sum(accuracies) / len(accuracies) def eval_iter(network: Module, data_loader: DataLoader, device ) -> Tuple[float, float, float]: """ Evaluate the current model. :param network: network instance to evaluate :param data_loader: data loader instance providing validation data :return: tuple comprising validation loss, validation error as well as accuracy """ network.eval() # p_bar = tqdm(data_loader, total=len(data_loader)) with torch.no_grad(): losses, errors, accuracies, rocs, probs, labels = [], [], [], [], [], [] for data, target, mask in data_loader: data, target, mask = data.to(device=device), target.to(device=device).float(), mask.to(device) # Process data by Hopfield-based network out = network(data, mask=mask) loss = F.binary_cross_entropy_with_logits(input=out, target=target, reduction=r'mean') # Compute performance measures of current model. probs = probs + (torch.sigmoid(out).squeeze(-1).tolist()) labels = labels + (target.squeeze(-1).tolist()) accuracy = (out.sigmoid().round() == target).to(dtype=torch.float32).mean() accuracies.append(accuracy.detach().item()) roc = roc_auc_score(target.squeeze().detach().cpu(), out.sigmoid().squeeze().detach().cpu()) rocs.append(roc) losses.append(loss.detach().item()) return sum(losses) / len(losses), sum(accuracies) / len(accuracies), sum(rocs)/len(rocs) def train(config, args, train_features, train_labels, testset): device = "cpu" if torch.cuda.is_available(): device = "cuda:0" skf_inner = StratifiedKFold(n_splits=5, random_state=args.rs, shuffle=True) train_subset_ids, val_subset_ids = next(skf_inner.split(train_features, train_labels)) train_subset_features, train_subset_labels = [train_features[id] for id in train_subset_ids] \ , [train_labels[id] for id in train_subset_ids] val_subset_features, val_subset_labels = [train_features[id] for id in val_subset_ids] \ , [train_labels[id] for id in val_subset_ids] train_subset, val_subset = DummyDataset(train_subset_features, train_subset_labels, args.max_len) \ , DummyDataset(val_subset_features, val_subset_labels, args.max_len) trainloader = torch.utils.data.DataLoader( train_subset, batch_size=int(config["batch_size"]), shuffle=True, num_workers=8, collate_fn=testset.collate ) valloader = torch.utils.data.DataLoader( val_subset, batch_size=len(val_subset), shuffle=True, num_workers=8, collate_fn=testset.collate ) testloader = torch.utils.data.DataLoader( testset, batch_size=len(testset), shuffle=False, num_workers=8, collate_fn=testset.collate ) # scaling_max = 1.0 # annealing_factor = math.pow(scaling_max/config["scaling_factor"], 1/10) net = HopfieldMIL(config, feat_dim=args.feat_dim, mode=args.mode, max_len=args.max_len) net.to(device) optimizer = torch.optim.AdamW(params=net.parameters(), lr=config['lr'], weight_decay=1e-4) early_stopper = EarlyStopper() best_auc = 0.0 for epoch in range(50): # loop over the dataset multiple times epoch_steps = 0 _ = train_epoch(net, optimizer, trainloader, device) # if net.mode == "sparse" and epoch%5==0: # net.hopfield_pooling.hopfield.set_scaling(net.hopfield_pooling.hopfield.scaling * annealing_factor) epoch_steps += 1 for g in optimizer.param_groups: g['lr'] *= config["lr_decay"] val_loss, val_acc, val_auc = eval_iter(net, valloader, device) if best_auc<val_auc: test_loss, test_acc, test_auc = eval_iter(net, testloader, device) if early_stopper.early_stop(val_auc): break session.report({"auc": early_stopper.max_validation_loss, "test_auc": test_auc}) def main(args, cpus_per_trial, gpus_per_trial, num_samples=1):
features, labels = load_data(args) if args.dataset!="ucsb" else load_ucsb()
0
2023-11-12 06:36:52+00:00
4k
Kuba314/arcparse
arcparse/parser.py
[ { "identifier": "itemwise", "path": "arcparse/converters.py", "snippet": "class itemwise[T]:\n \"\"\"Mark converter as itemwise\n\n This changes its return-type signature to wrap T in list. This is used in\n argument converter declaration. Argument converters returning T make the\n argument ...
from collections.abc import Iterator, Sequence from dataclasses import dataclass, field from types import NoneType, UnionType from typing import Any, Union, get_args, get_origin from arcparse.converters import itemwise from ._partial_arguments import ( BasePartialArgument, PartialFlag, PartialMxGroup, PartialOption, PartialSubparsers, PartialTriFlag, ) from ._typehints import extract_optional_type, extract_subparsers_from_typehint from .arguments import ( BaseArgument, BaseValueArgument, MxGroup, Subparsers, TriFlag, void, ) from .errors import InvalidArgument, InvalidParser, InvalidTypehint import argparse import inspect
2,192
__all__ = ["Parser", "RootParser"] @dataclass class Parser[T]: shape: type[T] arguments: dict[str, BaseArgument] = field(default_factory=dict) mx_groups: list[MxGroup] = field(default_factory=list) @property def all_arguments(self) -> Iterator[tuple[str, BaseArgument]]: yield from self.arguments.items() for mx_group in self.mx_groups: yield from mx_group.arguments.items() def apply(self, actions_container: argparse._ActionsContainer) -> None: for name, argument in self.arguments.items(): argument.apply(actions_container, name) for mx_group in self.mx_groups: group = actions_container.add_mutually_exclusive_group(required=mx_group.required) for name, argument in mx_group.arguments.items(): argument.apply(group, name) @dataclass class RootParser[T]: parser: Parser[T] subparsers: tuple[str, Subparsers] | None = None @property def shape(self) -> type[T]: return self.parser.shape @property def all_arguments(self) -> Iterator[tuple[str, BaseArgument]]: yield from self.parser.all_arguments if self.subparsers is not None: for subparser in self.subparsers[1].sub_parsers.values(): yield from subparser.all_arguments def parse(self, args: Sequence[str] | None = None) -> T: ap_parser = argparse.ArgumentParser() self.parser.apply(ap_parser) if self.subparsers is not None: name, subparsers = self.subparsers ap_subparsers = ap_parser.add_subparsers(dest=name, required=subparsers.required) for name, subparser in subparsers.sub_parsers.items(): ap_subparser = ap_subparsers.add_parser(name) subparser.apply(ap_subparser) parsed = ap_parser.parse_args(args) ret = parsed.__dict__ if self.subparsers is not None: name, subparsers = self.subparsers # optional subparsers will result in `dict[name]` being `None` if chosen_subparser := getattr(parsed, name, None): sub_parser = subparsers.sub_parsers[chosen_subparser] ret[name] = _construct_object_with_parsed(sub_parser, ret) return _construct_object_with_parsed(self.parser, ret) def _construct_object_with_parsed[T](parser: Parser[T], parsed: dict[str, Any]) -> T: # apply argument converters for name, argument in parser.all_arguments:
__all__ = ["Parser", "RootParser"] @dataclass class Parser[T]: shape: type[T] arguments: dict[str, BaseArgument] = field(default_factory=dict) mx_groups: list[MxGroup] = field(default_factory=list) @property def all_arguments(self) -> Iterator[tuple[str, BaseArgument]]: yield from self.arguments.items() for mx_group in self.mx_groups: yield from mx_group.arguments.items() def apply(self, actions_container: argparse._ActionsContainer) -> None: for name, argument in self.arguments.items(): argument.apply(actions_container, name) for mx_group in self.mx_groups: group = actions_container.add_mutually_exclusive_group(required=mx_group.required) for name, argument in mx_group.arguments.items(): argument.apply(group, name) @dataclass class RootParser[T]: parser: Parser[T] subparsers: tuple[str, Subparsers] | None = None @property def shape(self) -> type[T]: return self.parser.shape @property def all_arguments(self) -> Iterator[tuple[str, BaseArgument]]: yield from self.parser.all_arguments if self.subparsers is not None: for subparser in self.subparsers[1].sub_parsers.values(): yield from subparser.all_arguments def parse(self, args: Sequence[str] | None = None) -> T: ap_parser = argparse.ArgumentParser() self.parser.apply(ap_parser) if self.subparsers is not None: name, subparsers = self.subparsers ap_subparsers = ap_parser.add_subparsers(dest=name, required=subparsers.required) for name, subparser in subparsers.sub_parsers.items(): ap_subparser = ap_subparsers.add_parser(name) subparser.apply(ap_subparser) parsed = ap_parser.parse_args(args) ret = parsed.__dict__ if self.subparsers is not None: name, subparsers = self.subparsers # optional subparsers will result in `dict[name]` being `None` if chosen_subparser := getattr(parsed, name, None): sub_parser = subparsers.sub_parsers[chosen_subparser] ret[name] = _construct_object_with_parsed(sub_parser, ret) return _construct_object_with_parsed(self.parser, ret) def _construct_object_with_parsed[T](parser: Parser[T], parsed: dict[str, Any]) -> T: # apply argument converters for name, argument in parser.all_arguments:
if not isinstance(argument, BaseValueArgument) or argument.converter is None:
9
2023-11-15 08:58:37+00:00
4k
CharlesTheGreat77/YardstickOneGUI
yardstick-gui.py
[ { "identifier": "yardstick_rx", "path": "utility/subghz.py", "snippet": "class yardstick_rx:\n def __init__(self, callback):\n self.signals = []\n self.stop_event = threading.Event()\n self.callback = callback\n\n def capture_signals(self, d):\n print(\"[*] Live Packet ...
import tkinter as tk import customtkinter, threading from tkinter import filedialog from utility.subghz import yardstick_rx, transmit_signals, transmit_tesla, jammer, parse_import_file from utility.yardstick import configure_yardstick from rflib import *
2,841
customtkinter.set_appearance_mode("dark") customtkinter.set_default_color_theme("blue") class App(customtkinter.CTk): def __init__(self): super().__init__() self.d = RfCat() self.d.lowball(0) self.title('Yardstick One Playground') self.geometry('1080x460') self.grid_columnconfigure(1, weight=1) self.grid_columnconfigure((2, 3), weight=0) self.grid_columnconfigure((0, 2, 3), weight=1) self.scrollable_frame = customtkinter.CTkScrollableFrame(self, label_text="Options") self.scrollable_frame.grid(row=0, column=0, padx=(20, 0), pady=(20, 0), sticky="nsew") self.scrollable_frame.grid_columnconfigure(0, weight=1) # receive switch self.switch_receive = customtkinter.CTkSwitch(master=self.scrollable_frame, text=f"Receive", command=self.toggle_receive) self.switch_receive.grid(row=1, column=0, padx=10, pady=(0, 20)) # transmit switch self.switch_transmit = customtkinter.CTkSwitch(master=self.scrollable_frame, text="Transmit", command=self.toggle_transmit) self.switch_transmit.grid(row=2, column=0, padx=10, pady=(0, 20)) # tesla charging port switch self.tesla_transmit = customtkinter.CTkSwitch(master=self.scrollable_frame, text="Tesla Port", command=self.toggle_tesla) self.tesla_transmit.grid(row=3, column=0, padx=10, pady=(0, 20)) self.switch_jammer = customtkinter.CTkSwitch(master=self.scrollable_frame, text="Jam", command=self.toggle_jammer) self.switch_jammer.grid(row=4, column=0, padx=10, pady=(0, 20)) # spectrum analyzer self.button_spectrum_analyzer = customtkinter.CTkButton(master=self.scrollable_frame, text="Spectrum Analyzer [buggy]", command=self.spectrum_analyzer) self.button_spectrum_analyzer.grid(row=5, column=0, padx=20, pady=10) # reset button # self.button_reset = customtkinter.CTkButton(master=self.scrollable_frame, text="Spectrum Analyzer", command=self.reset_yardstick(d)) # self.button_reset.grid(row=6, column=0, padx=20, pady=10) # create tabview self.tabview = customtkinter.CTkTabview(self, width=250) self.tabview.grid(row=0, column=2, padx=(20, 0), pady=(20, 0), sticky="nsew") self.tabview.add("Configure") self.tabview.tab("Configure").grid_columnconfigure(0, weight=1) # Add the "Advanced" tab self.tabview.add("Advanced") self.tabview.tab("Advanced").grid_columnconfigure(0, weight=1) self.frequencies = ["300Mhz", "315Mhz", "390Mhz", "433.92Mhz", "Custom"] self.selected_frequency = tk.StringVar() self.optionmenu_1 = customtkinter.CTkOptionMenu(self.tabview.tab("Configure"), values=self.frequencies, command=self.frequency_option_selected) self.optionmenu_1.grid(row=0, column=0, padx=20, pady=(20, 10)) # create textbox for custom frequency self.custom_frequency_entry = customtkinter.CTkEntry(self.tabview.tab("Configure"), placeholder_text="Custom Frequency") self.custom_frequency_entry.grid(row=1, column=0, padx=20, pady=(10, 10)) self.custom_frequency_entry.configure(state="disabled") # Initially disable the textbox # dropdown box for modulation selection self.selected_modulation = tk.StringVar() self.optionmenu_2 = customtkinter.CTkOptionMenu(self.tabview.tab("Configure"), values=['AM270', 'AM650', 'FM238', 'FM476'], command=self.modulation_option_selection) self.optionmenu_2.grid(row=2, column=0, padx=20, pady=(20, 10)) # Configure button self.button_configure = customtkinter.CTkButton(self.tabview.tab("Configure"), text="configure", command=self.configure_stick) self.button_configure.grid(row=3, column=0, padx=20, pady=10) # signals text box self.textbox = customtkinter.CTkTextbox(self, width=512) self.textbox.grid(row=0, column=1, padx=(20, 0), pady=(20, 0), sticky="nsew") # Scrollable frame for the "Advanced" tab self.advanced_scrollable_frame = customtkinter.CTkScrollableFrame(self.tabview.tab("Advanced")) self.advanced_scrollable_frame.grid(row=0, column=0, padx=20, pady=(20, 0), sticky="nsew") self.advanced_scrollable_frame.grid_columnconfigure(0, weight=1) # Labels and textboxes for user input in the "Advanced" tab self.entry_baudrate = customtkinter.CTkEntry(self.advanced_scrollable_frame, placeholder_text="Custom Baudrate") self.entry_baudrate.grid(row=0, column=0, padx=20, pady=(10, 10)) self.entry_deviation = customtkinter.CTkEntry(self.advanced_scrollable_frame, placeholder_text="Custom Deviation") self.entry_deviation.grid(row=1, column=0, padx=20, pady=(10, 10)) self.label_amp = customtkinter.CTkLabel(self.advanced_scrollable_frame, text="Enable amp") self.label_amp.grid(row=2, column=0, padx=20, pady=(20, 0), sticky='w') self.entry_amp = customtkinter.CTkOptionMenu(self.advanced_scrollable_frame, values=['True', 'False']) self.entry_amp.grid(row=3, column=0, padx=20, pady=(0, 10)) # terminal entry box self.entry = customtkinter.CTkEntry(self, placeholder_text="Manually Configure/Utilize Yardstick One") self.entry.grid(row=2, column=1, columnspan=1, padx=(20, 0), pady=(20, 20), sticky="nsew") self.button_save_file = customtkinter.CTkButton(master=self, text='Save Capture', border_width=2, command=self.save_capture_to_file) self.button_save_file.grid(row=2, column=2, padx=(20, 0), pady=(20, 20), sticky="nsew") # import file self.button_import_file = customtkinter.CTkButton(master=self, text='Import Cap File', fg_color="transparent", border_width=2, text_color=("gray10", "#DCE4EE"), command=self.import_file) self.button_import_file.grid(row=2, column=0, padx=(20, 0), pady=(20, 20), sticky="nsew") # progress bar self.slider_progressbar_frame = customtkinter.CTkFrame(self, fg_color="transparent") self.slider_progressbar_frame.grid(row=1, column=1, padx=(20, 0), pady=(20, 0), sticky="nsew") self.slider_progressbar_frame.grid_columnconfigure(0, weight=1) self.slider_progressbar_frame.grid_rowconfigure(4, weight=1) self.progressbar_1 = customtkinter.CTkProgressBar(self.slider_progressbar_frame) self.progressbar_1.grid(row=1, column=0, padx=(20, 10), pady=(10, 10), sticky="ew") self.yardstick_receiver = yardstick_rx(self.textbox.insert) def configure_stick(self): amp = self.entry_amp.get() baudrate = int(self.entry_baudrate.get()) if self.entry_baudrate.get() else 0 deviation = int(self.entry_deviation.get()) if self.entry_deviation.get() else 0 print(f'Freq: {self.frequency}, Mod: {self.modulation}, Baud: {baudrate}, Dev: {deviation}, Amp: {amp}')
customtkinter.set_appearance_mode("dark") customtkinter.set_default_color_theme("blue") class App(customtkinter.CTk): def __init__(self): super().__init__() self.d = RfCat() self.d.lowball(0) self.title('Yardstick One Playground') self.geometry('1080x460') self.grid_columnconfigure(1, weight=1) self.grid_columnconfigure((2, 3), weight=0) self.grid_columnconfigure((0, 2, 3), weight=1) self.scrollable_frame = customtkinter.CTkScrollableFrame(self, label_text="Options") self.scrollable_frame.grid(row=0, column=0, padx=(20, 0), pady=(20, 0), sticky="nsew") self.scrollable_frame.grid_columnconfigure(0, weight=1) # receive switch self.switch_receive = customtkinter.CTkSwitch(master=self.scrollable_frame, text=f"Receive", command=self.toggle_receive) self.switch_receive.grid(row=1, column=0, padx=10, pady=(0, 20)) # transmit switch self.switch_transmit = customtkinter.CTkSwitch(master=self.scrollable_frame, text="Transmit", command=self.toggle_transmit) self.switch_transmit.grid(row=2, column=0, padx=10, pady=(0, 20)) # tesla charging port switch self.tesla_transmit = customtkinter.CTkSwitch(master=self.scrollable_frame, text="Tesla Port", command=self.toggle_tesla) self.tesla_transmit.grid(row=3, column=0, padx=10, pady=(0, 20)) self.switch_jammer = customtkinter.CTkSwitch(master=self.scrollable_frame, text="Jam", command=self.toggle_jammer) self.switch_jammer.grid(row=4, column=0, padx=10, pady=(0, 20)) # spectrum analyzer self.button_spectrum_analyzer = customtkinter.CTkButton(master=self.scrollable_frame, text="Spectrum Analyzer [buggy]", command=self.spectrum_analyzer) self.button_spectrum_analyzer.grid(row=5, column=0, padx=20, pady=10) # reset button # self.button_reset = customtkinter.CTkButton(master=self.scrollable_frame, text="Spectrum Analyzer", command=self.reset_yardstick(d)) # self.button_reset.grid(row=6, column=0, padx=20, pady=10) # create tabview self.tabview = customtkinter.CTkTabview(self, width=250) self.tabview.grid(row=0, column=2, padx=(20, 0), pady=(20, 0), sticky="nsew") self.tabview.add("Configure") self.tabview.tab("Configure").grid_columnconfigure(0, weight=1) # Add the "Advanced" tab self.tabview.add("Advanced") self.tabview.tab("Advanced").grid_columnconfigure(0, weight=1) self.frequencies = ["300Mhz", "315Mhz", "390Mhz", "433.92Mhz", "Custom"] self.selected_frequency = tk.StringVar() self.optionmenu_1 = customtkinter.CTkOptionMenu(self.tabview.tab("Configure"), values=self.frequencies, command=self.frequency_option_selected) self.optionmenu_1.grid(row=0, column=0, padx=20, pady=(20, 10)) # create textbox for custom frequency self.custom_frequency_entry = customtkinter.CTkEntry(self.tabview.tab("Configure"), placeholder_text="Custom Frequency") self.custom_frequency_entry.grid(row=1, column=0, padx=20, pady=(10, 10)) self.custom_frequency_entry.configure(state="disabled") # Initially disable the textbox # dropdown box for modulation selection self.selected_modulation = tk.StringVar() self.optionmenu_2 = customtkinter.CTkOptionMenu(self.tabview.tab("Configure"), values=['AM270', 'AM650', 'FM238', 'FM476'], command=self.modulation_option_selection) self.optionmenu_2.grid(row=2, column=0, padx=20, pady=(20, 10)) # Configure button self.button_configure = customtkinter.CTkButton(self.tabview.tab("Configure"), text="configure", command=self.configure_stick) self.button_configure.grid(row=3, column=0, padx=20, pady=10) # signals text box self.textbox = customtkinter.CTkTextbox(self, width=512) self.textbox.grid(row=0, column=1, padx=(20, 0), pady=(20, 0), sticky="nsew") # Scrollable frame for the "Advanced" tab self.advanced_scrollable_frame = customtkinter.CTkScrollableFrame(self.tabview.tab("Advanced")) self.advanced_scrollable_frame.grid(row=0, column=0, padx=20, pady=(20, 0), sticky="nsew") self.advanced_scrollable_frame.grid_columnconfigure(0, weight=1) # Labels and textboxes for user input in the "Advanced" tab self.entry_baudrate = customtkinter.CTkEntry(self.advanced_scrollable_frame, placeholder_text="Custom Baudrate") self.entry_baudrate.grid(row=0, column=0, padx=20, pady=(10, 10)) self.entry_deviation = customtkinter.CTkEntry(self.advanced_scrollable_frame, placeholder_text="Custom Deviation") self.entry_deviation.grid(row=1, column=0, padx=20, pady=(10, 10)) self.label_amp = customtkinter.CTkLabel(self.advanced_scrollable_frame, text="Enable amp") self.label_amp.grid(row=2, column=0, padx=20, pady=(20, 0), sticky='w') self.entry_amp = customtkinter.CTkOptionMenu(self.advanced_scrollable_frame, values=['True', 'False']) self.entry_amp.grid(row=3, column=0, padx=20, pady=(0, 10)) # terminal entry box self.entry = customtkinter.CTkEntry(self, placeholder_text="Manually Configure/Utilize Yardstick One") self.entry.grid(row=2, column=1, columnspan=1, padx=(20, 0), pady=(20, 20), sticky="nsew") self.button_save_file = customtkinter.CTkButton(master=self, text='Save Capture', border_width=2, command=self.save_capture_to_file) self.button_save_file.grid(row=2, column=2, padx=(20, 0), pady=(20, 20), sticky="nsew") # import file self.button_import_file = customtkinter.CTkButton(master=self, text='Import Cap File', fg_color="transparent", border_width=2, text_color=("gray10", "#DCE4EE"), command=self.import_file) self.button_import_file.grid(row=2, column=0, padx=(20, 0), pady=(20, 20), sticky="nsew") # progress bar self.slider_progressbar_frame = customtkinter.CTkFrame(self, fg_color="transparent") self.slider_progressbar_frame.grid(row=1, column=1, padx=(20, 0), pady=(20, 0), sticky="nsew") self.slider_progressbar_frame.grid_columnconfigure(0, weight=1) self.slider_progressbar_frame.grid_rowconfigure(4, weight=1) self.progressbar_1 = customtkinter.CTkProgressBar(self.slider_progressbar_frame) self.progressbar_1.grid(row=1, column=0, padx=(20, 10), pady=(10, 10), sticky="ew") self.yardstick_receiver = yardstick_rx(self.textbox.insert) def configure_stick(self): amp = self.entry_amp.get() baudrate = int(self.entry_baudrate.get()) if self.entry_baudrate.get() else 0 deviation = int(self.entry_deviation.get()) if self.entry_deviation.get() else 0 print(f'Freq: {self.frequency}, Mod: {self.modulation}, Baud: {baudrate}, Dev: {deviation}, Amp: {amp}')
configure_yardstick(self.d, int(self.frequency), self.modulation, int(baudrate), int(deviation), amp)
5
2023-11-14 04:32:40+00:00
4k
rohitsinghlab/sceodesic
sceodesic/sceo_main/run_sceo.py
[ { "identifier": "get_cell_cohorts", "path": "sceodesic/sceo_main/get_cell_cohorts.py", "snippet": "@fn_timer\ndef get_cell_cohorts(adata, num_cohorts, stratify_cols='none', num_hvg=None, \n copy=False, return_results=False, n_init=1, \n uns_key=None):\n \n r...
import sys import scanpy as sc import numpy as np import pandas as pd from .get_cell_cohorts import get_cell_cohorts from .get_locally_variable_genes import get_locally_variable_genes from .estimate_covariances import estimate_covariances from .reconstruct_programs import reconstruct_programs from .default_keys import UNS_KEY from .default_keys import SCEO_CONFIG_KEY from .default_keys import * from ..utils import fn_timer from ..utils import order_by_second_moment
3,307
:param pvd_pct: Take eigenvectors 1,...,k, where k is the minimum integer for which sum(lambda_1,...,lambda_k) >= pvd_pct :type pvd_pct: float in (0, 1) :param do_global_hvg: If True, do a global hvg estimation from the entire gene expression matrix rather than getting locally variable genes per cohort. :type do_global_hvg: boolean :param cohort_assn: Optionally, one can specify the cohort assignment rather than have them computed. If not specified, the cohort assignments will be computed according to the parameters num_cohorts, stratify_cols, num_hvg. :type cohort_assn: np.array[str] of length n_cells :param top_genes: If specified, use these genes as the gene set for estimating covariances and computing sceodesic programs. If not specified, will be computed according to the parameters num_hvg, num_hvg_per_cohort, and do_global_hvg. :type top_genes: list[str] :param copy: Return a copy of anndata if True :type copy: boolean :param n_init: Number of initializations for k-means clustering :type n_init: int > 0 :param key_added: If specified, sceodesic embeddings stored in adata.obsm[key_added], and sceodesic programs are stored in adata.varm[key_added]. Otherwise, (by default) sceodesic embeddings are stored in adata.obsm['sceo_embeddings'] and sceodesic programs are stored in adata.varm['sceo_programs']. :type key_added: str :param uns_key: Where to store the sceodesic gene programs, parameter information, and metadata. :type uns_key: str :returns: a copy of adata if copy=True, else modifies adata in place and returns None. """ if key_added is None: obsm_key_added = SCEO_EMBEDDINGS_KEY varm_key_added = MODULES_KEY else: obsm_key_added = key_added varm_key_added = key_added if uns_key is None: uns_key = UNS_KEY if copy: adata = adata.copy() adata.uns[uns_key] = {} # can give cohort_assn or top_genes optionally if cohort_assn is not None and top_genes is None: num_cohorts = len(np.unique(cohort_assn)) stratify_cols = '***NOT SPECIFIED***' get_locally_variable_genes(adata, num_hvg, num_hvg_per_cohort, do_global_hvg, cohort_assn=cohort_assn, uns_key=uns_key) estimate_covariances(adata, max_condition_number, pvd_pct, uns_key=uns_key) elif cohort_assn is None and top_genes is not None: num_hvg = len(top_genes) get_cell_cohorts(adata, num_cohorts, stratify_cols, num_hvg, n_init=n_init, uns_key=uns_key) estimate_covariances(adata, max_condition_number, pvd_pct, top_genes=top_genes, uns_key=uns_key) elif cohort_assn is not None and top_genes is not None: num_cohorts = len(np.unique(cohort_assn)) stratify_cols = '***NOT SPECIFIED***' num_hvg = len(top_genes) estimate_covariances(adata, max_condition_number, pvd_pct, top_genes=top_genes, cohort_assn=cohort_assn, uns_key=uns_key) else: try: assert num_hvg > 0 except Exception as e: message = ("Error: you must either specify the number of variable genes to select" " or input your own list of genes of interest.") print(message, file=sys.stderr) raise e get_cell_cohorts(adata, num_cohorts, stratify_cols, num_hvg, n_init=n_init, uns_key=uns_key) get_locally_variable_genes(adata, num_hvg, num_hvg_per_cohort, do_global_hvg, uns_key=uns_key) estimate_covariances(adata, max_condition_number, pvd_pct, uns_key=uns_key) # will do the same thing here no matter which of cohort_assn/top_genes is pre-specified reconstruct_programs(adata, sparse_pca_lambda, uns_key=uns_key) # these are hard-coded for now (fix later) cluster_key = CLUSTER_KEY embeddings_dict_key = EMBEDDINGS_DICT_KEY modules_key = MODULES_KEY hvg_key = HVG_KEY cell2cluster = adata.uns[uns_key][cluster_key] embeddings = adata.uns[uns_key][embeddings_dict_key] modules = adata.uns[uns_key][modules_key] top_genes = adata.uns[uns_key][hvg_key] # making the .obsm object observation_count = adata.n_obs data_embedding = np.zeros((observation_count, num_hvg)) for i, embed in embeddings.items(): cluster_indices = cell2cluster[i] for cell in cluster_indices: data_embedding[cell, :] = embed
@fn_timer def run_sceo(adata, num_hvg=-1, num_cohorts='auto', sparse_pca_lambda=0.03, max_condition_number=50, stratify_cols='none', num_hvg_per_cohort=100, pvd_pct=0.9, do_global_hvg=False, cohort_assn=None, top_genes=None, copy=False, n_init=1, key_added=None, uns_key=None): """ Computes sceodesic embeddings and saves them in adata.obsm[key_added], sceodesic programs are stored in adata.obsm[key_added], and sceodesic programs and metadata stored in adata.uns[uns_key]. Note that programs are also stored in adata.uns[uns_key]['sceo_programs']. :param adata: An adata file with log-normalized gene expression data in adata.X. :type adata: anndata.AnnData :param num_hvg: The final number of locally variable genes to select out of the union of locally variable genes across all cohorts. Must be specified unless top_genes is specified. :type num_hvg: int > 0 :param num_cohorts: The number of cell cohorts to create. Must be at least 10. :type num_cohorts: int > 10 :param sparse_pca_lambda: Sparsity parameter for sparse pca during module reconstruction. :type sparse_pca_lambda: float >= 0 :param max_condition_number: The maximum condition number of each estimated cohort-specific covariance matrix. :type max_condition_number: float > 0 :param stratify_cols: Columns of adata.obs by which to stratify observations when constructing cell cohorts. If none, no stratification is performed. :type stratify_cols: string or list of strings :param num_hvg_per_cohort: Number of locally variable genes to estimate per cohort :type num_hvg_per_cohort: int > 0 :param pvd_pct: Take eigenvectors 1,...,k, where k is the minimum integer for which sum(lambda_1,...,lambda_k) >= pvd_pct :type pvd_pct: float in (0, 1) :param do_global_hvg: If True, do a global hvg estimation from the entire gene expression matrix rather than getting locally variable genes per cohort. :type do_global_hvg: boolean :param cohort_assn: Optionally, one can specify the cohort assignment rather than have them computed. If not specified, the cohort assignments will be computed according to the parameters num_cohorts, stratify_cols, num_hvg. :type cohort_assn: np.array[str] of length n_cells :param top_genes: If specified, use these genes as the gene set for estimating covariances and computing sceodesic programs. If not specified, will be computed according to the parameters num_hvg, num_hvg_per_cohort, and do_global_hvg. :type top_genes: list[str] :param copy: Return a copy of anndata if True :type copy: boolean :param n_init: Number of initializations for k-means clustering :type n_init: int > 0 :param key_added: If specified, sceodesic embeddings stored in adata.obsm[key_added], and sceodesic programs are stored in adata.varm[key_added]. Otherwise, (by default) sceodesic embeddings are stored in adata.obsm['sceo_embeddings'] and sceodesic programs are stored in adata.varm['sceo_programs']. :type key_added: str :param uns_key: Where to store the sceodesic gene programs, parameter information, and metadata. :type uns_key: str :returns: a copy of adata if copy=True, else modifies adata in place and returns None. """ if key_added is None: obsm_key_added = SCEO_EMBEDDINGS_KEY varm_key_added = MODULES_KEY else: obsm_key_added = key_added varm_key_added = key_added if uns_key is None: uns_key = UNS_KEY if copy: adata = adata.copy() adata.uns[uns_key] = {} # can give cohort_assn or top_genes optionally if cohort_assn is not None and top_genes is None: num_cohorts = len(np.unique(cohort_assn)) stratify_cols = '***NOT SPECIFIED***' get_locally_variable_genes(adata, num_hvg, num_hvg_per_cohort, do_global_hvg, cohort_assn=cohort_assn, uns_key=uns_key) estimate_covariances(adata, max_condition_number, pvd_pct, uns_key=uns_key) elif cohort_assn is None and top_genes is not None: num_hvg = len(top_genes) get_cell_cohorts(adata, num_cohorts, stratify_cols, num_hvg, n_init=n_init, uns_key=uns_key) estimate_covariances(adata, max_condition_number, pvd_pct, top_genes=top_genes, uns_key=uns_key) elif cohort_assn is not None and top_genes is not None: num_cohorts = len(np.unique(cohort_assn)) stratify_cols = '***NOT SPECIFIED***' num_hvg = len(top_genes) estimate_covariances(adata, max_condition_number, pvd_pct, top_genes=top_genes, cohort_assn=cohort_assn, uns_key=uns_key) else: try: assert num_hvg > 0 except Exception as e: message = ("Error: you must either specify the number of variable genes to select" " or input your own list of genes of interest.") print(message, file=sys.stderr) raise e get_cell_cohorts(adata, num_cohorts, stratify_cols, num_hvg, n_init=n_init, uns_key=uns_key) get_locally_variable_genes(adata, num_hvg, num_hvg_per_cohort, do_global_hvg, uns_key=uns_key) estimate_covariances(adata, max_condition_number, pvd_pct, uns_key=uns_key) # will do the same thing here no matter which of cohort_assn/top_genes is pre-specified reconstruct_programs(adata, sparse_pca_lambda, uns_key=uns_key) # these are hard-coded for now (fix later) cluster_key = CLUSTER_KEY embeddings_dict_key = EMBEDDINGS_DICT_KEY modules_key = MODULES_KEY hvg_key = HVG_KEY cell2cluster = adata.uns[uns_key][cluster_key] embeddings = adata.uns[uns_key][embeddings_dict_key] modules = adata.uns[uns_key][modules_key] top_genes = adata.uns[uns_key][hvg_key] # making the .obsm object observation_count = adata.n_obs data_embedding = np.zeros((observation_count, num_hvg)) for i, embed in embeddings.items(): cluster_indices = cell2cluster[i] for cell in cluster_indices: data_embedding[cell, :] = embed
data_embedding, modules = order_by_second_moment(data_embedding, modules)
7
2023-11-10 12:28:33+00:00
4k
fepegar/jvol
src/jvol/io.py
[ { "identifier": "decode_array", "path": "src/jvol/decoding.py", "snippet": "@timed() # pyright: ignore\ndef decode_array(\n dc_rle_values: npt.NDArray[np.int32],\n dc_rle_counts: npt.NDArray[np.uint32],\n ac_rle_values: npt.NDArray[np.int32],\n ac_rle_counts: npt.NDArray[np.uint32],\n qu...
import enum import itk import numpy as np import numpy.typing as npt from pathlib import Path from typing import Tuple from .decoding import decode_array from .encoding import encode_array from .encoding import get_quantization_table from .transforms import create_ijk_to_ras_from_itk_image from .transforms import get_itk_metadata_from_ijk_to_ras
1,663
class FormatKeys(str, enum.Enum): IJK_TO_RAS = "ijk_to_ras" QUANTIZATION_BLOCK = "quantization_block" DC_RLE_VALUES = "dc_rle_values" DC_RLE_COUNTS = "dc_rle_counts" AC_RLE_VALUES = "ac_rle_values" AC_RLE_COUNTS = "ac_rle_counts" DTYPE = "dtype" INTERCEPT = "intercept" SLOPE = "slope" SHAPE = "shape" def open_image(path: Path) -> Tuple[np.ndarray, np.ndarray]: _open = open_jvol if path.suffix == ".jvol" else open_itk_image return _open(path) def save_image( array: np.ndarray, ijk_to_ras: np.ndarray, path: Path, **kwargs: int, ) -> None: if path.suffix == ".jvol": save_jvol(array, ijk_to_ras, path, **kwargs) else: save_itk_image(array, ijk_to_ras, path) def open_itk_image(path: Path) -> Tuple[np.ndarray, np.ndarray]: image = itk.imread(path) array = itk.array_view_from_image(image).T
class FormatKeys(str, enum.Enum): IJK_TO_RAS = "ijk_to_ras" QUANTIZATION_BLOCK = "quantization_block" DC_RLE_VALUES = "dc_rle_values" DC_RLE_COUNTS = "dc_rle_counts" AC_RLE_VALUES = "ac_rle_values" AC_RLE_COUNTS = "ac_rle_counts" DTYPE = "dtype" INTERCEPT = "intercept" SLOPE = "slope" SHAPE = "shape" def open_image(path: Path) -> Tuple[np.ndarray, np.ndarray]: _open = open_jvol if path.suffix == ".jvol" else open_itk_image return _open(path) def save_image( array: np.ndarray, ijk_to_ras: np.ndarray, path: Path, **kwargs: int, ) -> None: if path.suffix == ".jvol": save_jvol(array, ijk_to_ras, path, **kwargs) else: save_itk_image(array, ijk_to_ras, path) def open_itk_image(path: Path) -> Tuple[np.ndarray, np.ndarray]: image = itk.imread(path) array = itk.array_view_from_image(image).T
ijk_to_ras = create_ijk_to_ras_from_itk_image(image)
3
2023-11-12 18:41:36+00:00
4k
iramluism/basel
tests/unit_tests/loaders/module_loader_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 ...
import os import pytest from pathlib import Path from unittest.mock import MagicMock from unittest.mock import Mock from basel.components import Component from basel.components.classes import ClassNode from basel.components.links import Link from basel.components.modules import ModuleNode from basel.loaders.modules import ModuleLoader from basel.parsers import Parser
2,578
STUB_PROJECT_1_PATH = Path("tests/stubs/project_1") @pytest.mark.parametrize( "paths,expected_components", [ ( [STUB_PROJECT_1_PATH], [ Component( name=str(STUB_PROJECT_1_PATH / "module_1.py"), nodes=[
STUB_PROJECT_1_PATH = Path("tests/stubs/project_1") @pytest.mark.parametrize( "paths,expected_components", [ ( [STUB_PROJECT_1_PATH], [ Component( name=str(STUB_PROJECT_1_PATH / "module_1.py"), nodes=[
ModuleNode(
3
2023-11-18 13:47:55+00:00
4k
giu-guarino/R-PNN
test.py
[ { "identifier": "R_PNN_model", "path": "network.py", "snippet": "class R_PNN_model(nn.Module):\n def __init__(self, padding='valid', scope=6, bias=True) -> None:\n super(R_PNN_model, self).__init__()\n self.conv1 = nn.Conv2d(2, 48, 7, padding=padding, bias=bias)\n self.conv2 = nn...
import argparse import gc import os import numpy as np import scipy.io as io import torch from torch import nn from tqdm import tqdm from network import R_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
2,596
def test_r_pnn(args): # Paths and env configuration basepath = args.input method = 'R-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'] # 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) ms_lr = normalize(ms_lr) ms = normalize(ms) pan = normalize(pan).to(device) net_scope = config['net_scope'] pad = nn.ReflectionPad2d(net_scope) # Torch configuration net = R_PNN_model() net.load_state_dict(torch.load(os.path.join('weights', 'R-PNN_' + sensor + '.tar'))) net = net.to(device) criterion_spec = SpectralLoss(gen_mtf(ratio, sensor, kernel_size=61, nbands=1), ratio, device).to(device) criterion_struct = StructuralLoss(ratio).to(device) optim = torch.optim.Adam(net.parameters(), lr=learning_rate) history_loss_spec = [] history_loss_struct = [] alpha = config['alpha_1'] fused = [] for band_number in range(ms.shape[1]): band = ms[:, band_number:band_number + 1, :, :].to(device) band_lr = ms_lr[:, band_number:band_number + 1, :, :].to(device) # Aux data generation inp = torch.cat([band, pan], dim=1) inp = pad(inp)
def test_r_pnn(args): # Paths and env configuration basepath = args.input method = 'R-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'] # 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) ms_lr = normalize(ms_lr) ms = normalize(ms) pan = normalize(pan).to(device) net_scope = config['net_scope'] pad = nn.ReflectionPad2d(net_scope) # Torch configuration net = R_PNN_model() net.load_state_dict(torch.load(os.path.join('weights', 'R-PNN_' + sensor + '.tar'))) net = net.to(device) criterion_spec = SpectralLoss(gen_mtf(ratio, sensor, kernel_size=61, nbands=1), ratio, device).to(device) criterion_struct = StructuralLoss(ratio).to(device) optim = torch.optim.Adam(net.parameters(), lr=learning_rate) history_loss_spec = [] history_loss_struct = [] alpha = config['alpha_1'] fused = [] for band_number in range(ms.shape[1]): band = ms[:, band_number:band_number + 1, :, :].to(device) band_lr = ms_lr[:, band_number:band_number + 1, :, :].to(device) # Aux data generation inp = torch.cat([band, pan], dim=1) inp = pad(inp)
threshold = local_corr_mask(inp, ratio, sensor, device, config['semi_width'])
8
2023-11-10 14:07:17+00:00
4k
Wolfsauge/async_summarize
main.py
[ { "identifier": "get_buck_slip_config", "path": "sync_helpers.py", "snippet": "def get_buck_slip_config(buck_slip_filename: str) -> dict:\n buck_slip = {\n \"httpx_max_connections\": 1,\n \"httpx_max_keepalive_connections\": 1,\n \"model_identifier\": \"empty\",\n \"api_ke...
import os import sys import argparse import asyncio from time import perf_counter from dataclasses import dataclass from icecream import ic # type: ignore from sync_helpers import ( get_buck_slip_config, get_prompt_template, get_tokenizer, get_api_client, get_jinja2_environment, get_file_contents, get_output_filename, insert_buckslip_into_result, write_output_file, ) from async_helpers import do_the_work
2,026
#!/usr/bin/env python3 # Dataclass for commandline arguments @dataclass class CommandlineArguments: config: str prompt: str mode: str file: str async def main(my_args: CommandlineArguments) -> None: time_t0: float time_t1: float time_delta: float summarize_duration: float result: dict # Check if all files given on the command line do exist # error out if not. # tbc. # Check if summarizing mode is understood. mode = my_args.mode while mode not in ["hm"]: ic("ERROR: mode {mode} not implemented.") sys.exit(1) # Initialize buck_slip dict config_filename = my_args.config buck_slip = get_buck_slip_config(config_filename) buck_slip["config_filename"] = config_filename # Get prompt_template prompt_template_filename = my_args.prompt buck_slip["prompt_templates"] = get_prompt_template(prompt_template_filename) buck_slip["prompt_template_filename"] = prompt_template_filename # Get tokenizer buck_slip["tokenizer"] = get_tokenizer(buck_slip) # Get OpenAI-compatible API buck_slip["api_client"] = get_api_client(buck_slip) # Get Jinja2 environment
#!/usr/bin/env python3 # Dataclass for commandline arguments @dataclass class CommandlineArguments: config: str prompt: str mode: str file: str async def main(my_args: CommandlineArguments) -> None: time_t0: float time_t1: float time_delta: float summarize_duration: float result: dict # Check if all files given on the command line do exist # error out if not. # tbc. # Check if summarizing mode is understood. mode = my_args.mode while mode not in ["hm"]: ic("ERROR: mode {mode} not implemented.") sys.exit(1) # Initialize buck_slip dict config_filename = my_args.config buck_slip = get_buck_slip_config(config_filename) buck_slip["config_filename"] = config_filename # Get prompt_template prompt_template_filename = my_args.prompt buck_slip["prompt_templates"] = get_prompt_template(prompt_template_filename) buck_slip["prompt_template_filename"] = prompt_template_filename # Get tokenizer buck_slip["tokenizer"] = get_tokenizer(buck_slip) # Get OpenAI-compatible API buck_slip["api_client"] = get_api_client(buck_slip) # Get Jinja2 environment
buck_slip["jinja2_env"] = get_jinja2_environment()
4
2023-11-16 01:51:17+00:00
4k
balazsborsos/dae_postprocessing
train.py
[ { "identifier": "DAE", "path": "models/DAE.py", "snippet": "class DAE(nn.Module):\n def __init__(\n self,\n spatial_dims: int = 2,\n in_channels: int = 1,\n out_channels: int = 1,\n strides: Sequence[int] = (2,),\n image_size: Sequence...
import torch import pytorch_lightning as pl from pathlib import Path from typing import Union from models.DAE import DAE from utils.loss import DiceLoss from utils.data import get_dataloader from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning.loggers import TensorBoardLogger
2,377
def get_model( *args, **kwargs ) -> Union[torch.nn.Module, pl.LightningModule]: return DenoiseModel(**kwargs)
def get_model( *args, **kwargs ) -> Union[torch.nn.Module, pl.LightningModule]: return DenoiseModel(**kwargs)
class DenoiseModel(DAE, pl.LightningModule):
0
2023-11-18 13:57:25+00:00
4k
htyao89/Textual-based_Class-aware_prompt_tuning
trainers/tcp.py
[ { "identifier": "clip", "path": "trainers/clip_text/clip.py", "snippet": " BICUBIC = InterpolationMode.BICUBIC\n BICUBIC = Image.BICUBIC\n_MODELS = {\n \"RN50\":\n \"https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt\",\n ...
import os.path as osp import torch import torch.nn as nn import scipy.io as sio import tqdm import numpy as np import copy import clip.clip as clip_ori from torch.nn import functional as F from torch.cuda.amp import GradScaler, autocast from collections import OrderedDict from dassl.engine import TRAINER_REGISTRY, TrainerX from dassl.metrics import compute_accuracy from dassl.utils import load_pretrained_weights, load_checkpoint from dassl.optim import build_optimizer, build_lr_scheduler from .clip_text import clip from .clip_text.simple_tokenizer import SimpleTokenizer as _Tokenizer from scipy.optimize import linear_sum_assignment
1,603
_tokenizer = _Tokenizer() def load_clip_to_cpu(cfg): backbone_name = cfg.MODEL.BACKBONE.NAME
_tokenizer = _Tokenizer() def load_clip_to_cpu(cfg): backbone_name = cfg.MODEL.BACKBONE.NAME
url = clip._MODELS[backbone_name]
0
2023-11-14 03:50:33+00:00
4k
KevinXu02/ControlledDreamGaussian
frankmocap/renderer/glRenderer.py
[ { "identifier": "createProgram", "path": "frankmocap/renderer/shaders/framework.py", "snippet": "def createProgram(shaderList):\n program = glCreateProgram()\n\n for shader in shaderList:\n glAttachShader(program, shader)\n\n glLinkProgram(program)\n\n status = glGetProgramiv(program,...
import numpy as np import cv2 import scipy.io as sio import cv2 import viewer2D from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GL import * from frankmocap.renderer.shaders.framework import createProgram, loadShader from frankmocap.renderer.render_utils import ComputeNormal from modelViewer.batch_smpl import SMPL
2,054
# Copyright (c) Facebook, Inc. and its affiliates. _glut_window = None class glRenderer: def __init__(self, width=640, height=480, name='GL Renderer', program_files=['renderer/shaders/simple140.fs', 'renderer/shaders/simple140.vs'], color_size=1, ms_rate=1): self.width = width self.height = height self.name = name self.display_mode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE self.use_inverse_depth = False global _glut_window if _glut_window is None: glutInit() glutInitDisplayMode(self.display_mode) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) _glut_window = glutCreateWindow("GL_Renderer") glEnable(GL_DEPTH_CLAMP) glEnable(GL_DEPTH_TEST) glClampColor(GL_CLAMP_READ_COLOR, GL_FALSE) glClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE) glClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE) self.program = None self.initShaderProgram(program_files) # Init Uniform variables self.model_mat_unif = glGetUniformLocation(self.program, 'ModelMat') self.persp_mat_unif = glGetUniformLocation(self.program, 'PerspMat') self.model_view_matrix = None self.projection_matrix = None self.vertex_buffer = glGenBuffers(1) self.color_buffer = glGenBuffers(1) self.normal_buffer = glGenBuffers(1) self.index_buffer = glGenBuffers(1) #for Mesh face indices. Without this vertices should be repeated and ordered (3x times bigger) #Create Background Texture glPixelStorei(GL_UNPACK_ALIGNMENT, 1) #So that texture doesnt have to be power of 2 self.backgroundTextureID = glGenTextures(1) K = np.array([[2000, 0, 960],[0, 2000, 540],[0,0,1]]) #MTC default camera. for 1920 x 1080 input image self.camView_K = K # Inner storage for buffer data self.vertex_data = None self.vertex_dim = None self.n_vertices = None #Variables for view change self.m_xTrans = 0. self.m_yTrans = 0. self.m_zTrans = 0. self.m_zoom = 378 self.m_xRotate = 59. self.m_yRotate = 0. self.m_zRotate = 0. self.m_xrot = 0.0 self.m_yrot = 0.0 #Camera view self.m_viewmode = "cam" #To compute sideview self.m_meshCenter = None #Option self.bOffscreenMode = False self.bAntiAliasing = True #apply anti aliasing #Textures self.data_texture = None #Visualization option self.bShowBackground = False self.bShowFloor = False self.nearPlane = 1 # original self.farPlane = 10000.0 self.counter=1 self.bOrthoCam = True glutMouseFunc(self.mouseButton) glutMotionFunc(self.mouseMotion) glutDisplayFunc(self.display) glutReshapeFunc(self.reshape) def initShaderProgram(self, program_files): # Init shader programs shader_list = [] for program_file in program_files: _, ext = os.path.splitext(program_file) if ext == '.vs': shader_list.append(loadShader(GL_VERTEX_SHADER, program_file)) elif ext == '.fs': shader_list.append(loadShader(GL_FRAGMENT_SHADER, program_file)) elif ext == '.gs': shader_list.append(loadShader(GL_GEOMETRY_SHADER, program_file)) if self.program is not None: glDeleteProgram(self.program)
# Copyright (c) Facebook, Inc. and its affiliates. _glut_window = None class glRenderer: def __init__(self, width=640, height=480, name='GL Renderer', program_files=['renderer/shaders/simple140.fs', 'renderer/shaders/simple140.vs'], color_size=1, ms_rate=1): self.width = width self.height = height self.name = name self.display_mode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE self.use_inverse_depth = False global _glut_window if _glut_window is None: glutInit() glutInitDisplayMode(self.display_mode) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(0, 0) _glut_window = glutCreateWindow("GL_Renderer") glEnable(GL_DEPTH_CLAMP) glEnable(GL_DEPTH_TEST) glClampColor(GL_CLAMP_READ_COLOR, GL_FALSE) glClampColor(GL_CLAMP_FRAGMENT_COLOR, GL_FALSE) glClampColor(GL_CLAMP_VERTEX_COLOR, GL_FALSE) self.program = None self.initShaderProgram(program_files) # Init Uniform variables self.model_mat_unif = glGetUniformLocation(self.program, 'ModelMat') self.persp_mat_unif = glGetUniformLocation(self.program, 'PerspMat') self.model_view_matrix = None self.projection_matrix = None self.vertex_buffer = glGenBuffers(1) self.color_buffer = glGenBuffers(1) self.normal_buffer = glGenBuffers(1) self.index_buffer = glGenBuffers(1) #for Mesh face indices. Without this vertices should be repeated and ordered (3x times bigger) #Create Background Texture glPixelStorei(GL_UNPACK_ALIGNMENT, 1) #So that texture doesnt have to be power of 2 self.backgroundTextureID = glGenTextures(1) K = np.array([[2000, 0, 960],[0, 2000, 540],[0,0,1]]) #MTC default camera. for 1920 x 1080 input image self.camView_K = K # Inner storage for buffer data self.vertex_data = None self.vertex_dim = None self.n_vertices = None #Variables for view change self.m_xTrans = 0. self.m_yTrans = 0. self.m_zTrans = 0. self.m_zoom = 378 self.m_xRotate = 59. self.m_yRotate = 0. self.m_zRotate = 0. self.m_xrot = 0.0 self.m_yrot = 0.0 #Camera view self.m_viewmode = "cam" #To compute sideview self.m_meshCenter = None #Option self.bOffscreenMode = False self.bAntiAliasing = True #apply anti aliasing #Textures self.data_texture = None #Visualization option self.bShowBackground = False self.bShowFloor = False self.nearPlane = 1 # original self.farPlane = 10000.0 self.counter=1 self.bOrthoCam = True glutMouseFunc(self.mouseButton) glutMotionFunc(self.mouseMotion) glutDisplayFunc(self.display) glutReshapeFunc(self.reshape) def initShaderProgram(self, program_files): # Init shader programs shader_list = [] for program_file in program_files: _, ext = os.path.splitext(program_file) if ext == '.vs': shader_list.append(loadShader(GL_VERTEX_SHADER, program_file)) elif ext == '.fs': shader_list.append(loadShader(GL_FRAGMENT_SHADER, program_file)) elif ext == '.gs': shader_list.append(loadShader(GL_GEOMETRY_SHADER, program_file)) if self.program is not None: glDeleteProgram(self.program)
self.program = createProgram(shader_list)
0
2023-11-17 05:21:26+00:00
4k
Veridise/vanguard-aleo
vanguard/aleo/detectors/unused.py
[ { "identifier": "AleoProgram", "path": "vanguard/aleo/grammar.py", "snippet": "class AleoProgram:\n \"\"\"A virtual machine that prepare Aleo program for future use and provides common functionalities\n \"\"\"\n\n def __init__(self, json=None):\n self.json = json\n\n # simplified ...
import networkx as nx from ..grammar import AleoProgram from ..common import get_dfg_edges
2,643
def detector_unused(prog: AleoProgram, func: str): """Detect for unused variable Args: - prog (AleoProgram): - func (str): Rets: (result, info) """
def detector_unused(prog: AleoProgram, func: str): """Detect for unused variable Args: - prog (AleoProgram): - func (str): Rets: (result, info) """
edges = get_dfg_edges(prog, func)
1
2023-11-10 02:57:03+00:00
4k
dazhangyu123/OCL
evaluate.py
[ { "identifier": "get_model", "path": "utils/train_helper.py", "snippet": "def get_model(args):\n if args.backbone == \"deeplabv2_multi\":\n model = DeeplabMulti(num_classes=args.num_classes,\n pretrained=args.imagenet_pretrained)\n params = model.optim_paramet...
import os import sys import torch.optim as optim from train_source import * from utils.train_helper import get_model, modified_bn_forward, MetricLogger, flip from utils.eval import build_eval_info from copy import deepcopy
2,405
sys.path.append(os.path.abspath('tools')) class Evaluater(): def __init__(self, cuda=None, train_id=None, logger=None, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) self.method = self.method os.environ["CUDA_VISIBLE_DEVICES"] = self.gpu self.cuda = cuda and torch.cuda.is_available() self.device = torch.device('cuda' if self.cuda else 'cpu') self.current_MIoU = 0 self.best_MIou = 0 self.current_epoch = 0 self.current_iter = 0 self.train_id = train_id self.logger = logger # set TensorboardX self.writer = SummaryWriter(self.checkpoint_dir) # Metric definition self.Eval = Eval(self.num_classes) # model self.model, params = get_model(self) self.model = nn.DataParallel(self.model, device_ids=[0]) self.model.eval() self.model.to(self.device) # load pretrained checkpoint if self.pretrained_ckpt_file is not None: path1 = os.path.join(*self.checkpoint_dir.split('/')[:-1], self.train_id + 'best.pth') path2 = self.pretrained_ckpt_file if os.path.exists(path1): pretrained_ckpt_file = path1 elif os.path.exists(path2): pretrained_ckpt_file = path2 else: raise AssertionError("no pretrained_ckpt_file") self.load_checkpoint(pretrained_ckpt_file) if args.prior > 0.0: assert isinstance(args.prior, float) and args.prior <= 1 and args.prior >= 0, 'False prior exists.' nn.BatchNorm2d.prior = None nn.BatchNorm2d.forward = modified_bn_forward nn.BatchNorm2d.prior = args.prior # dataloader self.dataloader = City_DataLoader(self) if self.dataset=="cityscapes" else GTA5_DataLoader(self) self.dataloader.val_loader = self.dataloader.data_loader self.dataloader.valid_iterations = min(self.dataloader.num_iterations, 500) self.epoch_num = ceil(self.iter_max / self.dataloader.num_iterations) def main(self): # choose cuda if self.cuda: current_device = torch.cuda.current_device() self.logger.info("This model will run on {}".format(torch.cuda.get_device_name(current_device))) else: self.logger.info("This model will run on CPU") if self.method == 'TTT': # validate self.TTT() elif self.method == 'baseline': self.validate() else: raise AssertionError("do not implement ttt method") self.writer.close() def TTT(self): self.logger.info('Test time training...') self.Eval.reset() anchor = deepcopy(self.model.state_dict()) optimizer = optim.SGD(self.model.parameters(), lr=self.learning_rate, momentum=self.momentum, weight_decay=self.weight_decay)
sys.path.append(os.path.abspath('tools')) class Evaluater(): def __init__(self, cuda=None, train_id=None, logger=None, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) self.method = self.method os.environ["CUDA_VISIBLE_DEVICES"] = self.gpu self.cuda = cuda and torch.cuda.is_available() self.device = torch.device('cuda' if self.cuda else 'cpu') self.current_MIoU = 0 self.best_MIou = 0 self.current_epoch = 0 self.current_iter = 0 self.train_id = train_id self.logger = logger # set TensorboardX self.writer = SummaryWriter(self.checkpoint_dir) # Metric definition self.Eval = Eval(self.num_classes) # model self.model, params = get_model(self) self.model = nn.DataParallel(self.model, device_ids=[0]) self.model.eval() self.model.to(self.device) # load pretrained checkpoint if self.pretrained_ckpt_file is not None: path1 = os.path.join(*self.checkpoint_dir.split('/')[:-1], self.train_id + 'best.pth') path2 = self.pretrained_ckpt_file if os.path.exists(path1): pretrained_ckpt_file = path1 elif os.path.exists(path2): pretrained_ckpt_file = path2 else: raise AssertionError("no pretrained_ckpt_file") self.load_checkpoint(pretrained_ckpt_file) if args.prior > 0.0: assert isinstance(args.prior, float) and args.prior <= 1 and args.prior >= 0, 'False prior exists.' nn.BatchNorm2d.prior = None nn.BatchNorm2d.forward = modified_bn_forward nn.BatchNorm2d.prior = args.prior # dataloader self.dataloader = City_DataLoader(self) if self.dataset=="cityscapes" else GTA5_DataLoader(self) self.dataloader.val_loader = self.dataloader.data_loader self.dataloader.valid_iterations = min(self.dataloader.num_iterations, 500) self.epoch_num = ceil(self.iter_max / self.dataloader.num_iterations) def main(self): # choose cuda if self.cuda: current_device = torch.cuda.current_device() self.logger.info("This model will run on {}".format(torch.cuda.get_device_name(current_device))) else: self.logger.info("This model will run on CPU") if self.method == 'TTT': # validate self.TTT() elif self.method == 'baseline': self.validate() else: raise AssertionError("do not implement ttt method") self.writer.close() def TTT(self): self.logger.info('Test time training...') self.Eval.reset() anchor = deepcopy(self.model.state_dict()) optimizer = optim.SGD(self.model.parameters(), lr=self.learning_rate, momentum=self.momentum, weight_decay=self.weight_decay)
metric_logger = MetricLogger(delimiter=" ")
2
2023-11-14 02:01:11+00:00
4k
winrey/x-following
common_cli.py
[ { "identifier": "FollowingUser", "path": "client.py", "snippet": "class MyUser(TypedDict):\nclass TimelineUserEntitiesDescription(TypedDict):\nclass TimelineUserEntitiesURL(TypedDict):\nclass TimelineUserEntities(TypedDict):\nclass TimelineUserLegacy(TypedDict):\nclass TimelineUser(TypedDict):\nclass Fo...
import base64 import os import sys import webbrowser import requests from io import BytesIO from typing import List from colorama import init, Fore, Style from PIL import Image from client import FollowingUser, client from back_white_list import save_blacklist, save_whitelist
1,744
LINE_STR = "-------------------------" # Initialize Colorama init(autoreset=True) def select_account(): users = client.get_multi_user_info() choice = 0 if len(users) > 1: print("Select Account:") for idx, user in enumerate(users): print(f"{idx+1}. {user['screen_name']}") choice = input("Which Account? Please input the number: ") choice = int(choice) - 1 client.set_current_user_info(users[choice]) # Function to center the text based on the terminal width def center_text(text): term_width = os.get_terminal_size().columns return text.center(term_width) def print_centered_description(description): term_width = os.get_terminal_size().columns max_line_length = term_width // 3 # Maximum length of the line is half the width of the terminal # Split the description into words words = description.split() # Initialize an empty line and list of lines line = '' lines = [] # Build lines of appropriate length for word in words: # Check if adding the next word would exceed the max line length if len(line) + len(word) + 1 > max_line_length: lines.append(line) line = word else: line += ' ' + word if line else word # Add the last line if it's not empty if line: lines.append(line) # Print each line centered for line in lines: print(YELLOW + line.center(term_width) + RESET) def display_image_iterm2_from_url(image_url, scale=0.1): response = requests.get(image_url) if response.status_code == 200: # 获取原始图片数据 image_data = BytesIO(response.content) # 使用Pillow来加载图像 image = Image.open(image_data) # 计算缩放后的新尺寸 term_width = os.get_terminal_size().columns new_width = term_width * scale aspect_ratio = image.height / image.width new_height = aspect_ratio * new_width # 转换图片大小为整数 new_width, new_height = int(new_width), int(new_height) # 缩放图像并再次编码为base64 resized_image = image.resize((new_width, new_height), Image.LANCZOS) buffered = BytesIO() resized_image.save(buffered, format="PNG") encoded_image = base64.b64encode(buffered.getvalue()).decode('utf-8') # 使用 iTerm2 的专有转义序列来显示图片 # 添加 padding 来尝试居中图片(这将不完全准确) padding = " " * ((term_width - new_width) // 2) print(padding + f'\x1b]1337;File=inline=1;width={new_width};preserveAspectRatio=1:{encoded_image}\a\n') else: print(f"Error: Unable to download image. Status code: {response.status_code}") def print_following_info(following: FollowingUser): is_verify = following.get('is_blue_verified', None) or following.get('is_verified', None) personal_site = following.get('legacy', {}).get('entities', {}).get('url', {}).get('urls', [{}])[0].get('expanded_url', None) is_following = following.get('following', False) follow_by = following.get('followed_by', False) relation = '❤' if is_following and follow_by else '←' if follow_by else '→' if is_following else 'x' # Bold the name and handle, and add a checkmark or cross emoji based on verification status # Centered and styled text output display_image_iterm2_from_url(following['profile_image_url_https']) print(center_text(f"{BOLD}{following['name']}{RESET} (@{following['screen_name']}) {GREEN+'✅' if is_verify else RED+''}\n")) print_centered_description(following['description']) print() if personal_site: print(center_text(f"{CYAN}{personal_site}{RESET}")) print() print(center_text(f"{MAGENTA}{following.get('friends_count', 'x')} following, {following.get('followers_count', 'x')} followers")) print() print(center_text(f"DM: {following.get('can_dm', False) and '✅' or '❌'} | You {relation} 👤")) print(center_text(f"{BLUE}https://twitter.com/{following['screen_name']}{RESET}")) def trial_single(following: FollowingUser): print_following_info(following) while True: print(f"\n\n{GREEN}{center_text(LINE_STR)}{RESET}\n\n") print(f"\t\t\tGuilty or not Guilty?") print(f"\t\t\t( {RED}[g]{RESET}uilty / {BLUE}[n]{RESET}ot guilty / {CYAN}[w]{RESET}hitelist / open {MAGENTA}[p]{RESET}rofile / {YELLOW}[q]{RESET}uit )") choice = input(f"\t\t\tYour Choice: ") choice = choice.lower() print() if choice == 'g': print(center_text(f"{RED}Guilty! {following['name']} (@{following['screen_name']}) Unfollowed!{RESET}")) client.unfollow(following) # Uncomment this when you integrate with Twitter API
BOLD = Style.BRIGHT NORMAL = Style.NORMAL GREEN = Fore.GREEN RED = Fore.RED YELLOW = Fore.YELLOW BLUE = Fore.BLUE CYAN = Fore.CYAN MAGENTA = Fore.MAGENTA RESET = Style.RESET_ALL LINE_STR = "-------------------------" # Initialize Colorama init(autoreset=True) def select_account(): users = client.get_multi_user_info() choice = 0 if len(users) > 1: print("Select Account:") for idx, user in enumerate(users): print(f"{idx+1}. {user['screen_name']}") choice = input("Which Account? Please input the number: ") choice = int(choice) - 1 client.set_current_user_info(users[choice]) # Function to center the text based on the terminal width def center_text(text): term_width = os.get_terminal_size().columns return text.center(term_width) def print_centered_description(description): term_width = os.get_terminal_size().columns max_line_length = term_width // 3 # Maximum length of the line is half the width of the terminal # Split the description into words words = description.split() # Initialize an empty line and list of lines line = '' lines = [] # Build lines of appropriate length for word in words: # Check if adding the next word would exceed the max line length if len(line) + len(word) + 1 > max_line_length: lines.append(line) line = word else: line += ' ' + word if line else word # Add the last line if it's not empty if line: lines.append(line) # Print each line centered for line in lines: print(YELLOW + line.center(term_width) + RESET) def display_image_iterm2_from_url(image_url, scale=0.1): response = requests.get(image_url) if response.status_code == 200: # 获取原始图片数据 image_data = BytesIO(response.content) # 使用Pillow来加载图像 image = Image.open(image_data) # 计算缩放后的新尺寸 term_width = os.get_terminal_size().columns new_width = term_width * scale aspect_ratio = image.height / image.width new_height = aspect_ratio * new_width # 转换图片大小为整数 new_width, new_height = int(new_width), int(new_height) # 缩放图像并再次编码为base64 resized_image = image.resize((new_width, new_height), Image.LANCZOS) buffered = BytesIO() resized_image.save(buffered, format="PNG") encoded_image = base64.b64encode(buffered.getvalue()).decode('utf-8') # 使用 iTerm2 的专有转义序列来显示图片 # 添加 padding 来尝试居中图片(这将不完全准确) padding = " " * ((term_width - new_width) // 2) print(padding + f'\x1b]1337;File=inline=1;width={new_width};preserveAspectRatio=1:{encoded_image}\a\n') else: print(f"Error: Unable to download image. Status code: {response.status_code}") def print_following_info(following: FollowingUser): is_verify = following.get('is_blue_verified', None) or following.get('is_verified', None) personal_site = following.get('legacy', {}).get('entities', {}).get('url', {}).get('urls', [{}])[0].get('expanded_url', None) is_following = following.get('following', False) follow_by = following.get('followed_by', False) relation = '❤' if is_following and follow_by else '←' if follow_by else '→' if is_following else 'x' # Bold the name and handle, and add a checkmark or cross emoji based on verification status # Centered and styled text output display_image_iterm2_from_url(following['profile_image_url_https']) print(center_text(f"{BOLD}{following['name']}{RESET} (@{following['screen_name']}) {GREEN+'✅' if is_verify else RED+''}\n")) print_centered_description(following['description']) print() if personal_site: print(center_text(f"{CYAN}{personal_site}{RESET}")) print() print(center_text(f"{MAGENTA}{following.get('friends_count', 'x')} following, {following.get('followers_count', 'x')} followers")) print() print(center_text(f"DM: {following.get('can_dm', False) and '✅' or '❌'} | You {relation} 👤")) print(center_text(f"{BLUE}https://twitter.com/{following['screen_name']}{RESET}")) def trial_single(following: FollowingUser): print_following_info(following) while True: print(f"\n\n{GREEN}{center_text(LINE_STR)}{RESET}\n\n") print(f"\t\t\tGuilty or not Guilty?") print(f"\t\t\t( {RED}[g]{RESET}uilty / {BLUE}[n]{RESET}ot guilty / {CYAN}[w]{RESET}hitelist / open {MAGENTA}[p]{RESET}rofile / {YELLOW}[q]{RESET}uit )") choice = input(f"\t\t\tYour Choice: ") choice = choice.lower() print() if choice == 'g': print(center_text(f"{RED}Guilty! {following['name']} (@{following['screen_name']}) Unfollowed!{RESET}")) client.unfollow(following) # Uncomment this when you integrate with Twitter API
save_blacklist(following)
1
2023-11-11 18:54:25+00:00
4k
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
2,109
# -*- 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,
# -*- 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,
1
2023-11-14 05:55:48+00:00
4k
Scholar01/ComfyUI-Keyframe
keyframe/nodes.py
[ { "identifier": "KeyframePartGroup", "path": "keyframe/interface.py", "snippet": "class KeyframePartGroup:\n def __init__(self) -> None:\n self.keyframes: list[KeyframePart] = []\n\n def add(self, keyframe: KeyframePart) -> None:\n added = False\n for i in range(len(self.keyfr...
import numpy as np import comfy.sample as comfy_sample from .interface import KeyframePartGroup, KeyframePart, ModelInjectParam from .sampling import keyframe_sample_factory from .util import inject_model from .samples import inject_samples
2,117
RETURN_NAMES = ("part",) FUNCTION = "load_keyframe_part" CATEGORY = "KeyframePart" def load_keyframe_part(self, image, batch_index, denoise, part=None): if not part: part = KeyframePartGroup() part = part.clone() keyframe = KeyframePart(batch_index, image, denoise) part.add(keyframe) return (part,) class KeyframeInterpolationPartNode: @classmethod def INPUT_TYPES(s): return { "required": { "image": ("IMAGE",), "batch_index_from": ("INT", {"default": 0, "min": 0, "max": 9999, "step": 1}), "batch_index_to": ("INT", {"default": 4, "min": 1, "max": 9999, "step": 1}), "denoise_from": ("FLOAT", {"default": 0.1, "min": 0.001, "max": 1.0, "step": 0.01}), "denoise_to": ("FLOAT", {"default": 1.0, "min": 0.001, "max": 1.0, "step": 0.01}), "interpolation": (["linear", "ease-in", "ease-out", "ease-in-out"],), }, "optional": { "part": ("LATENT_KEYFRAME_PART",), } } RETURN_TYPES = ("LATENT_KEYFRAME_PART",) RETURN_NAMES = ("part",) FUNCTION = "load_keyframe_part" CATEGORY = "KeyframeInterpolationPartNode" def load_keyframe_part(self, image, batch_index_from, batch_index_to, denoise_from, denoise_to, interpolation, part=None): if batch_index_from >= batch_index_to: raise ValueError("batch_index_from must be less than batch_index_to") if not part: part = KeyframePartGroup() part = part.clone() current_group = KeyframePartGroup() steps = batch_index_to - batch_index_from diff = denoise_to - denoise_from if interpolation == "linear": weights = np.linspace(denoise_from, denoise_to, steps) elif interpolation == "ease-in": index = np.linspace(0, 1, steps) weights = diff * np.power(index, 2) + denoise_from elif interpolation == "ease-out": index = np.linspace(0, 1, steps) weights = diff * (1 - np.power(1 - index, 2)) + denoise_from elif interpolation == "ease-in-out": index = np.linspace(0, 1, steps) weights = diff * ((1 - np.cos(index * np.pi)) / 2) + denoise_from for i in range(steps): keyframe = KeyframePart(batch_index_from + i, image, float(weights[i])) current_group.add(keyframe) # replace values with prev_latent_keyframes for latent_keyframe in part.keyframes: current_group.add(latent_keyframe) return (current_group,) class KeyframeApplyNode: @classmethod def INPUT_TYPES(s): return { "required": { "model": ("MODEL",), "latent": ("LATENT",), "part_group": ("LATENT_KEYFRAME_PART",), "vae": ("VAE",), } } RETURN_TYPES = ("MODEL", "LATENT",) RETURN_NAMES = ("model", "latent",) FUNCTION = "apply_latent_keyframe" CATEGORY = "LatentKeyframeApply" @staticmethod def vae_encode_crop_pixels(pixels): x = (pixels.shape[1] // 8) * 8 y = (pixels.shape[2] // 8) * 8 if pixels.shape[1] != x or pixels.shape[2] != y: x_offset = (pixels.shape[1] % 8) // 2 y_offset = (pixels.shape[2] % 8) // 2 pixels = pixels[:, x_offset:x + x_offset, y_offset:y + y_offset, :] return pixels def encode(self, vae, pixels): pixels = self.vae_encode_crop_pixels(pixels) t = vae.encode(pixels[:, :, :, :3]) return t def apply_latent_keyframe(self, model, latent, part_group: KeyframePartGroup, vae): # 预处理latent,把图片替换进去 for part in part_group.keyframes: latent['samples'][part.batch_index] = self.encode(vae, part.image) print(f"apply keyframe {part.batch_index}:{part.denoise}") # 注入参数,后续处理 inject_param = ModelInjectParam(part_group, latent)
inject_samples() comfy_sample.sample = keyframe_sample_factory(comfy_sample.sample) class KeyframePartNode: @classmethod def INPUT_TYPES(s): return { "required": { "image": ("IMAGE",), "batch_index": ("INT", {"default": 0, "min": 0, "max": 9999, "step": 1}), "denoise": ("FLOAT", {"default": 0.1, "min": 0.001, "max": 1.0, "step": 0.01}), }, "optional": { "part": ("LATENT_KEYFRAME_PART",), } } RETURN_TYPES = ("LATENT_KEYFRAME_PART",) RETURN_NAMES = ("part",) FUNCTION = "load_keyframe_part" CATEGORY = "KeyframePart" def load_keyframe_part(self, image, batch_index, denoise, part=None): if not part: part = KeyframePartGroup() part = part.clone() keyframe = KeyframePart(batch_index, image, denoise) part.add(keyframe) return (part,) class KeyframeInterpolationPartNode: @classmethod def INPUT_TYPES(s): return { "required": { "image": ("IMAGE",), "batch_index_from": ("INT", {"default": 0, "min": 0, "max": 9999, "step": 1}), "batch_index_to": ("INT", {"default": 4, "min": 1, "max": 9999, "step": 1}), "denoise_from": ("FLOAT", {"default": 0.1, "min": 0.001, "max": 1.0, "step": 0.01}), "denoise_to": ("FLOAT", {"default": 1.0, "min": 0.001, "max": 1.0, "step": 0.01}), "interpolation": (["linear", "ease-in", "ease-out", "ease-in-out"],), }, "optional": { "part": ("LATENT_KEYFRAME_PART",), } } RETURN_TYPES = ("LATENT_KEYFRAME_PART",) RETURN_NAMES = ("part",) FUNCTION = "load_keyframe_part" CATEGORY = "KeyframeInterpolationPartNode" def load_keyframe_part(self, image, batch_index_from, batch_index_to, denoise_from, denoise_to, interpolation, part=None): if batch_index_from >= batch_index_to: raise ValueError("batch_index_from must be less than batch_index_to") if not part: part = KeyframePartGroup() part = part.clone() current_group = KeyframePartGroup() steps = batch_index_to - batch_index_from diff = denoise_to - denoise_from if interpolation == "linear": weights = np.linspace(denoise_from, denoise_to, steps) elif interpolation == "ease-in": index = np.linspace(0, 1, steps) weights = diff * np.power(index, 2) + denoise_from elif interpolation == "ease-out": index = np.linspace(0, 1, steps) weights = diff * (1 - np.power(1 - index, 2)) + denoise_from elif interpolation == "ease-in-out": index = np.linspace(0, 1, steps) weights = diff * ((1 - np.cos(index * np.pi)) / 2) + denoise_from for i in range(steps): keyframe = KeyframePart(batch_index_from + i, image, float(weights[i])) current_group.add(keyframe) # replace values with prev_latent_keyframes for latent_keyframe in part.keyframes: current_group.add(latent_keyframe) return (current_group,) class KeyframeApplyNode: @classmethod def INPUT_TYPES(s): return { "required": { "model": ("MODEL",), "latent": ("LATENT",), "part_group": ("LATENT_KEYFRAME_PART",), "vae": ("VAE",), } } RETURN_TYPES = ("MODEL", "LATENT",) RETURN_NAMES = ("model", "latent",) FUNCTION = "apply_latent_keyframe" CATEGORY = "LatentKeyframeApply" @staticmethod def vae_encode_crop_pixels(pixels): x = (pixels.shape[1] // 8) * 8 y = (pixels.shape[2] // 8) * 8 if pixels.shape[1] != x or pixels.shape[2] != y: x_offset = (pixels.shape[1] % 8) // 2 y_offset = (pixels.shape[2] % 8) // 2 pixels = pixels[:, x_offset:x + x_offset, y_offset:y + y_offset, :] return pixels def encode(self, vae, pixels): pixels = self.vae_encode_crop_pixels(pixels) t = vae.encode(pixels[:, :, :, :3]) return t def apply_latent_keyframe(self, model, latent, part_group: KeyframePartGroup, vae): # 预处理latent,把图片替换进去 for part in part_group.keyframes: latent['samples'][part.batch_index] = self.encode(vae, part.image) print(f"apply keyframe {part.batch_index}:{part.denoise}") # 注入参数,后续处理 inject_param = ModelInjectParam(part_group, latent)
inject_model(model.model, inject_param)
4
2023-11-10 13:15:08+00:00
4k
Hamidrezaostadabbas/FOSS4G_Asia_2023
03_Exercise_2/exercise_2/layout_generator/layout_generator.py
[ { "identifier": "LayoutGeneratorDialog", "path": "03_Exercise_2/exercise_2/layout_generator/layout_generator_dialog.py", "snippet": "class LayoutGeneratorDialog(QtWidgets.QDialog, FORM_CLASS):\n def __init__(self, parent=None):\n \"\"\"Constructor.\"\"\"\n super(LayoutGeneratorDialog, s...
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtWidgets import QAction from .resources import * from .layout_generator_dialog import LayoutGeneratorDialog from .core_functions import ( import_vector_layer, display_vector_layer, zoom_to_layer, qml_loader, get_script_path_plugin ) from .layout import layout_executor import os.path
2,049
# initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'LayoutGenerator_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Layout Generator') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('LayoutGenerator', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None ): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/layout_generator/icon.png' self.add_action(icon_path, text=self.tr(u'Layout Generator'), callback=self.run, parent=self.iface.mainWindow()) self.layout_generator_dialog.addDataPushButton.clicked.connect(self.__load_data_with_symbol) self.layout_generator_dialog.pdfGeneratorPushButton.clicked.connect(self.__print_map) # will be set False in run() self.first_start = True def __load_data_with_symbol(self): layers = [ ('land_parcels', 'Land parcel', self.layout_generator_dialog.landParcelFileWidget.filePath()), ('buildings', 'Buildings', self.layout_generator_dialog.buildingFileWidget.filePath()), ] for layer in layers: imported_layer = import_vector_layer(layer[-1], layer[1])
# -*- coding: utf-8 -*- """ /*************************************************************************** LayoutGenerator A QGIS plugin auto layout generator Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ ------------------- begin : 2023-11-24 git sha : $Format:%H$ copyright : (C) 2023 by foss4g-asia email : info@foss4g-asia.com ***************************************************************************/ /*************************************************************************** * * * 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 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ class LayoutGenerator: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # new variables self.layout_generator_dialog = LayoutGeneratorDialog() # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'LayoutGenerator_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Layout Generator') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('LayoutGenerator', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None ): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/layout_generator/icon.png' self.add_action(icon_path, text=self.tr(u'Layout Generator'), callback=self.run, parent=self.iface.mainWindow()) self.layout_generator_dialog.addDataPushButton.clicked.connect(self.__load_data_with_symbol) self.layout_generator_dialog.pdfGeneratorPushButton.clicked.connect(self.__print_map) # will be set False in run() self.first_start = True def __load_data_with_symbol(self): layers = [ ('land_parcels', 'Land parcel', self.layout_generator_dialog.landParcelFileWidget.filePath()), ('buildings', 'Buildings', self.layout_generator_dialog.buildingFileWidget.filePath()), ] for layer in layers: imported_layer = import_vector_layer(layer[-1], layer[1])
display_vector_layer(imported_layer, layer[1])
2
2023-11-17 09:40:49+00:00
4k
davidhozic/TkClassWizard
tkclasswiz/object_frame/frame_base.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, Any, TYPE_CHECKING, TypeVar from abc import ABC from inspect import isabstract from contextlib import suppress from ..convert import * from ..aliasing import * from ..dpi import * from ..utilities import * from ..storage import * from ..messagebox import Messagebox from ..extensions import extendable from ..doc import doc_category from .window import ObjectEditWindow import tkinter.ttk as ttk import tkinter as tk import json
1,879
if TYPE_CHECKING: T = TypeVar('T') __all__ = ( "NewObjectFrameBase", ) @extendable
if TYPE_CHECKING: T = TypeVar('T') __all__ = ( "NewObjectFrameBase", ) @extendable
@doc_category("Object frames")
2
2023-11-14 09:26:01+00:00
4k
raphaelreme/koft
src/experiments/simulate.py
[ { "identifier": "Simulator", "path": "src/simulator/simulator.py", "snippet": "class Simulator:\n \"\"\"Simulator object\n\n Handle the image generation and temporal evolution.\n \"\"\"\n\n def __init__(\n self,\n particles: GaussianParticles,\n background: Optional[Gaus...
import dataclasses import pathlib import cv2 import dacite import numpy as np import torch import tqdm # type: ignore import yaml # type: ignore from ..simulator.simulator import Simulator, SimulatorConfig from ..simulator.motion import ElasticMotion from ..utils import enforce_all_seeds
1,646
"""Simulate a fake video""" @dataclasses.dataclass class ExperimentConfig: seed: int n_frames: int display: bool
"""Simulate a fake video""" @dataclasses.dataclass class ExperimentConfig: seed: int n_frames: int display: bool
simulator: SimulatorConfig
1
2023-11-10 10:18:39+00:00
4k
har777/snek-evm
test.py
[ { "identifier": "EVM", "path": "vm.py", "snippet": "class EVM:\n def __init__(self):\n self.address_to_contract = {}\n\n def create_contract(self, bytecode, address):\n contract = Contract(bytecode=bytecode, address=address)\n self.address_to_contract[address] = contract\n ...
import unittest from vm import EVM, TransactionMetadata, get_create_contract_address, get_create2_contract_address
1,608
class UtilTestCase(unittest.TestCase): def test_get_create_contract_address(self): sender_address = "0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0" self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=0), "0xcd234a471b72ba2f1ccf0a70fcaba648a5eecd8d") self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=1), "0x343c43a37d37dff08ae8c4a11544c718abb4fcf8") self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=2), "0xf778b86fa74e846c4f0a1fbd1335fe81c00a0c91") self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=3), "0xfffd933a0bc612844eaf0c6fe3e5b8e9b6c1d19c") def test_get_create2_contract_address(self): # https://eips.ethereum.org/EIPS/eip-1014 self.assertEqual( get_create2_contract_address( origin_address="0x0000000000000000000000000000000000000000", salt=0, initialisation_code="00" ), "0x4d1a2e2bb4f88f0250f26ffff098b0b30b26bf38" ) self.assertEqual( get_create2_contract_address( origin_address="0xdeadbeef00000000000000000000000000000000", salt=0, initialisation_code="00" ), "0xb928f69bb1d91cd65274e3c79d8986362984fda3" ) self.assertEqual( get_create2_contract_address( origin_address="0xdeadbeef00000000000000000000000000000000", salt=1455368932401306996839762510191304720241787928576, initialisation_code="00" ), "0xd04116cdd17bebe565eb2422f2497e06cc1c9833" ) self.assertEqual( get_create2_contract_address( origin_address="0x0000000000000000000000000000000000000000", salt=0, initialisation_code="deadbeef" ), "0x70f2b2914a2a4b783faefb75f459a580616fcb5e" ) self.assertEqual( get_create2_contract_address( origin_address="0x00000000000000000000000000000000deadbeef", salt=3405691582, initialisation_code="deadbeef" ), "0x60f3f640a8508fc6a86d45df051962668e1e8ac7" ) self.assertEqual( get_create2_contract_address( origin_address="0x00000000000000000000000000000000deadbeef", salt=3405691582, initialisation_code="deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" ), "0x1d8bfdc5d46dc4f61d6b6115972536ebe6a8854c" ) self.assertEqual( get_create2_contract_address( origin_address="0x0000000000000000000000000000000000000000", salt=0, initialisation_code="" ), "0xe33c0c7f7df4809055c3eba6c09cfe4baf1bd9e0" ) class OpcodeTestCase(unittest.TestCase): def setUp(self): self.evm = EVM() self.address_1 = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045" self.address_2 = "0xd8da6bf26964af9d7eed9e03e53415d37aa96046" self.eoa_1 = "0xd8da6bf26964af9d7eed9e03e53415d37aa96047" def test_stop(self): # https://www.evm.codes/playground?fork=shanghai&unit=Wei&codeType=Bytecode&code='600a00600a'_ # PUSH1 0x0a # STOP # PUSH1 0x0a self.evm.create_contract(bytecode="600a00600a", address=self.address_1)
class UtilTestCase(unittest.TestCase): def test_get_create_contract_address(self): sender_address = "0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0" self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=0), "0xcd234a471b72ba2f1ccf0a70fcaba648a5eecd8d") self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=1), "0x343c43a37d37dff08ae8c4a11544c718abb4fcf8") self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=2), "0xf778b86fa74e846c4f0a1fbd1335fe81c00a0c91") self.assertEqual(get_create_contract_address(sender_address=sender_address, sender_nonce=3), "0xfffd933a0bc612844eaf0c6fe3e5b8e9b6c1d19c") def test_get_create2_contract_address(self): # https://eips.ethereum.org/EIPS/eip-1014 self.assertEqual( get_create2_contract_address( origin_address="0x0000000000000000000000000000000000000000", salt=0, initialisation_code="00" ), "0x4d1a2e2bb4f88f0250f26ffff098b0b30b26bf38" ) self.assertEqual( get_create2_contract_address( origin_address="0xdeadbeef00000000000000000000000000000000", salt=0, initialisation_code="00" ), "0xb928f69bb1d91cd65274e3c79d8986362984fda3" ) self.assertEqual( get_create2_contract_address( origin_address="0xdeadbeef00000000000000000000000000000000", salt=1455368932401306996839762510191304720241787928576, initialisation_code="00" ), "0xd04116cdd17bebe565eb2422f2497e06cc1c9833" ) self.assertEqual( get_create2_contract_address( origin_address="0x0000000000000000000000000000000000000000", salt=0, initialisation_code="deadbeef" ), "0x70f2b2914a2a4b783faefb75f459a580616fcb5e" ) self.assertEqual( get_create2_contract_address( origin_address="0x00000000000000000000000000000000deadbeef", salt=3405691582, initialisation_code="deadbeef" ), "0x60f3f640a8508fc6a86d45df051962668e1e8ac7" ) self.assertEqual( get_create2_contract_address( origin_address="0x00000000000000000000000000000000deadbeef", salt=3405691582, initialisation_code="deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" ), "0x1d8bfdc5d46dc4f61d6b6115972536ebe6a8854c" ) self.assertEqual( get_create2_contract_address( origin_address="0x0000000000000000000000000000000000000000", salt=0, initialisation_code="" ), "0xe33c0c7f7df4809055c3eba6c09cfe4baf1bd9e0" ) class OpcodeTestCase(unittest.TestCase): def setUp(self): self.evm = EVM() self.address_1 = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045" self.address_2 = "0xd8da6bf26964af9d7eed9e03e53415d37aa96046" self.eoa_1 = "0xd8da6bf26964af9d7eed9e03e53415d37aa96047" def test_stop(self): # https://www.evm.codes/playground?fork=shanghai&unit=Wei&codeType=Bytecode&code='600a00600a'_ # PUSH1 0x0a # STOP # PUSH1 0x0a self.evm.create_contract(bytecode="600a00600a", address=self.address_1)
operation = self.evm.execute_transaction(address=self.address_1, transaction_metadata=TransactionMetadata(from_address=self.eoa_1))
1
2023-11-10 14:13:05+00:00
4k
guwwl123/xet
main.py
[ { "identifier": "shop_get", "path": "tools/driver.py", "snippet": "def shop_get():\r\n url = \"https://study.xiaoe-tech.com/xe.learn-pc/my_attend_normal_list.get/1.0.1\"\r\n\r\n payload = json.dumps({\r\n \"page_size\": 16,\r\n \"page\": 1,\r\n \"agent_type\": 7,\r\n \"...
from tools.driver import shop_get, _setup, course_get, get_all_course_urls, get_m3u8_urls, m3u8_make from tools.log import logger
1,702
if __name__ == '__main__': work_dir = fr'D:\videos' # 1.获取所有课堂信息course_info,包括( app_id 和 resource_id ) # shop_infos = shop_get()[:1] shop_infos = shop_get() # logger.info(json.dumps(shop_get(), ensure_ascii=False)) browser, server, proxy = _setup() ok = [] retry = [] for shop_info in shop_infos: # 2.获取指定课堂的课程信息,根据shop_info中的 app_id 和 resource_id
if __name__ == '__main__': work_dir = fr'D:\videos' # 1.获取所有课堂信息course_info,包括( app_id 和 resource_id ) # shop_infos = shop_get()[:1] shop_infos = shop_get() # logger.info(json.dumps(shop_get(), ensure_ascii=False)) browser, server, proxy = _setup() ok = [] retry = [] for shop_info in shop_infos: # 2.获取指定课堂的课程信息,根据shop_info中的 app_id 和 resource_id
course_info = course_get(shop_info['app_id'], shop_info['resource_id'])
2
2023-11-10 06:23:37+00:00
4k
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
3,068
# 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:
# 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):
0
2023-11-10 10:26:10+00:00
4k
KeAWang/interpretable-cgm-representations
train_hybrid_vae.py
[ { "identifier": "preprocess_train_test", "path": "data_utils.py", "snippet": "def preprocess_train_test(seed, domain_adaptation=False):\n all_arrays, patient_info = load_data(seed=seed, domain_adaptation=domain_adaptation)\n train_idx, train_patient_ids = zip(*[(i, patient_id) for i, patient_id in...
import torch import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from data_utils import preprocess_train_test, MEAL_COVARIATES, DEMOGRAPHICS_COVARIATES from models import MechanisticAutoencoder, count_params from utils import seed_everything from torch.utils.data import DataLoader, TensorDataset from typing import NamedTuple
3,453
# %% seed = 4 batch_size = 64 lr = 1e-2 beta_hat = 0.01 num_epochs = 100 seed_everything(seed) if torch.backends.mps.is_available(): device = torch.device("mps") elif torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") train_arrays, test_arrays, patient_info, (train_mean, train_std) = preprocess_train_test(seed=21, domain_adaptation=False) train_tensors = list(map(lambda x: torch.as_tensor(x, dtype=torch.float, device=device), train_arrays)) train_dataset = TensorDataset(*train_tensors) train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) test_tensors = list(map(lambda x: torch.as_tensor(x, dtype=torch.float, device=device), test_arrays)) # %% G_mean = torch.as_tensor(train_mean[0], dtype=torch.float, device=device) G_std = torch.as_tensor(train_std[0], dtype=torch.float, device=device) def remove_scale(G, mean=G_mean, std=G_std): return (G - mean) / std def add_scale(G, mean=G_mean, std=G_std): return G * std + mean # %% model = MechanisticAutoencoder( meal_size=len(MEAL_COVARIATES),
# %% seed = 4 batch_size = 64 lr = 1e-2 beta_hat = 0.01 num_epochs = 100 seed_everything(seed) if torch.backends.mps.is_available(): device = torch.device("mps") elif torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") train_arrays, test_arrays, patient_info, (train_mean, train_std) = preprocess_train_test(seed=21, domain_adaptation=False) train_tensors = list(map(lambda x: torch.as_tensor(x, dtype=torch.float, device=device), train_arrays)) train_dataset = TensorDataset(*train_tensors) train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) test_tensors = list(map(lambda x: torch.as_tensor(x, dtype=torch.float, device=device), test_arrays)) # %% G_mean = torch.as_tensor(train_mean[0], dtype=torch.float, device=device) G_std = torch.as_tensor(train_std[0], dtype=torch.float, device=device) def remove_scale(G, mean=G_mean, std=G_std): return (G - mean) / std def add_scale(G, mean=G_mean, std=G_std): return G * std + mean # %% model = MechanisticAutoencoder( meal_size=len(MEAL_COVARIATES),
demographics_size=len(DEMOGRAPHICS_COVARIATES),
2
2023-11-14 18:10:58+00:00
4k
jpcadena/fastapi-boilerplate
app/utils/security/password.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 from datetime import datetime, timedelta, timezone from typing import Annotated, Any, Optional from fastapi import Depends from pydantic import EmailStr from app.config.config import get_auth_settings from app.config.db.auth_settings import AuthSettings from app.utils.security.jwt import decode_jwt, encode_jwt
2,093
""" A module for password in the app.utils.security package. """ logger: logging.Logger = logging.getLogger(__name__) def generate_password_reset_payload( email: EmailStr, auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], ) -> dict[str, Any]: """ Generate a password reset payload :param email: The email to generate the reset token for :type email: EmailStr :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :return: The payload to be used :rtype: dict[str, Any] """ now: datetime = datetime.now(timezone.utc) expires: datetime = now + timedelta( hours=auth_settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS ) exp: float = expires.timestamp() payload: dict[str, Any] = { "iss": f"{auth_settings.SERVER_URL}", "exp": exp, "nbf": now, "sub": email, } logger.info("Payload generated for password") return payload def generate_password_reset_token( email: EmailStr, auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], ) -> str: """ Generate a password reset token for the given email address. :param email: The email to generate the reset token for :type email: EmailStr :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :return: The password reset token :rtype: str """ payload: dict[str, Any] = generate_password_reset_payload( email, auth_settings )
""" A module for password in the app.utils.security package. """ logger: logging.Logger = logging.getLogger(__name__) def generate_password_reset_payload( email: EmailStr, auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], ) -> dict[str, Any]: """ Generate a password reset payload :param email: The email to generate the reset token for :type email: EmailStr :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :return: The payload to be used :rtype: dict[str, Any] """ now: datetime = datetime.now(timezone.utc) expires: datetime = now + timedelta( hours=auth_settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS ) exp: float = expires.timestamp() payload: dict[str, Any] = { "iss": f"{auth_settings.SERVER_URL}", "exp": exp, "nbf": now, "sub": email, } logger.info("Payload generated for password") return payload def generate_password_reset_token( email: EmailStr, auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], ) -> str: """ Generate a password reset token for the given email address. :param email: The email to generate the reset token for :type email: EmailStr :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :return: The password reset token :rtype: str """ payload: dict[str, Any] = generate_password_reset_payload( email, auth_settings )
return encode_jwt(payload, auth_settings)
3
2023-11-17 00:32:32+00:00
4k
vitant-lang/CBAM-ASPP
utils/utils_fit.py
[ { "identifier": "CE_Loss", "path": "nets/deeplabv3_training.py", "snippet": "def CE_Loss(inputs, target, cls_weights, num_classes=21):\n n, c, h, w = inputs.size()\n nt, ht, wt = target.size()\n if h != ht and w != wt:\n inputs = F.interpolate(inputs, size=(ht, wt), mode=\"bilinear\", al...
import os import torch from nets.deeplabv3_training import (CE_Loss, Dice_loss, Focal_Loss, weights_init) from tqdm import tqdm from utils.utils import get_lr from utils.utils_metrics import f_score from torch.cuda.amp import autocast
1,796
def fit_one_epoch(model_train, model, loss_history, eval_callback, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, cuda, dice_loss, focal_loss, cls_weights, num_classes, \ fp16, scaler, save_period, save_dir, local_rank=0): total_loss = 0 total_f_score = 0 val_loss = 0 val_f_score = 0 if local_rank == 0: print('Start Train') pbar = tqdm(total=epoch_step,desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) model_train.train() for iteration, batch in enumerate(gen): if iteration >= epoch_step: break imgs, pngs, labels = batch with torch.no_grad(): weights = torch.from_numpy(cls_weights) if cuda: imgs = imgs.cuda(local_rank) pngs = pngs.cuda(local_rank) labels = labels.cuda(local_rank) weights = weights.cuda(local_rank) #----------------------# # 清零梯度 #----------------------# optimizer.zero_grad() if not fp16: #----------------------# # 前向传播 #----------------------# outputs = model_train(imgs) #----------------------# # 计算损失 #----------------------# if focal_loss: loss = Focal_Loss(outputs, pngs, weights, num_classes = num_classes) else: loss = CE_Loss(outputs, pngs, weights, num_classes = num_classes) if dice_loss: main_dice = Dice_loss(outputs, labels) loss = loss + main_dice with torch.no_grad(): #-------------------------------# # 计算f_score #-------------------------------#
def fit_one_epoch(model_train, model, loss_history, eval_callback, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, cuda, dice_loss, focal_loss, cls_weights, num_classes, \ fp16, scaler, save_period, save_dir, local_rank=0): total_loss = 0 total_f_score = 0 val_loss = 0 val_f_score = 0 if local_rank == 0: print('Start Train') pbar = tqdm(total=epoch_step,desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) model_train.train() for iteration, batch in enumerate(gen): if iteration >= epoch_step: break imgs, pngs, labels = batch with torch.no_grad(): weights = torch.from_numpy(cls_weights) if cuda: imgs = imgs.cuda(local_rank) pngs = pngs.cuda(local_rank) labels = labels.cuda(local_rank) weights = weights.cuda(local_rank) #----------------------# # 清零梯度 #----------------------# optimizer.zero_grad() if not fp16: #----------------------# # 前向传播 #----------------------# outputs = model_train(imgs) #----------------------# # 计算损失 #----------------------# if focal_loss: loss = Focal_Loss(outputs, pngs, weights, num_classes = num_classes) else: loss = CE_Loss(outputs, pngs, weights, num_classes = num_classes) if dice_loss: main_dice = Dice_loss(outputs, labels) loss = loss + main_dice with torch.no_grad(): #-------------------------------# # 计算f_score #-------------------------------#
_f_score = f_score(outputs, labels)
5
2023-11-17 13:25:28+00:00
4k
JiNanPiWang/apple_health_export_gpx_add_heartrate
src/sport_type_getter.py
[ { "identifier": "WORKOUT_ROUTES", "path": "config/paths.py", "snippet": "WORKOUT_ROUTES = os.path.join(PROJECT_ROOT, 'apple_health_export', 'workout-routes')" }, { "identifier": "ExportXmlParser", "path": "src/export_xml_parser.py", "snippet": "class ExportXmlParser:\n def __init__(se...
import os from config.paths import WORKOUT_ROUTES from .export_xml_parser import ExportXmlParser from config.activity_types import type_trans from datetime import datetime, timezone, timedelta from .gpx_data_point import GpxDataPoint
1,889
# 在export.xml中,有一个workout标签,如<Workout workoutActivityType="HKWorkoutActivityTypeWalking", # 可以通过它来判断运动类型 # 传入全部的workout-routes-run文件夹,返回一个字典,key为文件名,value为运动类型 # 文件名称使用endDate确定 def parse_date_to_filename(end_date): """ Parse date from end_date to file name like 2019-10-04 09:45:05 +0800 -> route_2019-10-04_9.45am.gpx 2019-10-03 16:05:59 +0800 -> route_2019-10-03_4.05pm.gpx :param end_date: str, later trans to datetime.datetime :return: file_name """ _date = GpxDataPoint(time=end_date).datetime_origin # 解读:小时使用%#I:12小时制,#使得小时前面不带0,使用%H则是24小时制;%p:AM/PM,lower(),将%P转为小写 parsed_date = _date.strftime("%Y-%m-%d_%#I.%M%p").lower() file_name = f'route_{parsed_date}.gpx' return file_name def parse_date_from_filename(file_name): """ Parse date from file name like route_2019-10-04_9.45am.gpx -> 2019-10-04 09:45:05 route_2019-10-03_4.05pm.gpx -> 2019-10-03 16:05:59 :param file_name: str :return: end_date """ _date = GpxDataPoint(time=file_name[6:-4]).datetime_origin # 格式转换为utc+8,datetime比较时间会自动转换到同一时区,所以无需考虑过多内容 _date = _date.replace(tzinfo=timezone(timedelta(hours=8))) return _date # 比如route_2019-10-23_12.08pm,但creation_date和end_date都是2019-10-23 12:09 def get_sport_type(files: list[str]): """ Get workout type for almost all files, exclude files that are uploaded via Strava, etc Apple Watch's record is fine :param files: list of uploading files :return: dict, key is file name, value is workout type """ print('Start getting workout type for all files') type_dict = {}
# 在export.xml中,有一个workout标签,如<Workout workoutActivityType="HKWorkoutActivityTypeWalking", # 可以通过它来判断运动类型 # 传入全部的workout-routes-run文件夹,返回一个字典,key为文件名,value为运动类型 # 文件名称使用endDate确定 def parse_date_to_filename(end_date): """ Parse date from end_date to file name like 2019-10-04 09:45:05 +0800 -> route_2019-10-04_9.45am.gpx 2019-10-03 16:05:59 +0800 -> route_2019-10-03_4.05pm.gpx :param end_date: str, later trans to datetime.datetime :return: file_name """ _date = GpxDataPoint(time=end_date).datetime_origin # 解读:小时使用%#I:12小时制,#使得小时前面不带0,使用%H则是24小时制;%p:AM/PM,lower(),将%P转为小写 parsed_date = _date.strftime("%Y-%m-%d_%#I.%M%p").lower() file_name = f'route_{parsed_date}.gpx' return file_name def parse_date_from_filename(file_name): """ Parse date from file name like route_2019-10-04_9.45am.gpx -> 2019-10-04 09:45:05 route_2019-10-03_4.05pm.gpx -> 2019-10-03 16:05:59 :param file_name: str :return: end_date """ _date = GpxDataPoint(time=file_name[6:-4]).datetime_origin # 格式转换为utc+8,datetime比较时间会自动转换到同一时区,所以无需考虑过多内容 _date = _date.replace(tzinfo=timezone(timedelta(hours=8))) return _date # 比如route_2019-10-23_12.08pm,但creation_date和end_date都是2019-10-23 12:09 def get_sport_type(files: list[str]): """ Get workout type for almost all files, exclude files that are uploaded via Strava, etc Apple Watch's record is fine :param files: list of uploading files :return: dict, key is file name, value is workout type """ print('Start getting workout type for all files') type_dict = {}
for record in ExportXmlParser().load_activities_type_in_dict(files):
1
2023-11-14 01:50:02+00:00
4k
dataaug/open-interpreter-free
interpreter/terminal_interface/terminal_interface.py
[ { "identifier": "check_for_package", "path": "interpreter/utils/check_for_package.py", "snippet": "def check_for_package(package):\n if package in sys.modules:\n return True\n elif (spec := importlib.util.find_spec(package)) is not None:\n try:\n module = importlib.util.mo...
import readline import base64 import random import re from ..utils.check_for_package import check_for_package from ..utils.display_markdown_message import display_markdown_message from ..utils.display_output import display_output from ..utils.find_image_path import find_image_path from ..utils.scan_code import scan_code from ..utils.system_debug_info import system_info from ..utils.truncate_output import truncate_output from .components.code_block import CodeBlock from .components.message_block import MessageBlock from .magic_commands import handle_magic_command
3,210
""" The terminal interface is just a view. Just handles the very top layer. If you were to build a frontend this would be a way to do it """ try: except ImportError: pass # Add examples to the readline history examples = [ "How many files are on my desktop?", "What time is it in Seattle?", "Make me a simple Pomodoro app.", "Open Chrome and go to YouTube.", ] # random.shuffle(examples) for example in examples: readline.add_history(example) def terminal_interface(interpreter, message): # Auto run and local don't display messages. # Probably worth abstracting this to something like "verbose_cli" at some point. if not interpreter.auto_run and not interpreter.local: interpreter_intro_message = [ "**Open Interpreter** will require approval before running code." ] if interpreter.safe_mode == "ask" or interpreter.safe_mode == "auto": if not check_for_package("semgrep"): interpreter_intro_message.append( f"**Safe Mode**: {interpreter.safe_mode}\n\n>Note: **Safe Mode** requires `semgrep` (`pip install semgrep`)" ) else: interpreter_intro_message.append("Use `interpreter -y` to bypass this.") interpreter_intro_message.append("Press `CTRL-C` to exit.") display_markdown_message("\n\n".join(interpreter_intro_message) + "\n") active_block = None if message: interactive = False else: interactive = True while True: try: if interactive: message = input("> ").strip() try: # This lets users hit the up arrow key for past messages readline.add_history(message) except: # If the user doesn't have readline (may be the case on windows), that's fine pass except KeyboardInterrupt: # Exit gracefully break if message.startswith("%") and interactive: handle_magic_command(interpreter, message) continue # Many users do this if message.strip() == "interpreter --local": print("Please press CTRL-C then run `interpreter --local`.") continue if True: ################## interpreter.vision: # Is the input a path to an image? Like they just dragged it into the terminal? image_path = find_image_path(message) ## If we found an image, add it to the message if image_path: if interpreter.debug_mode: print("Found image:", image_path) # Turn it into base64 with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode("utf-8") file_extension = image_path.split(".")[-1] message = { "role": "user", "message": message, "image": f"data:image/{file_extension};base64,{encoded_string}", } # Track if we've ran a code block. # We'll use this to determine if we should render a new code block, # In the event we get code -> output -> code again ran_code_block = False render_cursor = True try: for chunk in interpreter.chat(message, display=False, stream=True): if interpreter.debug_mode: print("Chunk in `terminal_interface`:", chunk) # Message if "message" in chunk: if active_block is None: active_block = MessageBlock() if active_block.type != "message": active_block.end() active_block = MessageBlock() active_block.message += chunk["message"] render_cursor = True # Code if "code" in chunk or "language" in chunk: if active_block is None:
""" The terminal interface is just a view. Just handles the very top layer. If you were to build a frontend this would be a way to do it """ try: except ImportError: pass # Add examples to the readline history examples = [ "How many files are on my desktop?", "What time is it in Seattle?", "Make me a simple Pomodoro app.", "Open Chrome and go to YouTube.", ] # random.shuffle(examples) for example in examples: readline.add_history(example) def terminal_interface(interpreter, message): # Auto run and local don't display messages. # Probably worth abstracting this to something like "verbose_cli" at some point. if not interpreter.auto_run and not interpreter.local: interpreter_intro_message = [ "**Open Interpreter** will require approval before running code." ] if interpreter.safe_mode == "ask" or interpreter.safe_mode == "auto": if not check_for_package("semgrep"): interpreter_intro_message.append( f"**Safe Mode**: {interpreter.safe_mode}\n\n>Note: **Safe Mode** requires `semgrep` (`pip install semgrep`)" ) else: interpreter_intro_message.append("Use `interpreter -y` to bypass this.") interpreter_intro_message.append("Press `CTRL-C` to exit.") display_markdown_message("\n\n".join(interpreter_intro_message) + "\n") active_block = None if message: interactive = False else: interactive = True while True: try: if interactive: message = input("> ").strip() try: # This lets users hit the up arrow key for past messages readline.add_history(message) except: # If the user doesn't have readline (may be the case on windows), that's fine pass except KeyboardInterrupt: # Exit gracefully break if message.startswith("%") and interactive: handle_magic_command(interpreter, message) continue # Many users do this if message.strip() == "interpreter --local": print("Please press CTRL-C then run `interpreter --local`.") continue if True: ################## interpreter.vision: # Is the input a path to an image? Like they just dragged it into the terminal? image_path = find_image_path(message) ## If we found an image, add it to the message if image_path: if interpreter.debug_mode: print("Found image:", image_path) # Turn it into base64 with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode("utf-8") file_extension = image_path.split(".")[-1] message = { "role": "user", "message": message, "image": f"data:image/{file_extension};base64,{encoded_string}", } # Track if we've ran a code block. # We'll use this to determine if we should render a new code block, # In the event we get code -> output -> code again ran_code_block = False render_cursor = True try: for chunk in interpreter.chat(message, display=False, stream=True): if interpreter.debug_mode: print("Chunk in `terminal_interface`:", chunk) # Message if "message" in chunk: if active_block is None: active_block = MessageBlock() if active_block.type != "message": active_block.end() active_block = MessageBlock() active_block.message += chunk["message"] render_cursor = True # Code if "code" in chunk or "language" in chunk: if active_block is None:
active_block = CodeBlock()
7
2023-11-16 03:10:42+00:00
4k
3dp-accelerometer/octoprint-accelerometer
octoprint_accelerometer/record_step_series.py
[ { "identifier": "RecordingEventType", "path": "octoprint_accelerometer/event_types.py", "snippet": "class RecordingEventType(IntEnum):\n \"\"\"\n Types that can be emitted by callback from the recording task.\n \"\"\"\n\n STARTING = 1\n \"processing: sane execution event\"\n PROCESSING...
import threading import time import traceback from logging import Logger from typing import List, Literal, Callable, Optional from typing import Tuple from octoprint.printer import PrinterInterface from py3dpaxxel.controller.api import ErrorFifoOverflow, ErrorUnknownResponse from py3dpaxxel.controller.constants import OutputDataRateFromHz from py3dpaxxel.sampling_tasks.exception_task_wrapper import ExceptionTaskWrapper from py3dpaxxel.sampling_tasks.steps_series_runner import SamplingStepsSeriesRunner from octoprint_accelerometer.event_types import RecordingEventType from octoprint_accelerometer.py3dpaxxel_octo import Py3dpAxxelOcto
2,998
@property def stop_frequency_hz(self) -> int: return self._stop_frequency_hz @stop_frequency_hz.setter def stop_frequency_hz(self, stop_frequency_hz: int): self._stop_frequency_hz = stop_frequency_hz @property def step_frequency_hz(self) -> int: return self._step_frequency_hz @step_frequency_hz.setter def step_frequency_hz(self, step_frequency_hz: int): self._step_frequency_hz = step_frequency_hz @property def start_zeta_em2(self) -> int: return self._start_zeta_em2 @start_zeta_em2.setter def start_zeta_em2(self, start_zeta_em2: int): self._start_zeta_em2 = start_zeta_em2 @property def stop_zeta_em2(self) -> int: return self._stop_zeta_em2 @stop_zeta_em2.setter def stop_zeta_em2(self, stop_zeta_em2: int): self._stop_zeta_em2 = stop_zeta_em2 @property def step_zeta_em2(self) -> int: return self._step_zeta_em2 @step_zeta_em2.setter def step_zeta_em2(self, step_zeta_em2: int): self._step_zeta_em2 = step_zeta_em2 @property def output_file_prefix(self) -> str: return self._output_file_prefix @output_file_prefix.setter def output_file_prefix(self, output_file_prefix: str): self._output_file_prefix = output_file_prefix @property def output_dir(self) -> str: return self._output_dir @output_dir.setter def output_dir(self, output_dir: str): self._output_dir = output_dir @property def do_dry_run(self) -> bool: return self._do_dry_run @do_dry_run.setter def do_dry_run(self, do_dry_run: bool): self._do_dry_run = do_dry_run def is_running(self) -> bool: return True if self._background_task is not None and self._background_task.is_alive() else False def task_execution_had_errors(self) -> bool: return self.controller_response_error or self.controller_response_error or self.unhandled_exception def _send_on_event_callback(self, event: RecordingEventType): if self.on_event_callback: self.on_event_callback(event) def _send_on_thread_event_callback(self, event: RecordingEventType): if event == RecordingEventType.PROCESSING_FINISHED: self._thread_stop_timestamp = time.time() if self.on_event_callback: self.on_event_callback(event) # TODO: force an early thread termination not by just terminating run(). # Reason: Thread.is_alive() takes up to 30 seconds after run() terminated # to report not-alive. This works but sounds like a bug though. if event in [RecordingEventType.PROCESSING_FINISHED, RecordingEventType.FIFO_OVERRUN, RecordingEventType.UNHANDLED_EXCEPTION, RecordingEventType.ABORTED]: self.logger.info("recording thread terminated") raise SystemExit() def stop(self) -> None: self._do_abort_flag.set() self._send_on_event_callback(RecordingEventType.ABORTING) if self._background_task: try: self._background_task.join() except RuntimeError as _e: self.logger.info("no running thread that can be stopped") self._background_task = None self._background_task_stop_timestamp = time.time() self._send_on_event_callback(RecordingEventType.ABORTED) def get_last_run_duration_s(self) -> Optional[float]: """ Returns the last known duration. Note: Whenever this method is called, make sure to assert that the thread is not running. This is-running check is skipped here on purpose. Normally the child thread is the caller itself. The call propagated indirectly through the plugin's callback that most likely called this method again. In that case the thread is always running. :return: the last known duration; None if unknown of thread is still running """ return None if not self._thread_stop_timestamp or not self._background_task_start_timestamp else self._thread_stop_timestamp - self._background_task_start_timestamp def run(self) -> None:
class RecordStepSeriesTask(Callable): """ Wrapper that handles callbacks on task finished. Meant to be run by :class:`threading.Thread`. """ def __init__(self, logger: Logger, runner: Callable, on_event_callback: Optional[Callable[[RecordingEventType.PROCESSING], None]]) -> None: self.logger: Logger = logger self.runner: Callable = runner self.on_event_callback: Optional[Callable[[RecordingEventType.PROCESSING], None]] = on_event_callback def __call__(self) -> None: try: ret = self.runner() if 0 == ret: self._send_on_event_callback(RecordingEventType.PROCESSING_FINISHED) elif -1 == ret: self._send_on_event_callback(RecordingEventType.ABORTED) else: self._send_on_event_callback(RecordingEventType.UNHANDLED_EXCEPTION) except ErrorFifoOverflow as e: self.logger.error("controller reported FiFo overrun") self.logger.error(str(e)) traceback.print_exception(e) self._send_on_event_callback(RecordingEventType.FIFO_OVERRUN) except ErrorUnknownResponse as e: self.logger.error("unknown response from controller") self.logger.error(str(e)) traceback.print_exception(e) self._send_on_event_callback(RecordingEventType.UNHANDLED_EXCEPTION) except Exception as e: self.logger.error("unknown controller API error") self.logger.error(str(e)) traceback.print_exception(e) self._send_on_event_callback(RecordingEventType.UNHANDLED_EXCEPTION) def _send_on_event_callback(self, event: RecordingEventType): if self.on_event_callback: self.on_event_callback(event) class RecordStepSeriesBackgroundTask: """ Task wrapper to catch exceptions when a task is run by :class:`threading.Thread` so that exceptions can be exposed to the parent thread. """ def __init__(self, logger: Logger, task: RecordStepSeriesTask) -> None: self.logger: Logger = logger self.task: RecordStepSeriesTask = task self.exception_wrapper: ExceptionTaskWrapper = ExceptionTaskWrapper(target=task) self.thread: threading.Thread = threading.Thread(name="recording_series", target=self.exception_wrapper) self.thread.daemon = True def is_alive(self): return self.thread.is_alive() def start(self) -> None: self.thread.start() def join(self) -> None: self.thread.join() class RecordStepSeriesRunner: """ Runner for moving printer, recording streams from accelerometer and saving to data to files. """ def __init__(self, logger: Logger, printer: PrinterInterface, controller_serial_device: str, on_event_callback: Optional[Callable[[RecordingEventType], None]], controller_record_timelapse_s: float, controller_decode_timeout_s: float, sensor_odr_hz: int, gcode_start_point_mm: Tuple[int, int, int], gcode_axis: List[Literal["x", "y", "z"]], gcode_distance_mm: int, gcode_step_count: int, gcode_sequence_count: int, start_frequency_hz: int, stop_frequency_hz: int, step_frequency_hz: int, start_zeta_em2: int, stop_zeta_em2: int, step_zeta_em2: int, output_file_prefix: str, output_dir: str, do_dry_run: bool, do_abort_flag: threading.Event = threading.Event()): self.controller_response_error: bool = False self.controller_fifo_overrun_error: bool = False self.unhandled_exception: bool = False self.logger: Logger = logger self.printer: PrinterInterface = printer self._controller_serial_device: str = controller_serial_device self.on_event_callback: Optional[Callable[[RecordingEventType], None]] = on_event_callback self._controller_record_timelapse_s: float = controller_record_timelapse_s self._controller_decode_timeout_s: float = controller_decode_timeout_s self._sensor_odr_hz: int = sensor_odr_hz self._gcode_start_point_mm: Tuple[int, int, int] = gcode_start_point_mm self._gcode_axis: List[Literal["x", "y", "z"]] = gcode_axis self._gcode_distance_mm: int = gcode_distance_mm self._gcode_step_count: int = gcode_step_count self._gcode_sequence_count: int = gcode_sequence_count self._start_frequency_hz: int = start_frequency_hz self._stop_frequency_hz: int = stop_frequency_hz self._step_frequency_hz: int = step_frequency_hz self._start_zeta_em2: int = start_zeta_em2 self._stop_zeta_em2: int = stop_zeta_em2 self._step_zeta_em2: int = step_zeta_em2 self._output_file_prefix: str = output_file_prefix self._output_dir: str = output_dir self._do_dry_run: bool = do_dry_run self._do_abort_flag: threading.Event = do_abort_flag self._background_task: Optional[RecordStepSeriesBackgroundTask] = None self._background_task_start_timestamp: Optional[float] = None self._background_task_stop_timestamp: Optional[float] = None @property def controller_serial_device(self) -> str: return self._controller_serial_device @controller_serial_device.setter def controller_serial_device(self, controller_serial_device: str): self._controller_serial_device = controller_serial_device @property def controller_record_timelapse_s(self) -> float: return self._controller_record_timelapse_s @controller_record_timelapse_s.setter def controller_record_timelapse_s(self, controller_record_timelapse_s: float): self._controller_record_timelapse_s = controller_record_timelapse_s @property def controller_decode_timeout_s(self) -> float: return self._controller_decode_timeout_s @controller_decode_timeout_s.setter def controller_decode_timeout_s(self, controller_decode_timeout_s: float): self._controller_decode_timeout_s = controller_decode_timeout_s @property def sensor_odr_hz(self) -> int: return self._sensor_odr_hz @sensor_odr_hz.setter def sensor_odr_hz(self, sensor_odr_hz: int): self._sensor_odr_hz = sensor_odr_hz @property def gcode_start_point_mm(self) -> Tuple[int, int, int]: return self._gcode_start_point_mm @gcode_start_point_mm.setter def gcode_start_point_mm(self, gcode_start_point_mm: Tuple[int, int, int]): self._gcode_start_point_mm = gcode_start_point_mm @property def gcode_axis(self) -> List[Literal["x", "y", "z"]]: return self._gcode_axis @gcode_axis.setter def gcode_axis(self, gcode_axis: List[Literal["x", "y", "z"]]): self._gcode_axis = gcode_axis @property def gcode_distance_mm(self) -> int: return self._gcode_distance_mm @gcode_distance_mm.setter def gcode_distance_mm(self, gcode_distance_mm: int): self._gcode_distance_mm = gcode_distance_mm @property def gcode_step_count(self) -> int: return self._gcode_step_count @gcode_step_count.setter def gcode_step_count(self, gcode_step_count: int): self._gcode_step_count = gcode_step_count @property def gcode_sequence_count(self) -> int: return self._gcode_sequence_count @gcode_sequence_count.setter def gcode_sequence_count(self, gcode_sequence_count: int): self._gcode_sequence_count = gcode_sequence_count @property def start_frequency_hz(self) -> int: return self._start_frequency_hz @start_frequency_hz.setter def start_frequency_hz(self, start_frequency_hz: int): self._start_frequency_hz = start_frequency_hz @property def stop_frequency_hz(self) -> int: return self._stop_frequency_hz @stop_frequency_hz.setter def stop_frequency_hz(self, stop_frequency_hz: int): self._stop_frequency_hz = stop_frequency_hz @property def step_frequency_hz(self) -> int: return self._step_frequency_hz @step_frequency_hz.setter def step_frequency_hz(self, step_frequency_hz: int): self._step_frequency_hz = step_frequency_hz @property def start_zeta_em2(self) -> int: return self._start_zeta_em2 @start_zeta_em2.setter def start_zeta_em2(self, start_zeta_em2: int): self._start_zeta_em2 = start_zeta_em2 @property def stop_zeta_em2(self) -> int: return self._stop_zeta_em2 @stop_zeta_em2.setter def stop_zeta_em2(self, stop_zeta_em2: int): self._stop_zeta_em2 = stop_zeta_em2 @property def step_zeta_em2(self) -> int: return self._step_zeta_em2 @step_zeta_em2.setter def step_zeta_em2(self, step_zeta_em2: int): self._step_zeta_em2 = step_zeta_em2 @property def output_file_prefix(self) -> str: return self._output_file_prefix @output_file_prefix.setter def output_file_prefix(self, output_file_prefix: str): self._output_file_prefix = output_file_prefix @property def output_dir(self) -> str: return self._output_dir @output_dir.setter def output_dir(self, output_dir: str): self._output_dir = output_dir @property def do_dry_run(self) -> bool: return self._do_dry_run @do_dry_run.setter def do_dry_run(self, do_dry_run: bool): self._do_dry_run = do_dry_run def is_running(self) -> bool: return True if self._background_task is not None and self._background_task.is_alive() else False def task_execution_had_errors(self) -> bool: return self.controller_response_error or self.controller_response_error or self.unhandled_exception def _send_on_event_callback(self, event: RecordingEventType): if self.on_event_callback: self.on_event_callback(event) def _send_on_thread_event_callback(self, event: RecordingEventType): if event == RecordingEventType.PROCESSING_FINISHED: self._thread_stop_timestamp = time.time() if self.on_event_callback: self.on_event_callback(event) # TODO: force an early thread termination not by just terminating run(). # Reason: Thread.is_alive() takes up to 30 seconds after run() terminated # to report not-alive. This works but sounds like a bug though. if event in [RecordingEventType.PROCESSING_FINISHED, RecordingEventType.FIFO_OVERRUN, RecordingEventType.UNHANDLED_EXCEPTION, RecordingEventType.ABORTED]: self.logger.info("recording thread terminated") raise SystemExit() def stop(self) -> None: self._do_abort_flag.set() self._send_on_event_callback(RecordingEventType.ABORTING) if self._background_task: try: self._background_task.join() except RuntimeError as _e: self.logger.info("no running thread that can be stopped") self._background_task = None self._background_task_stop_timestamp = time.time() self._send_on_event_callback(RecordingEventType.ABORTED) def get_last_run_duration_s(self) -> Optional[float]: """ Returns the last known duration. Note: Whenever this method is called, make sure to assert that the thread is not running. This is-running check is skipped here on purpose. Normally the child thread is the caller itself. The call propagated indirectly through the plugin's callback that most likely called this method again. In that case the thread is always running. :return: the last known duration; None if unknown of thread is still running """ return None if not self._thread_stop_timestamp or not self._background_task_start_timestamp else self._thread_stop_timestamp - self._background_task_start_timestamp def run(self) -> None:
py3dpaxxel_octo = Py3dpAxxelOcto(self.printer, self.logger)
1
2023-11-14 17:15:15+00:00
4k
itzshukla/STRANGER-SPAM
TheXSpam/alt_spam.py
[ { "identifier": "SUDO_USERS", "path": "config.py", "snippet": "SUDO_USERS = list(map(lambda x: int(x), getenv(\"SUDO_USERS\", \"6163010926\").split(\" \")))" }, { "identifier": "GROUP", "path": "data.py", "snippet": "GROUP = [-1001313291319, -1001777776331, -1001859846702, \"TheAltron\",...
import asyncio from random import choice from pyrogram.types import Message from pyrogram import filters, Client from config import SUDO_USERS from data import GROUP, PORM
2,024
@Client.on_message(filters.user(SUDO_USERS) & filters.command(['spam'], [".", "!", "/"])) async def altspam(client: Client, message: Message): alt = message.text.split(" ", 2) if len(alt) == 3: quantity, spam_text = int(alt[1]), alt[2] if message.reply_to_message: id = message.reply_to_message_id for _ in range(quantity): await message.reply_text(spam_text, reply_to_message_id=id) await asyncio.sleep(0.3) else: cid = message.chat.id for _ in range(quantity): await client.send_message(cid, spam_text) await asyncio.sleep(0.3) elif message.reply_to_message: spam_text = message.reply_to_message.text quantity = int(alt[1]) cid = message.chat.id for _ in range(quantity): await client.send_message(cid, spam_text) await asyncio.sleep(0.3) else: await message.reply_text(f"😈 **ᴜsᴀɢᴇ:**\n » !spam 13 Altron\n » !spam 13 <ʀᴇᴘʟʏ ᴛᴏ ᴛᴇxᴛ>\n\n**To do spam with replying to a user:**\n » !spam 13 Altron <ʀᴇᴘʟʏ ᴛᴏ ᴜꜱᴇʀ>") @Client.on_message(filters.command(["pspam", "pornspam"], [".", "/", "!"]) & filters.user(SUDO_USERS)) async def pspam(client: Client, message: Message): cid = message.chat.id if int(cid) in GROUP: await message.reply_text("» ꜱᴏʀʀʏ, ᴛʜɪꜱ ɪꜱ ᴀʟᴛʀᴏɴ ᴘʀᴏᴛᴇᴄᴛᴇᴅ ɢʀᴏᴜᴘ.") return altp = message.text.split(" ", 2) if len(altp) > 1: quantity = int(altp[1]) for _ in range(quantity):
@Client.on_message(filters.user(SUDO_USERS) & filters.command(['spam'], [".", "!", "/"])) async def altspam(client: Client, message: Message): alt = message.text.split(" ", 2) if len(alt) == 3: quantity, spam_text = int(alt[1]), alt[2] if message.reply_to_message: id = message.reply_to_message_id for _ in range(quantity): await message.reply_text(spam_text, reply_to_message_id=id) await asyncio.sleep(0.3) else: cid = message.chat.id for _ in range(quantity): await client.send_message(cid, spam_text) await asyncio.sleep(0.3) elif message.reply_to_message: spam_text = message.reply_to_message.text quantity = int(alt[1]) cid = message.chat.id for _ in range(quantity): await client.send_message(cid, spam_text) await asyncio.sleep(0.3) else: await message.reply_text(f"😈 **ᴜsᴀɢᴇ:**\n » !spam 13 Altron\n » !spam 13 <ʀᴇᴘʟʏ ᴛᴏ ᴛᴇxᴛ>\n\n**To do spam with replying to a user:**\n » !spam 13 Altron <ʀᴇᴘʟʏ ᴛᴏ ᴜꜱᴇʀ>") @Client.on_message(filters.command(["pspam", "pornspam"], [".", "/", "!"]) & filters.user(SUDO_USERS)) async def pspam(client: Client, message: Message): cid = message.chat.id if int(cid) in GROUP: await message.reply_text("» ꜱᴏʀʀʏ, ᴛʜɪꜱ ɪꜱ ᴀʟᴛʀᴏɴ ᴘʀᴏᴛᴇᴄᴛᴇᴅ ɢʀᴏᴜᴘ.") return altp = message.text.split(" ", 2) if len(altp) > 1: quantity = int(altp[1]) for _ in range(quantity):
porm = choice(PORM)
2
2023-11-14 05:14:00+00:00
4k
CmosWolf1/Code_implementation_for_paper_SKZC
diffusiondet/loss.py
[ { "identifier": "box_ops", "path": "diffusiondet/util/box_ops.py", "snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef masks_to_boxes(masks):" }, { "identifier": "get_world_size", "path": "diffusionde...
import torch import torch.nn.functional as F import torchvision.ops as ops from torch import nn from fvcore.nn import sigmoid_focal_loss_jit from .util import box_ops from .util.misc import get_world_size, is_dist_avail_and_initialized from .util.box_ops import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh, generalized_box_iou from detectron2.data.detection_utils import get_fed_loss_cls_weights
3,345
gt_classes = torch.argmax(target_classes_onehot, dim=-1) target_classes_onehot = target_classes_onehot[:, :, :-1] src_logits = src_logits.flatten(0, 1) target_classes_onehot = target_classes_onehot.flatten(0, 1) if self.use_focal: cls_loss = sigmoid_focal_loss_jit(src_logits, target_classes_onehot, alpha=self.focal_loss_alpha, gamma=self.focal_loss_gamma, reduction="none") else: cls_loss = F.binary_cross_entropy_with_logits(src_logits, target_classes_onehot, reduction="none") if self.use_fed_loss: K = self.num_classes N = src_logits.shape[0] fed_loss_classes = self.get_fed_loss_classes( gt_classes, num_fed_loss_classes=self.fed_loss_num_classes, num_classes=K, weight=self.fed_loss_cls_weights, ) fed_loss_classes_mask = fed_loss_classes.new_zeros(K + 1) fed_loss_classes_mask[fed_loss_classes] = 1 fed_loss_classes_mask = fed_loss_classes_mask[:K] weight = fed_loss_classes_mask.view(1, K).expand(N, K).float() loss_ce = torch.sum(cls_loss * weight) / num_boxes else: loss_ce = torch.sum(cls_loss) / num_boxes losses = {'loss_ce': loss_ce} else: raise NotImplementedError return losses def loss_boxes(self, outputs, targets, indices, num_boxes): """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size. """ assert 'pred_boxes' in outputs # idx = self._get_src_permutation_idx(indices) src_boxes = outputs['pred_boxes'] batch_size = len(targets) pred_box_list = [] pred_norm_box_list = [] tgt_box_list = [] tgt_box_xyxy_list = [] for batch_idx in range(batch_size): valid_query = indices[batch_idx][0] gt_multi_idx = indices[batch_idx][1] if len(gt_multi_idx) == 0: continue bz_image_whwh = targets[batch_idx]['image_size_xyxy'] bz_src_boxes = src_boxes[batch_idx] bz_target_boxes = targets[batch_idx]["boxes"] # normalized (cx, cy, w, h) bz_target_boxes_xyxy = targets[batch_idx]["boxes_xyxy"] # absolute (x1, y1, x2, y2) pred_box_list.append(bz_src_boxes[valid_query]) pred_norm_box_list.append(bz_src_boxes[valid_query] / bz_image_whwh) # normalize (x1, y1, x2, y2) tgt_box_list.append(bz_target_boxes[gt_multi_idx]) tgt_box_xyxy_list.append(bz_target_boxes_xyxy[gt_multi_idx]) if len(pred_box_list) != 0: src_boxes = torch.cat(pred_box_list) src_boxes_norm = torch.cat(pred_norm_box_list) # normalized (x1, y1, x2, y2) target_boxes = torch.cat(tgt_box_list) target_boxes_abs_xyxy = torch.cat(tgt_box_xyxy_list) num_boxes = src_boxes.shape[0] losses = {} # require normalized (x1, y1, x2, y2) loss_bbox = F.l1_loss(src_boxes_norm, box_cxcywh_to_xyxy(target_boxes), reduction='none') losses['loss_bbox'] = loss_bbox.sum() / num_boxes # loss_giou = giou_loss(box_ops.box_cxcywh_to_xyxy(src_boxes), box_ops.box_cxcywh_to_xyxy(target_boxes)) loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(src_boxes, target_boxes_abs_xyxy)) losses['loss_giou'] = loss_giou.sum() / num_boxes else: losses = {'loss_bbox': outputs['pred_boxes'].sum() * 0, 'loss_giou': outputs['pred_boxes'].sum() * 0} return losses def _get_src_permutation_idx(self, indices): # permute predictions following indices batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)]) src_idx = torch.cat([src for (src, _) in indices]) return batch_idx, src_idx def _get_tgt_permutation_idx(self, indices): # permute targets following indices batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)]) tgt_idx = torch.cat([tgt for (_, tgt) in indices]) return batch_idx, tgt_idx def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs): loss_map = { 'labels': self.loss_labels, 'boxes': self.loss_boxes, } assert loss in loss_map, f'do you really want to compute {loss} loss?' return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs) def forward(self, outputs, targets): """ This performs the loss computation. Parameters: outputs: dict of tensors, see the output specification of the model for the format targets: list of dicts, such that len(targets) == batch_size. The expected keys in each dict depends on the losses applied, see each loss' doc """ outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'} # Retrieve the matching between the outputs of the last layer and the targets indices, _ = self.matcher(outputs_without_aux, targets) # Compute the average number of target boxes accross all nodes, for normalization purposes num_boxes = sum(len(t["labels"]) for t in targets) num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device) if is_dist_avail_and_initialized(): torch.distributed.all_reduce(num_boxes)
# ======================================== # Modified by Shoufa Chen # ======================================== # Modified by Peize Sun, Rufeng Zhang # Contact: {sunpeize, cxrfzhang}@foxmail.com # # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ DiffusionDet model and criterion classes. """ class SetCriterionDynamicK(nn.Module): """ This class computes the loss for DiffusionDet. The process happens in two steps: 1) we compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and box) """ def __init__(self, cfg, num_classes, matcher, weight_dict, eos_coef, losses, use_focal): """ Create the criterion. Parameters: num_classes: number of object categories, omitting the special no-object category matcher: module able to compute a matching between targets and proposals weight_dict: dict containing as key the names of the losses and as values their relative weight. eos_coef: relative classification weight applied to the no-object category losses: list of all the losses to be applied. See get_loss for list of available losses. """ super().__init__() self.cfg = cfg self.num_classes = num_classes self.matcher = matcher self.weight_dict = weight_dict self.eos_coef = eos_coef self.losses = losses self.use_focal = use_focal self.use_fed_loss = cfg.MODEL.DiffusionDet.USE_FED_LOSS if self.use_fed_loss: self.fed_loss_num_classes = 50 cls_weight_fun = lambda: get_fed_loss_cls_weights(dataset_names=cfg.DATASETS.TRAIN, freq_weight_power=cfg.MODEL.ROI_BOX_HEAD.FED_LOSS_FREQ_WEIGHT_POWER) # noqa fed_loss_cls_weights = cls_weight_fun() assert ( len(fed_loss_cls_weights) == self.num_classes ), "Please check the provided fed_loss_cls_weights. Their size should match num_classes" self.register_buffer("fed_loss_cls_weights", fed_loss_cls_weights) if self.use_focal: self.focal_loss_alpha = cfg.MODEL.DiffusionDet.ALPHA self.focal_loss_gamma = cfg.MODEL.DiffusionDet.GAMMA else: empty_weight = torch.ones(self.num_classes + 1) empty_weight[-1] = self.eos_coef self.register_buffer('empty_weight', empty_weight) # copy-paste from https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/roi_heads/fast_rcnn.py#L356 def get_fed_loss_classes(self, gt_classes, num_fed_loss_classes, num_classes, weight): """ Args: gt_classes: a long tensor of shape R that contains the gt class label of each proposal. num_fed_loss_classes: minimum number of classes to keep when calculating federated loss. Will sample negative classes if number of unique gt_classes is smaller than this value. num_classes: number of foreground classes weight: probabilities used to sample negative classes Returns: Tensor: classes to keep when calculating the federated loss, including both unique gt classes and sampled negative classes. """ unique_gt_classes = torch.unique(gt_classes) prob = unique_gt_classes.new_ones(num_classes + 1).float() prob[-1] = 0 if len(unique_gt_classes) < num_fed_loss_classes: prob[:num_classes] = weight.float().clone() prob[unique_gt_classes] = 0 sampled_negative_classes = torch.multinomial( prob, num_fed_loss_classes - len(unique_gt_classes), replacement=False ) fed_loss_classes = torch.cat([unique_gt_classes, sampled_negative_classes]) else: fed_loss_classes = unique_gt_classes return fed_loss_classes def loss_labels(self, outputs, targets, indices, num_boxes, log=False): """Classification loss (NLL) targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes] """ assert 'pred_logits' in outputs src_logits = outputs['pred_logits'] batch_size = len(targets) # idx = self._get_src_permutation_idx(indices) # target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)]) target_classes = torch.full(src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device) src_logits_list = [] target_classes_o_list = [] # target_classes[idx] = target_classes_o for batch_idx in range(batch_size): valid_query = indices[batch_idx][0] gt_multi_idx = indices[batch_idx][1] if len(gt_multi_idx) == 0: continue bz_src_logits = src_logits[batch_idx] target_classes_o = targets[batch_idx]["labels"] target_classes[batch_idx, valid_query] = target_classes_o[gt_multi_idx] src_logits_list.append(bz_src_logits[valid_query]) target_classes_o_list.append(target_classes_o[gt_multi_idx]) if self.use_focal or self.use_fed_loss: num_boxes = torch.cat(target_classes_o_list).shape[0] if len(target_classes_o_list) != 0 else 1 target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], self.num_classes + 1], dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device) target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1) gt_classes = torch.argmax(target_classes_onehot, dim=-1) target_classes_onehot = target_classes_onehot[:, :, :-1] src_logits = src_logits.flatten(0, 1) target_classes_onehot = target_classes_onehot.flatten(0, 1) if self.use_focal: cls_loss = sigmoid_focal_loss_jit(src_logits, target_classes_onehot, alpha=self.focal_loss_alpha, gamma=self.focal_loss_gamma, reduction="none") else: cls_loss = F.binary_cross_entropy_with_logits(src_logits, target_classes_onehot, reduction="none") if self.use_fed_loss: K = self.num_classes N = src_logits.shape[0] fed_loss_classes = self.get_fed_loss_classes( gt_classes, num_fed_loss_classes=self.fed_loss_num_classes, num_classes=K, weight=self.fed_loss_cls_weights, ) fed_loss_classes_mask = fed_loss_classes.new_zeros(K + 1) fed_loss_classes_mask[fed_loss_classes] = 1 fed_loss_classes_mask = fed_loss_classes_mask[:K] weight = fed_loss_classes_mask.view(1, K).expand(N, K).float() loss_ce = torch.sum(cls_loss * weight) / num_boxes else: loss_ce = torch.sum(cls_loss) / num_boxes losses = {'loss_ce': loss_ce} else: raise NotImplementedError return losses def loss_boxes(self, outputs, targets, indices, num_boxes): """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size. """ assert 'pred_boxes' in outputs # idx = self._get_src_permutation_idx(indices) src_boxes = outputs['pred_boxes'] batch_size = len(targets) pred_box_list = [] pred_norm_box_list = [] tgt_box_list = [] tgt_box_xyxy_list = [] for batch_idx in range(batch_size): valid_query = indices[batch_idx][0] gt_multi_idx = indices[batch_idx][1] if len(gt_multi_idx) == 0: continue bz_image_whwh = targets[batch_idx]['image_size_xyxy'] bz_src_boxes = src_boxes[batch_idx] bz_target_boxes = targets[batch_idx]["boxes"] # normalized (cx, cy, w, h) bz_target_boxes_xyxy = targets[batch_idx]["boxes_xyxy"] # absolute (x1, y1, x2, y2) pred_box_list.append(bz_src_boxes[valid_query]) pred_norm_box_list.append(bz_src_boxes[valid_query] / bz_image_whwh) # normalize (x1, y1, x2, y2) tgt_box_list.append(bz_target_boxes[gt_multi_idx]) tgt_box_xyxy_list.append(bz_target_boxes_xyxy[gt_multi_idx]) if len(pred_box_list) != 0: src_boxes = torch.cat(pred_box_list) src_boxes_norm = torch.cat(pred_norm_box_list) # normalized (x1, y1, x2, y2) target_boxes = torch.cat(tgt_box_list) target_boxes_abs_xyxy = torch.cat(tgt_box_xyxy_list) num_boxes = src_boxes.shape[0] losses = {} # require normalized (x1, y1, x2, y2) loss_bbox = F.l1_loss(src_boxes_norm, box_cxcywh_to_xyxy(target_boxes), reduction='none') losses['loss_bbox'] = loss_bbox.sum() / num_boxes # loss_giou = giou_loss(box_ops.box_cxcywh_to_xyxy(src_boxes), box_ops.box_cxcywh_to_xyxy(target_boxes)) loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(src_boxes, target_boxes_abs_xyxy)) losses['loss_giou'] = loss_giou.sum() / num_boxes else: losses = {'loss_bbox': outputs['pred_boxes'].sum() * 0, 'loss_giou': outputs['pred_boxes'].sum() * 0} return losses def _get_src_permutation_idx(self, indices): # permute predictions following indices batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)]) src_idx = torch.cat([src for (src, _) in indices]) return batch_idx, src_idx def _get_tgt_permutation_idx(self, indices): # permute targets following indices batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)]) tgt_idx = torch.cat([tgt for (_, tgt) in indices]) return batch_idx, tgt_idx def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs): loss_map = { 'labels': self.loss_labels, 'boxes': self.loss_boxes, } assert loss in loss_map, f'do you really want to compute {loss} loss?' return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs) def forward(self, outputs, targets): """ This performs the loss computation. Parameters: outputs: dict of tensors, see the output specification of the model for the format targets: list of dicts, such that len(targets) == batch_size. The expected keys in each dict depends on the losses applied, see each loss' doc """ outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'} # Retrieve the matching between the outputs of the last layer and the targets indices, _ = self.matcher(outputs_without_aux, targets) # Compute the average number of target boxes accross all nodes, for normalization purposes num_boxes = sum(len(t["labels"]) for t in targets) num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device) if is_dist_avail_and_initialized(): torch.distributed.all_reduce(num_boxes)
num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
1
2023-11-17 02:37:37+00:00
4k
fg320/DEASC
deasc/tuning.py
[ { "identifier": "floris_reinitialise_atmosphere", "path": "deasc/utils_floris.py", "snippet": "def floris_reinitialise_atmosphere(wf_model, ws, wd, ti, shear):\n \"\"\"Modify atmopheric conditions and return FLORIS object, one ws and wd.\"\"\"\n wf_model.interface.reinitialize(wind_speeds=[ws],\n ...
import numpy as np import copy from scipy.optimize import minimize from turbo import Turbo1 from .utils_floris import ( floris_reinitialise_atmosphere, floris_calculate_turbine_power, floris_extract_object_dict, floris_extract_models_dict, floris_print_params, floris_extract_parameter, floris_param_change_object_dict, floris_param_change_object ) from .utils import ( norm, unnorm )
2,990
Define the wind farm conditions (yaw and atmospheric) of the higher-fidelity data. Args ---- yaw_angles_list : list of lists For each condition, list of turbines yaw_angles wind_directions_list: list For each condtion, wind direction wind_speeds_list: list For each condtion, wind speed turbulence_intensities_list: list For each condtion, wind direction wind_shear_list: list For each condtion, wind shear """ self.yaw_angles_list = yaw_angles_list self.wind_directions_list = wind_directions_list self.wind_speeds_list = wind_speeds_list self.turbulence_intensities_list = turbulence_intensities_list self.wind_shear_list = wind_shear_list self.tuning_conditions_received = True pass def tune_parameters(self): """ Tune specified parameters of a WfModel object. Requires higher-fidelity tuning data and the related conditions to be previously specified (refer to Tuning methods: tuning_data and tuning_conditions). Returns ------- wf_model_tuned: WfModel object WfModel object with parameters tuned wf_model_dict_opt: dictionary tuned WfModel object dictionary """ # Double check tuning data and conditions have been specified if self.tuning_data_received is False: err_msg = "Tuning data not specified. Use tuning_data method." raise Exception(err_msg) if self.tuning_conditions_received is False: err_msg = "Tuning conditions not specified. Use tuning_conditions method." raise Exception(err_msg) # Extract original wf_model object dictionary and print its parameters self.wf_model_dict_original = floris_extract_object_dict(self.wf_model) self.models_dict = floris_extract_models_dict(self.wf_model_dict_original) floris_print_params(self.wf_model_dict_original, self.models_dict, "Original model parameters") # Extract initial variable values and normalise them self.variables_init = self._wf_model_dict_to_variables(self.wf_model_dict_original, self.variables_class_list, self.variables_names_list) self.variables_init_norm = self._norm_variables(self.variables_init, self.variables_bounds_list) # Normalize variable bounds tmp = self.variables_bounds_list (self.variables_bounds_list_norm, self.variables_low_bound_list_norm, self.variables_upp_bound_list_norm) = self._norm_variables_bounds_lists(tmp) # Minimisation of error | Extract optimal variables self._tuning_optimizer() self.opt_variables = self._unnorm_variables(self.opt_variables_norm, self.variables_bounds_list) # Apply tuned parameters (opt_variables) to wf_model and print them self.wf_model_dict_opt = self._vars_to_wf_model_dict(self.wf_model_dict_original, self.variables_class_list, self.variables_names_list, self.opt_variables) self.wf_model = floris_param_change_object(self.wf_model, self.wf_model_dict_opt) floris_print_params(self.wf_model_dict_opt, self.models_dict, "Optimal model parameters") return self.wf_model, self.wf_model_dict_opt # %% Private methods def _wf_model_dict_to_variables(self, wf_model_dict, class_list, names_list): variables = [] for i in range(len(names_list)): variable = floris_extract_parameter(wf_model_dict, class_list[i], names_list[i]) variables.append(variable) return variables def _norm_variables(self, variables, variables_bounds_list): variables_norm = ([norm(variables[i], variables_bounds_list[i][0], variables_bounds_list[i][1]) for i in range(len(variables))]) return variables_norm def _norm_variables_bounds_lists(self, variables_bounds_list): variables_bounds_list_norm = [] variables_low_bound_list_norm = [] variables_upp_bound_list_norm = [] for i, variable_bounds in enumerate(variables_bounds_list): lower_bound_norm = norm(variable_bounds[0], variable_bounds[0], variable_bounds[1]) upper_bound_norm = norm(variable_bounds[1], variable_bounds[0], variable_bounds[1]) bound_norm_tuple = (lower_bound_norm, upper_bound_norm) variables_bounds_list_norm.append(bound_norm_tuple) variables_low_bound_list_norm.append(lower_bound_norm) variables_upp_bound_list_norm.append(upper_bound_norm) return (variables_bounds_list_norm, np.array(variables_low_bound_list_norm), np.array(variables_upp_bound_list_norm)) def _unnorm_variables(self, variables_norm, variables_bounds_list):
# Copyright 2023 Filippo Gori # 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. class Tuning: """ Parameter tuning class for a low-fidelity model, where one or more parameters are tuned to higher fidelity power measurements. In particular, the RMSE is minimised for single turbine power measurements for a single or the sum of multiple atmospheric conditions. The wind farm layout is assumed fixed. """ def __init__(self, wf_model, variables_class_list, variables_names_list, variables_bounds_list, obj_func_name='RMSE', opt_method='SLSQP', opt_options=None ): """ Args ---- wf_model : WfModel object (low-fidelity model) single WfModel object to tune variables_class_list: list of strings list of classes of parameters to tune, one per parameter variables_names_list : list of strings list of parameter names to tune variables_bounds_list : list of tuples list of parameter bounds, upper and lower limits for each parameter obj_func_name: string objective function. Default set to "RMSE" opt_method: string optimization method. Dafault set to "SLSQP" ("TURBO_1" also available) opt_options: dict optimizer options. Default set to None """ self.obj_func_dict = {'RMSE': self._tuning_rmse_function} self.opt_method_list = ["SLSQP", "TURBO_1"] self.opt_options_dict = {"SLSQP": {'maxiter': 100, 'disp': True, 'iprint': 2, 'ftol': 1e-12, 'eps': 0.1}, "TURBO_1": {"n_init": 2*len(variables_names_list), "max_evals": 100, "batch_size": 1, # 1 = Serial "verbose": True, "use_ard": True, "max_cholesky_size": 2000, "n_training_steps": 50, "min_cuda": 1024, "device": "cpu", "dtype": "float64"}} self.tuning_optimizer_dict = {'SLSQP': self._tuning_optimizer_scipy, 'TURBO_1': self._tuning_optimizer_turbo_1} self.wf_model = wf_model self.variables_class_list = variables_class_list self.variables_names_list = variables_names_list self.variables_bounds_list = variables_bounds_list self.obj_func_name = obj_func_name self.obj_func = self.obj_func_dict[self.obj_func_name] self.opt_method = opt_method if opt_options == None: self.opt_options = self.opt_options_dict[self.opt_method] else: self.opt_options = opt_options self._tuning_optimizer = self.tuning_optimizer_dict[self.opt_method] self.tuning_data_received = False self.tuning_conditions_received = False print("\nInitialised parameter tuning") print("%i parameters to tune" % (len(self.variables_names_list))) print("%s optimization method" % (self.opt_method)) def tuning_data(self, data_power_list): """ Provide training higher-fidelity data for parameter tuning. Limited to power of each turbine for each condition ('RMSE') Args ---- data_power_list : list of lists For each condition: list of turbines power output ('RMSE') """ self.tuning_data_power_list = data_power_list self.tuning_data_received = True pass def tuning_conditions(self, yaw_angles_list, wind_directions_list, wind_speeds_list, turbulence_intensities_list, wind_shear_list): """ Define the wind farm conditions (yaw and atmospheric) of the higher-fidelity data. Args ---- yaw_angles_list : list of lists For each condition, list of turbines yaw_angles wind_directions_list: list For each condtion, wind direction wind_speeds_list: list For each condtion, wind speed turbulence_intensities_list: list For each condtion, wind direction wind_shear_list: list For each condtion, wind shear """ self.yaw_angles_list = yaw_angles_list self.wind_directions_list = wind_directions_list self.wind_speeds_list = wind_speeds_list self.turbulence_intensities_list = turbulence_intensities_list self.wind_shear_list = wind_shear_list self.tuning_conditions_received = True pass def tune_parameters(self): """ Tune specified parameters of a WfModel object. Requires higher-fidelity tuning data and the related conditions to be previously specified (refer to Tuning methods: tuning_data and tuning_conditions). Returns ------- wf_model_tuned: WfModel object WfModel object with parameters tuned wf_model_dict_opt: dictionary tuned WfModel object dictionary """ # Double check tuning data and conditions have been specified if self.tuning_data_received is False: err_msg = "Tuning data not specified. Use tuning_data method." raise Exception(err_msg) if self.tuning_conditions_received is False: err_msg = "Tuning conditions not specified. Use tuning_conditions method." raise Exception(err_msg) # Extract original wf_model object dictionary and print its parameters self.wf_model_dict_original = floris_extract_object_dict(self.wf_model) self.models_dict = floris_extract_models_dict(self.wf_model_dict_original) floris_print_params(self.wf_model_dict_original, self.models_dict, "Original model parameters") # Extract initial variable values and normalise them self.variables_init = self._wf_model_dict_to_variables(self.wf_model_dict_original, self.variables_class_list, self.variables_names_list) self.variables_init_norm = self._norm_variables(self.variables_init, self.variables_bounds_list) # Normalize variable bounds tmp = self.variables_bounds_list (self.variables_bounds_list_norm, self.variables_low_bound_list_norm, self.variables_upp_bound_list_norm) = self._norm_variables_bounds_lists(tmp) # Minimisation of error | Extract optimal variables self._tuning_optimizer() self.opt_variables = self._unnorm_variables(self.opt_variables_norm, self.variables_bounds_list) # Apply tuned parameters (opt_variables) to wf_model and print them self.wf_model_dict_opt = self._vars_to_wf_model_dict(self.wf_model_dict_original, self.variables_class_list, self.variables_names_list, self.opt_variables) self.wf_model = floris_param_change_object(self.wf_model, self.wf_model_dict_opt) floris_print_params(self.wf_model_dict_opt, self.models_dict, "Optimal model parameters") return self.wf_model, self.wf_model_dict_opt # %% Private methods def _wf_model_dict_to_variables(self, wf_model_dict, class_list, names_list): variables = [] for i in range(len(names_list)): variable = floris_extract_parameter(wf_model_dict, class_list[i], names_list[i]) variables.append(variable) return variables def _norm_variables(self, variables, variables_bounds_list): variables_norm = ([norm(variables[i], variables_bounds_list[i][0], variables_bounds_list[i][1]) for i in range(len(variables))]) return variables_norm def _norm_variables_bounds_lists(self, variables_bounds_list): variables_bounds_list_norm = [] variables_low_bound_list_norm = [] variables_upp_bound_list_norm = [] for i, variable_bounds in enumerate(variables_bounds_list): lower_bound_norm = norm(variable_bounds[0], variable_bounds[0], variable_bounds[1]) upper_bound_norm = norm(variable_bounds[1], variable_bounds[0], variable_bounds[1]) bound_norm_tuple = (lower_bound_norm, upper_bound_norm) variables_bounds_list_norm.append(bound_norm_tuple) variables_low_bound_list_norm.append(lower_bound_norm) variables_upp_bound_list_norm.append(upper_bound_norm) return (variables_bounds_list_norm, np.array(variables_low_bound_list_norm), np.array(variables_upp_bound_list_norm)) def _unnorm_variables(self, variables_norm, variables_bounds_list):
variables = ([unnorm(variables_norm[i],
9
2023-11-10 18:13:27+00:00
4k
CPES-Power-and-Energy-Systems/interoperable-recommender-tso
energy_app/packages/forecast-api/forecast_api/dataset/DataClass.py
[ { "identifier": "construct_inputs_from_forecasts", "path": "energy_app/packages/forecast-api/forecast_api/dataset/construct_inputs_funcs.py", "snippet": "def construct_inputs_from_forecasts(df, inputs, variables):\n \"\"\"\n Appends the forecasts datasets to the inputs\n\n Args:\n df (:o...
import logging import warnings import numpy as np import pandas as pd from .construct_inputs_funcs import ( construct_inputs_from_forecasts, construct_inputs_from_lags, construct_inputs_from_season, ) from sklearn.preprocessing import (MinMaxScaler, MaxAbsScaler, RobustScaler, Normalizer, StandardScaler) from .normalization_funcs import DeTrendPoly from .CrossValidation import CrossValidation
3,343
def get_dataset(self): """ Returns the stored dataset Returns: :obj:`pd.DataFrame` """ return self.dataset @staticmethod def convert_to_timezone(dataframe, new_tz): """ Converts the index of a given pandas DataFrame to the specified new time zone Args: dataframe (:obj:`pd.DataFrame`): DataFrame to be converted new_tz (:obj:`str`): new timezone, see all available in http://stackoverflow.com/questions/13866926/python-pytz-list-of-timezones # noqa Returns: :obj:`pd.DataFrame` """ # all timezones: https://stackoverflow.com/questions/13866926/ # python-pytz-list-of-timezones logger.info("Changing index timezone to {}".format(new_tz)) aux = dataframe.copy() aux.index = aux.index.tz_convert(new_tz) return aux @staticmethod def assign_timezone(dataframe, new_tz): """ Assigns a timezone to the index of a given DataFrame To see all timezones available: `import pytz; pytz.all_timezones` Args: dataframe (:obj:`pd.DataFrame`): DataFrame to be localized new_tz (:obj:`str`): new timezone Returns: :obj:`pd.DataFrame` """ aux = dataframe.copy() aux.index = aux.index.tz_localize(new_tz) return aux def construct_inputs(self, forecasts=None, lags=None, season=None, infer_dst_lags=False): """ Creates the ``inputs`` dataset according to the forecasts available, seasonal variables (hour, day, etc) and lags of realized data (price_t-1, price_t-2, etc). \n For the ``lags`` a dictionary must be fed as an argument indicating which is: * the variable (i.e. `DA_price_pt`) * the type of lag (i.e. hour, week, month) * the lag itself, positive or negative (i.e. -1, -24, +1, +3) Available seasonal variables: * hour: ('hour', 'hour_sin', 'hour_cos') * day * doy * month: ('month', 'month_sin', 'month_cos') * week_day: ('week_day', 'week_day_sin', 'week_day_cos') * business_day Example: For predictors associated with seasonal patterns:: predictors_season = ['hour', 'day', 'month', 'week_day', 'business_day'] For predictors associated with forecasted variables:: predictors_forec = ['Iberian_load_forecast', 'Iberian_wind_forecast', 'Iberian_solar_pv_forecast', 'Iberian_solar_thermal_forecast'] For predictors associated with lagged variables:: predictors_lags = { 'DA_price_pt': [('hour', [-1, -2, -24, -48]), ('month', -1)], 'Iberian_load_real': ('hour', [-24, -48]), } Args: forecasts (:obj:`list` of :obj:`str`): list of forecast variables lags (:obj:`dic`): dictionary with multiple configurations: * {'variable': (lag_type, lags)} * {'variable': [(lag_type1, lags1), (lag_type2, lags2)]} * {'variable': (lag_type, [lag1, lag2, lag3])} season (:obj:`list` of :obj:`str`): list of seasonal variables infer_dst_lags (:obj:`bool`): Consider lags on DST tz Returns: :obj:`pd.DataFrame` """ # todo limit construct_inputs by period # if self.inputs is None: self.inputs = pd.DataFrame(index=self.dataset.index) if season: construct_inputs_from_season(self.inputs, season) if forecasts: construct_inputs_from_forecasts(self.dataset, self.inputs, forecasts) if lags:
logger = logging.getLogger(__name__) class DataClass: """ Class used to store the dataset used to perform forecasting and aggregate all relevant methods, such as: * Resampling * Time zone conversion * Inputs construction * Split into x and y by period * Normalization * Cross validation DataClass main attribute is the ``dataset``, which is a pandas DataFrame where all the relevant information is gathered. \n This data is provided by the user and later used to create the other relevant attribute: ``inputs``. \n The correct order to use :class:`~DataClass` is: \n * initialize class instance with the timezone to be used in the dataset index (which must be tz aware) :: df = DataClass(tz='Europe/Madrid') * assign a pandas DataFrame provided by user :meth:`~load_dataset`:: df.load_dataset(example_dataset) Args: timezone (:obj:`str`): timezone of the dataset index, according to: http://stackoverflow.com/questions/13866926/python-pytz-list-of-timezones Attributes: dataset (:obj:`pd.DataFrame`): pandas DataFrame where are stored all data. inputs (:obj:`pd.DataFrame`): initialized with `None` and later populated with the inputs created with :meth:`~forecast_api.dataset.DataClass.DataClass.construct_inputs`. """ def __init__(self, timezone): self.dataset = None self.inputs = None self.tz = timezone logger.debug('DataClass instance initiated') def resample_dataset(self, timeframe, how): """ Resamples the dataset index, given a timeframe and a method (`how`) Args: timeframe (:obj:`str`): H, D, etc... how (:obj:`str`): mean, sum, std, etc... """ self.dataset = getattr(self.dataset.resample(timeframe), how)() logger.info(f"Dataset resampled to timeframe: {timeframe} " f"by applying the {how}") def load_dataset(self, dataset): """ Assignees a user provided pandas DataFrame to the class. The DataFrame must have an index aware of time zone. Args: dataset (:obj:`pd.DataFrame`): DataFrame in pandas object """ assert isinstance(dataset, pd.DataFrame) \ or isinstance(dataset, pd.Series), \ 'Dataset must be a pandas DataFrame or Series object' assert isinstance(dataset.index, pd.DatetimeIndex), \ 'Dataset must have a datetime index' assert dataset.index.tz is not None, \ 'Index must have a tz, use DataClass.assign_timezone() to assign' if dataset.index.tz.__str__() != self.tz: dataset = self.convert_to_timezone(dataset, self.tz) assert dataset.index.tz.__str__() == self.tz, \ 'Index must have the same tz specified in DataClass.__init__()' self.dataset = dataset.copy() if self.dataset.index.freq is None: inferred_freq = pd.infer_freq(index=dataset.index) if inferred_freq is not None: warnings.warn( f"Index does not have a predefined frequency. " f"'{inferred_freq}' freq. inferred from dataset index.", category=UserWarning) self.dataset.index.freq = inferred_freq else: raise AttributeError( "Index does not have a predefined frequency and failed to " "infer a index frequency." "\nUse pandas.DataFrame.resample() method to resample " "data to a specific frequency before loading dataset. " "\nSee https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html for more details.") # noqa del dataset def get_dataset(self): """ Returns the stored dataset Returns: :obj:`pd.DataFrame` """ return self.dataset @staticmethod def convert_to_timezone(dataframe, new_tz): """ Converts the index of a given pandas DataFrame to the specified new time zone Args: dataframe (:obj:`pd.DataFrame`): DataFrame to be converted new_tz (:obj:`str`): new timezone, see all available in http://stackoverflow.com/questions/13866926/python-pytz-list-of-timezones # noqa Returns: :obj:`pd.DataFrame` """ # all timezones: https://stackoverflow.com/questions/13866926/ # python-pytz-list-of-timezones logger.info("Changing index timezone to {}".format(new_tz)) aux = dataframe.copy() aux.index = aux.index.tz_convert(new_tz) return aux @staticmethod def assign_timezone(dataframe, new_tz): """ Assigns a timezone to the index of a given DataFrame To see all timezones available: `import pytz; pytz.all_timezones` Args: dataframe (:obj:`pd.DataFrame`): DataFrame to be localized new_tz (:obj:`str`): new timezone Returns: :obj:`pd.DataFrame` """ aux = dataframe.copy() aux.index = aux.index.tz_localize(new_tz) return aux def construct_inputs(self, forecasts=None, lags=None, season=None, infer_dst_lags=False): """ Creates the ``inputs`` dataset according to the forecasts available, seasonal variables (hour, day, etc) and lags of realized data (price_t-1, price_t-2, etc). \n For the ``lags`` a dictionary must be fed as an argument indicating which is: * the variable (i.e. `DA_price_pt`) * the type of lag (i.e. hour, week, month) * the lag itself, positive or negative (i.e. -1, -24, +1, +3) Available seasonal variables: * hour: ('hour', 'hour_sin', 'hour_cos') * day * doy * month: ('month', 'month_sin', 'month_cos') * week_day: ('week_day', 'week_day_sin', 'week_day_cos') * business_day Example: For predictors associated with seasonal patterns:: predictors_season = ['hour', 'day', 'month', 'week_day', 'business_day'] For predictors associated with forecasted variables:: predictors_forec = ['Iberian_load_forecast', 'Iberian_wind_forecast', 'Iberian_solar_pv_forecast', 'Iberian_solar_thermal_forecast'] For predictors associated with lagged variables:: predictors_lags = { 'DA_price_pt': [('hour', [-1, -2, -24, -48]), ('month', -1)], 'Iberian_load_real': ('hour', [-24, -48]), } Args: forecasts (:obj:`list` of :obj:`str`): list of forecast variables lags (:obj:`dic`): dictionary with multiple configurations: * {'variable': (lag_type, lags)} * {'variable': [(lag_type1, lags1), (lag_type2, lags2)]} * {'variable': (lag_type, [lag1, lag2, lag3])} season (:obj:`list` of :obj:`str`): list of seasonal variables infer_dst_lags (:obj:`bool`): Consider lags on DST tz Returns: :obj:`pd.DataFrame` """ # todo limit construct_inputs by period # if self.inputs is None: self.inputs = pd.DataFrame(index=self.dataset.index) if season: construct_inputs_from_season(self.inputs, season) if forecasts: construct_inputs_from_forecasts(self.dataset, self.inputs, forecasts) if lags:
construct_inputs_from_lags(self.dataset, self.inputs, lags,
1
2023-11-17 09:23:38+00:00
4k
PlaxtonFlarion/NexaFlow
nexaflow/classifier/keras_classifier.py
[ { "identifier": "toolbox", "path": "nexaflow/toolbox.py", "snippet": "def video_capture(video_path: str):\ndef video_jump(video_cap: cv2.VideoCapture, frame_id: int):\ndef compare_ssim(pic1: np.ndarray, pic2: np.ndarray) -> float:\ndef multi_compare_ssim(\n pic1_list: typing.List, pic2_list: typing.L...
import os import cv2 import typing import pathlib import numpy as np import tensorflow from loguru import logger from nexaflow import toolbox, constants from nexaflow.video import VideoFrame from nexaflow.classifier.base import BaseModelClassifier from tensorflow import keras
2,825
@property def follow_cv_size(self): return self.data_size[0], self.data_size[1] def clean_model(self): self._model = None def save_model(self, model_path: str, overwrite: bool = None): logger.debug(f"save model to {model_path}") # assert model file if os.path.isfile(model_path) and not overwrite: raise FileExistsError( f"model file {model_path} already existed, you can set `overwrite` True to cover it" ) # assert model data is not empty assert self._model, "model is empty" print(self._model.summary()) self._model.save_weights(model_path) def load_model(self, model_path: str, overwrite: bool = None): # logger.debug(f"load model from {model_path}") logger.info(f"加载Keras神经网络引擎 ...") # assert model file assert os.path.isfile(model_path), f"model file {model_path} not existed" # assert model data is empty if self._model and not overwrite: raise RuntimeError( f"model is not empty, you can set `overwrite` True to cover it" ) self._model = self.create_model() self._model.load_weights(model_path) def create_model(self) -> keras.Sequential: # logger.info(f"creating Keras sequential model") logger.info("Keras神经网络引擎创建图像分析模型 ...") if keras.backend.image_data_format() == "channels_first": input_shape = (1, *self.follow_keras_size) else: input_shape = (*self.follow_keras_size, 1) model = keras.Sequential() model.add(keras.layers.Conv2D(32, (3, 3), padding="same", input_shape=input_shape)) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Conv2D(64, (3, 3), padding="same")) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Conv2D(128, (3, 3), padding="same")) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(256, activation="relu")) model.add(keras.layers.Dropout(0.5)) model.add(keras.layers.Dense(self.MODEL_DENSE, activation="softmax")) model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) # logger.info("Keras model created") logger.info("Keras神经网络引擎加载完成,开始分析图像 ...") return model def train(self, data_path: str = None, *_, **__): def _data_verify(p: str): p = pathlib.Path(p) assert p.is_dir(), f"{p} is not a valid directory" number_of_dir = len([each for each in os.listdir(p) if (p / each).is_dir()]) assert ( number_of_dir > 1 ), f"dataset only contains one class. maybe some path errors happened: {p}?" assert number_of_dir <= self.MODEL_DENSE, ( f"dataset has {number_of_dir} classes (more than " + str(self.MODEL_DENSE) + ")" ) _data_verify(data_path) if not self._model: self._model = self.create_model() datagen = keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 16, shear_range=0.2, zoom_range=0.2, validation_split=0.33, horizontal_flip=True # 水平翻转增强 ) train_generator = datagen.flow_from_directory( data_path, target_size=self.follow_keras_size, batch_size=self.batch_size, color_mode="grayscale", class_mode="sparse", subset="training", ) validation_generator = datagen.flow_from_directory( data_path, target_size=self.follow_keras_size, batch_size=self.batch_size, color_mode="grayscale", class_mode="sparse", subset="validation", ) self._model.fit( train_generator, epochs=self.epochs, validation_data=validation_generator, ) logger.debug("train finished") def predict(self, pic_path: str, *args, **kwargs) -> str:
try: os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' except ImportError: raise ImportError("KerasClassifier requires tensorflow. install it first.") class KerasClassifier(BaseModelClassifier): UNKNOWN_STAGE_NAME = constants.UNKNOWN_STAGE_FLAG MODEL_DENSE = 6 def __init__( self, score_threshold: float = None, data_size: typing.Sequence[int] = None, nb_train_samples: int = None, nb_validation_samples: int = None, epochs: int = None, batch_size: int = None, *_, **__, ): super(KerasClassifier, self).__init__(*_, **__) # 模型 self._model: typing.Optional[keras.Sequential] = None # 配置 self.score_threshold: float = score_threshold or 0.0 self.data_size: typing.Sequence[int] = data_size or (200, 200) self.nb_train_samples: int = nb_train_samples or 64 self.nb_validation_samples: int = nb_validation_samples or 64 self.epochs: int = epochs or 20 self.batch_size: int = batch_size or 4 # logger.debug(f"score threshold: {self.score_threshold}") # logger.debug(f"data size: {self.data_size}") # logger.debug(f"nb train samples: {self.nb_train_samples}") # logger.debug(f"nb validation samples: {self.nb_validation_samples}") # logger.debug(f"epochs: {self.epochs}") # logger.debug(f"batch size: {self.batch_size}") @property def follow_keras_size(self): return self.data_size[1], self.data_size[0] @property def follow_cv_size(self): return self.data_size[0], self.data_size[1] def clean_model(self): self._model = None def save_model(self, model_path: str, overwrite: bool = None): logger.debug(f"save model to {model_path}") # assert model file if os.path.isfile(model_path) and not overwrite: raise FileExistsError( f"model file {model_path} already existed, you can set `overwrite` True to cover it" ) # assert model data is not empty assert self._model, "model is empty" print(self._model.summary()) self._model.save_weights(model_path) def load_model(self, model_path: str, overwrite: bool = None): # logger.debug(f"load model from {model_path}") logger.info(f"加载Keras神经网络引擎 ...") # assert model file assert os.path.isfile(model_path), f"model file {model_path} not existed" # assert model data is empty if self._model and not overwrite: raise RuntimeError( f"model is not empty, you can set `overwrite` True to cover it" ) self._model = self.create_model() self._model.load_weights(model_path) def create_model(self) -> keras.Sequential: # logger.info(f"creating Keras sequential model") logger.info("Keras神经网络引擎创建图像分析模型 ...") if keras.backend.image_data_format() == "channels_first": input_shape = (1, *self.follow_keras_size) else: input_shape = (*self.follow_keras_size, 1) model = keras.Sequential() model.add(keras.layers.Conv2D(32, (3, 3), padding="same", input_shape=input_shape)) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Conv2D(64, (3, 3), padding="same")) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Conv2D(128, (3, 3), padding="same")) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(256, activation="relu")) model.add(keras.layers.Dropout(0.5)) model.add(keras.layers.Dense(self.MODEL_DENSE, activation="softmax")) model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) # logger.info("Keras model created") logger.info("Keras神经网络引擎加载完成,开始分析图像 ...") return model def train(self, data_path: str = None, *_, **__): def _data_verify(p: str): p = pathlib.Path(p) assert p.is_dir(), f"{p} is not a valid directory" number_of_dir = len([each for each in os.listdir(p) if (p / each).is_dir()]) assert ( number_of_dir > 1 ), f"dataset only contains one class. maybe some path errors happened: {p}?" assert number_of_dir <= self.MODEL_DENSE, ( f"dataset has {number_of_dir} classes (more than " + str(self.MODEL_DENSE) + ")" ) _data_verify(data_path) if not self._model: self._model = self.create_model() datagen = keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 16, shear_range=0.2, zoom_range=0.2, validation_split=0.33, horizontal_flip=True # 水平翻转增强 ) train_generator = datagen.flow_from_directory( data_path, target_size=self.follow_keras_size, batch_size=self.batch_size, color_mode="grayscale", class_mode="sparse", subset="training", ) validation_generator = datagen.flow_from_directory( data_path, target_size=self.follow_keras_size, batch_size=self.batch_size, color_mode="grayscale", class_mode="sparse", subset="validation", ) self._model.fit( train_generator, epochs=self.epochs, validation_data=validation_generator, ) logger.debug("train finished") def predict(self, pic_path: str, *args, **kwargs) -> str:
pic_object = toolbox.imread(pic_path)
0
2023-11-13 05:27:34+00:00
4k
OpenBMB/XAgent
XAgent/agent/reflect_agent/agent.py
[ { "identifier": "BaseAgent", "path": "XAgent/agent/base_agent.py", "snippet": "class BaseAgent(metaclass=abc.ABCMeta):\n \"\"\"\n The BaseAgent class abstracts the essential attributes and methods for classes,\n which inherit it. It is a metaclass of the Abstract Base Class (abc module).\n\n ...
from typing import List from XAgent.agent.base_agent import BaseAgent from XAgent.utils import RequiredAbilities from XAgent.message_history import Message
1,998
class ReflectAgent(BaseAgent): """This ReflectAgent class extends the BaseAgent class. It primarily has the ability of reflection which means it can reflect upon the chat or dialogue and generate responses based on the messages received. Attributes: abilities (set): Required abilities for the agent, namely reflection in this case. """ abilities = set([RequiredAbilities.reflection]) def parse( self, placeholders: dict = {}, arguments:dict = None, functions=None, function_call=None, stop=None,
class ReflectAgent(BaseAgent): """This ReflectAgent class extends the BaseAgent class. It primarily has the ability of reflection which means it can reflect upon the chat or dialogue and generate responses based on the messages received. Attributes: abilities (set): Required abilities for the agent, namely reflection in this case. """ abilities = set([RequiredAbilities.reflection]) def parse( self, placeholders: dict = {}, arguments:dict = None, functions=None, function_call=None, stop=None,
additional_messages: List[Message] = [],
2
2023-10-16 03:44:57+00:00
4k
pytorch-labs/gpt-fast
tp.py
[ { "identifier": "Attention", "path": "model.py", "snippet": "class Attention(nn.Module):\n def __init__(self, config: ModelArgs):\n super().__init__()\n assert config.dim % config.n_head == 0\n\n total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim\n ...
import os import torch import torch.distributed as dist from typing import List, Optional from torch import nn from torch.distributed import _functional_collectives as funcol from model import Attention, FeedForward, Transformer from quantize import WeightOnlyInt4Linear
2,336
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. def _get_rank() -> int: return int(os.environ.get("LOCAL_RANK", "0")) def is_local(): return _get_rank() == 0 def local_break(): if is_local(): breakpoint() dist.barrier() def _get_world_size() -> int: return int(os.environ.get("LOCAL_WORLD_SIZE", "1")) def maybe_init_dist() -> Optional[int]: try: # provided by torchrun rank = _get_rank() world_size = _get_world_size() if world_size < 2: # too few gpus to parallelize, tp is no-op return None except KeyError: # not run via torchrun, no-op return None torch.cuda.set_device(rank) dist.init_process_group(backend="nccl", rank=rank, world_size=world_size) return rank def _apply_tp_linear(linear: nn.Linear, style: str, weight_splits: List[int] = []) -> None: rank = _get_rank() world_size = _get_world_size() # Linear's weight matrix is transposed, and is of shape # (linear.out_features, linear.in_features) dim_lookup = { "colwise": (0, "out_features"), "rowwise": (1, "in_features") } assert style in dim_lookup shard_dim, size_attr = dim_lookup[style] # ensure we can shard evenly assert getattr(linear, size_attr) % world_size == 0 def shard(x, dim): assert x.size(dim=dim) % world_size == 0 return torch.tensor_split(x, world_size, dim=dim)[rank] def shard_qkv(qkv, dim, weight_splits): q, k, v = qkv.split(weight_splits, dim=dim) q = shard(q, dim) k = shard(k, dim) v = shard(v, dim) return torch.cat((q,k,v), dim=dim) # shard if weight_splits: # attention assert len(weight_splits) == 3
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. def _get_rank() -> int: return int(os.environ.get("LOCAL_RANK", "0")) def is_local(): return _get_rank() == 0 def local_break(): if is_local(): breakpoint() dist.barrier() def _get_world_size() -> int: return int(os.environ.get("LOCAL_WORLD_SIZE", "1")) def maybe_init_dist() -> Optional[int]: try: # provided by torchrun rank = _get_rank() world_size = _get_world_size() if world_size < 2: # too few gpus to parallelize, tp is no-op return None except KeyError: # not run via torchrun, no-op return None torch.cuda.set_device(rank) dist.init_process_group(backend="nccl", rank=rank, world_size=world_size) return rank def _apply_tp_linear(linear: nn.Linear, style: str, weight_splits: List[int] = []) -> None: rank = _get_rank() world_size = _get_world_size() # Linear's weight matrix is transposed, and is of shape # (linear.out_features, linear.in_features) dim_lookup = { "colwise": (0, "out_features"), "rowwise": (1, "in_features") } assert style in dim_lookup shard_dim, size_attr = dim_lookup[style] # ensure we can shard evenly assert getattr(linear, size_attr) % world_size == 0 def shard(x, dim): assert x.size(dim=dim) % world_size == 0 return torch.tensor_split(x, world_size, dim=dim)[rank] def shard_qkv(qkv, dim, weight_splits): q, k, v = qkv.split(weight_splits, dim=dim) q = shard(q, dim) k = shard(k, dim) v = shard(v, dim) return torch.cat((q,k,v), dim=dim) # shard if weight_splits: # attention assert len(weight_splits) == 3
if isinstance(linear, WeightOnlyInt4Linear):
3
2023-10-17 05:30:32+00:00
4k
PKU-YuanGroup/Video-LLaVA
llava/eval/video/run_inference_benchmark_general.py
[ { "identifier": "get_model_output", "path": "llava/eval/video/run_inference_video_qa.py", "snippet": "def get_model_output(model, video_processor, tokenizer, video, qs, args):\n if model.config.mm_use_x_start_end:\n qs = DEFAULT_X_START_TOKEN['VIDEO'] + DEFAULT_X_TOKEN['VIDEO'] + DEFAULT_X_END...
import os import argparse import json from tqdm import tqdm from llava.eval.video.run_inference_video_qa import get_model_output from llava.mm_utils import get_model_name_from_path from llava.model.builder import load_pretrained_model
3,062
# from video_chatgpt.eval.model_utils import initialize_model, load_video # from video_chatgpt.inference import video_chatgpt_infer def parse_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser() # Define the command-line arguments parser.add_argument('--model_path', help='', required=True) parser.add_argument('--cache_dir', help='', required=True) parser.add_argument('--video_dir', help='Directory containing video files.', required=True) parser.add_argument('--gt_file', help='Path to the ground truth file.', required=True) parser.add_argument('--output_dir', help='Directory to save the model results JSON.', required=True) parser.add_argument('--output_name', help='Name of the file for storing results JSON.', required=True) # parser.add_argument("--model-name", type=str, required=True) parser.add_argument("--device", type=str, required=False, default='cuda:0') parser.add_argument('--model_base', help='', default=None, type=str, required=False) parser.add_argument("--model_max_length", type=int, required=False, default=2048) # parser.add_argument("--conv-mode", type=str, required=False, default='video-chatgpt_v1') # parser.add_argument("--projection_path", type=str, required=True) return parser.parse_args() def run_inference(args): """ Run inference on a set of video files using the provided model. Args: args: Command-line arguments. """# Initialize the model model_name = get_model_name_from_path(args.model_path)
# from video_chatgpt.eval.model_utils import initialize_model, load_video # from video_chatgpt.inference import video_chatgpt_infer def parse_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser() # Define the command-line arguments parser.add_argument('--model_path', help='', required=True) parser.add_argument('--cache_dir', help='', required=True) parser.add_argument('--video_dir', help='Directory containing video files.', required=True) parser.add_argument('--gt_file', help='Path to the ground truth file.', required=True) parser.add_argument('--output_dir', help='Directory to save the model results JSON.', required=True) parser.add_argument('--output_name', help='Name of the file for storing results JSON.', required=True) # parser.add_argument("--model-name", type=str, required=True) parser.add_argument("--device", type=str, required=False, default='cuda:0') parser.add_argument('--model_base', help='', default=None, type=str, required=False) parser.add_argument("--model_max_length", type=int, required=False, default=2048) # parser.add_argument("--conv-mode", type=str, required=False, default='video-chatgpt_v1') # parser.add_argument("--projection_path", type=str, required=True) return parser.parse_args() def run_inference(args): """ Run inference on a set of video files using the provided model. Args: args: Command-line arguments. """# Initialize the model model_name = get_model_name_from_path(args.model_path)
tokenizer, model, processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name)
2
2023-10-23 05:43:54+00:00
4k
deepseek-ai/DreamCraft3D
threestudio/models/renderers/nvdiff_rasterizer.py
[ { "identifier": "BaseBackground", "path": "threestudio/models/background/base.py", "snippet": "class BaseBackground(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n def configure(self):\n pass\n\n def forward(self, dirs: Float[Tensor, \...
from dataclasses import dataclass from threestudio.models.background.base import BaseBackground from threestudio.models.geometry.base import BaseImplicitGeometry from threestudio.models.materials.base import BaseMaterial from threestudio.models.renderers.base import Rasterizer, VolumeRenderer from threestudio.utils.misc import get_device from threestudio.utils.rasterize import NVDiffRasterizerContext from threestudio.utils.typing import * import nerfacc import torch import torch.nn.functional as F import threestudio
2,751
@threestudio.register("nvdiff-rasterizer") class NVDiffRasterizer(Rasterizer): @dataclass class Config(VolumeRenderer.Config): context_type: str = "gl" cfg: Config def configure( self, geometry: BaseImplicitGeometry, material: BaseMaterial, background: BaseBackground, ) -> None: super().configure(geometry, material, background)
@threestudio.register("nvdiff-rasterizer") class NVDiffRasterizer(Rasterizer): @dataclass class Config(VolumeRenderer.Config): context_type: str = "gl" cfg: Config def configure( self, geometry: BaseImplicitGeometry, material: BaseMaterial, background: BaseBackground, ) -> None: super().configure(geometry, material, background)
self.ctx = NVDiffRasterizerContext(self.cfg.context_type, get_device())
6
2023-10-23 07:40:20+00:00
4k
YORG-AI/Open-Assistant
package/src/yorgassistant/core/nodes/code_runner/code_runner.py
[ { "identifier": "BaseNode", "path": "package/src/yorgassistant/core/nodes/base_node.py", "snippet": "class BaseNode(ABC):\n config: NodeConfig\n func_mapping: dict[str, Callable]\n\n def __init__(self):\n # initialize func_mapping\n self.func_mapping = {}\n avail_funcs = [\...
import ast from typing import Optional from ...nodes.base_node import BaseNode, NodeConfig from ...nodes.code_runner.code_runner_model import ( RunCodeInput, RunCodeFromFileInput, ) from ....utils.code_executor.python_process import PythonProcess from ....utils.code_executor.python_repl import PythonREPL
1,640
code_runner_config = { "name": "code_runner", "description": "A simple node that run python code.", "functions": { "run_code": "Run python code in string format.", "run_code_from_file": "Run python code in specific files.", }, } class CodeRunnerNode(BaseNode): config: NodeConfig = NodeConfig(**code_runner_config) pythonREPL: PythonREPL def __init__(self): super().__init__() self.pythonREPL = None # TODO: check if the input is valid def run_code(self, input: RunCodeInput): if self.pythonREPL is None: self.init_python_repl() return self.pythonREPL.run(input.code)
code_runner_config = { "name": "code_runner", "description": "A simple node that run python code.", "functions": { "run_code": "Run python code in string format.", "run_code_from_file": "Run python code in specific files.", }, } class CodeRunnerNode(BaseNode): config: NodeConfig = NodeConfig(**code_runner_config) pythonREPL: PythonREPL def __init__(self): super().__init__() self.pythonREPL = None # TODO: check if the input is valid def run_code(self, input: RunCodeInput): if self.pythonREPL is None: self.init_python_repl() return self.pythonREPL.run(input.code)
def run_code_from_file(self, input: RunCodeFromFileInput):
3
2023-10-24 15:15:48+00:00
4k
zju3dv/4K4D
easyvolcap/engine/config.py
[ { "identifier": "import_modules_from_strings", "path": "easyvolcap/engine/misc.py", "snippet": "def import_modules_from_strings(imports, allow_failed_imports=False):\n \"\"\"Import modules from the given list of strings.\n Args:\n imports (list | str | None): The given module names to be im...
import os import sys import ast import copy import uuid import types import shutil import platform import warnings import os.path as osp import memory_tempfile except: import tempfile if platform.system() == 'Windows': import regex as re # type: ignore else: import re # type: ignore from addict import Dict from pathlib import Path from copy import deepcopy from collections import abc from typing import Union, List from importlib import import_module from argparse import Action, ArgumentParser from yapf.yapflib.yapf_api import FormatCode from .misc import import_modules_from_strings from .path import check_file_exist from . import io from . import io
2,146
elif isinstance(v, dict): add_args(parser, v, prefix + k + '.') elif isinstance(v, abc.Iterable): parser.add_argument('--' + prefix + k, type=type(v[0]), nargs='+') else: print(f'cannot parse key {prefix + k} of type {type(v)}') return parser class Config: """A facility for config and config files. It supports common file formats as configs: python/json/yaml. The interface is the same as a dict object and also allows access config values as attributes. Example: >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) >>> cfg.a 1 >>> cfg.b {'b1': [0, 1]} >>> cfg.b.b1 [0, 1] >>> cfg = Config.fromfile('tests/data/config/a.py') >>> cfg.filename "/home/kchen/projects/mmcv/tests/data/config/a.py" >>> cfg.item4 'test' >>> cfg "Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: " "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}" """ @staticmethod def _validate_py_syntax(filename): with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows content = f.read() try: ast.parse(content) except SyntaxError as e: raise SyntaxError('There are syntax errors in config ' f'file {filename}: {e}') @staticmethod def _substitute_predefined_vars(filename, temp_config_name): file_dirname = osp.dirname(filename) file_basename = osp.basename(filename) file_basename_no_extension = osp.splitext(file_basename)[0] file_extname = osp.splitext(filename)[1] support_templates = dict( fileDirname=file_dirname, fileBasename=file_basename, fileBasenameNoExtension=file_basename_no_extension, fileExtname=file_extname) with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows config_file = f.read() for key, value in support_templates.items(): regexp = r'\{\{\s*' + str(key) + r'\s*\}\}' value = value.replace('\\', '/') config_file = re.sub(regexp, value, config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) @staticmethod def _pre_substitute_base_vars(filename, temp_config_name): """Substitute base variable placehoders to string, so that parsing would work.""" with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows config_file = f.read() base_var_dict = {} regexp = r'\{\{\s*' + BASE_KEY + r'\.([\w\.]+)\s*\}\}' base_vars = set(re.findall(regexp, config_file)) for base_var in base_vars: randstr = f'_{base_var}_{uuid.uuid4().hex.lower()[:6]}' base_var_dict[randstr] = base_var regexp = r'\{\{\s*' + BASE_KEY + r'\.' + base_var + r'\s*\}\}' config_file = re.sub(regexp, f'"{randstr}"', config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) return base_var_dict @staticmethod def _substitute_base_vars(cfg, base_var_dict, base_cfg): """Substitute variable strings to their actual values.""" cfg = copy.deepcopy(cfg) if isinstance(cfg, dict): for k, v in cfg.items(): if isinstance(v, str) and v in base_var_dict: new_v = base_cfg for new_k in base_var_dict[v].split('.'): new_v = new_v[new_k] cfg[k] = new_v elif isinstance(v, (list, tuple, dict)): cfg[k] = Config._substitute_base_vars( v, base_var_dict, base_cfg) elif isinstance(cfg, tuple): cfg = tuple( Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg) elif isinstance(cfg, list): cfg = [ Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg ] elif isinstance(cfg, str) and cfg in base_var_dict: new_v = base_cfg for new_k in base_var_dict[cfg].split('.'): new_v = new_v[new_k] cfg = new_v return cfg @staticmethod def _file2dict(filename, use_predefined_variables=True, extra_base_cfg_dict={}): filename = osp.abspath(osp.expanduser(filename))
# Copyright (c) OpenMMLab. All rights reserved. from __future__ import annotations try: tempfile = memory_tempfile.MemoryTempfile() with tempfile.TemporaryDirectory() as temp_config_dir: pass BASE_KEY = 'configs' DELETE_KEY = '_delete_' APPEND_KEY = '_append_' # append stuff at end of existing list DEPRECATION_KEY = '_deprecation_' RESERVED_KEYS = ['filename', 'text', 'pretty_text'] class WithoutKey: def __init__(self, key: Union[List, str], cfg: Config): self.key = key if isinstance(key, list) else [key] self.cfg = cfg self.static = dict() def __enter__(self): for k in self.key: if k in self.cfg: self.static[k] = self.cfg[k] del self.cfg._cfg_dict[k] def __exit__(self, exc_type=None, exc_value=None, traceback=None): for k in self.key: if k in self.static: self.cfg[k] = self.static[k] class ConfigDict(Dict): def __missing__(self, name): raise KeyError(name) def __getattr__(self, name): try: value = super().__getattr__(name) except KeyError: ex = AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'") except Exception as e: ex = e else: return value raise ex def add_args(parser, cfg, prefix=''): for k, v in cfg.items(): if isinstance(v, str): parser.add_argument('--' + prefix + k) elif isinstance(v, int): parser.add_argument('--' + prefix + k, type=int) elif isinstance(v, float): parser.add_argument('--' + prefix + k, type=float) elif isinstance(v, bool): parser.add_argument('--' + prefix + k, action='store_true') elif isinstance(v, dict): add_args(parser, v, prefix + k + '.') elif isinstance(v, abc.Iterable): parser.add_argument('--' + prefix + k, type=type(v[0]), nargs='+') else: print(f'cannot parse key {prefix + k} of type {type(v)}') return parser class Config: """A facility for config and config files. It supports common file formats as configs: python/json/yaml. The interface is the same as a dict object and also allows access config values as attributes. Example: >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) >>> cfg.a 1 >>> cfg.b {'b1': [0, 1]} >>> cfg.b.b1 [0, 1] >>> cfg = Config.fromfile('tests/data/config/a.py') >>> cfg.filename "/home/kchen/projects/mmcv/tests/data/config/a.py" >>> cfg.item4 'test' >>> cfg "Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: " "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}" """ @staticmethod def _validate_py_syntax(filename): with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows content = f.read() try: ast.parse(content) except SyntaxError as e: raise SyntaxError('There are syntax errors in config ' f'file {filename}: {e}') @staticmethod def _substitute_predefined_vars(filename, temp_config_name): file_dirname = osp.dirname(filename) file_basename = osp.basename(filename) file_basename_no_extension = osp.splitext(file_basename)[0] file_extname = osp.splitext(filename)[1] support_templates = dict( fileDirname=file_dirname, fileBasename=file_basename, fileBasenameNoExtension=file_basename_no_extension, fileExtname=file_extname) with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows config_file = f.read() for key, value in support_templates.items(): regexp = r'\{\{\s*' + str(key) + r'\s*\}\}' value = value.replace('\\', '/') config_file = re.sub(regexp, value, config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) @staticmethod def _pre_substitute_base_vars(filename, temp_config_name): """Substitute base variable placehoders to string, so that parsing would work.""" with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows config_file = f.read() base_var_dict = {} regexp = r'\{\{\s*' + BASE_KEY + r'\.([\w\.]+)\s*\}\}' base_vars = set(re.findall(regexp, config_file)) for base_var in base_vars: randstr = f'_{base_var}_{uuid.uuid4().hex.lower()[:6]}' base_var_dict[randstr] = base_var regexp = r'\{\{\s*' + BASE_KEY + r'\.' + base_var + r'\s*\}\}' config_file = re.sub(regexp, f'"{randstr}"', config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) return base_var_dict @staticmethod def _substitute_base_vars(cfg, base_var_dict, base_cfg): """Substitute variable strings to their actual values.""" cfg = copy.deepcopy(cfg) if isinstance(cfg, dict): for k, v in cfg.items(): if isinstance(v, str) and v in base_var_dict: new_v = base_cfg for new_k in base_var_dict[v].split('.'): new_v = new_v[new_k] cfg[k] = new_v elif isinstance(v, (list, tuple, dict)): cfg[k] = Config._substitute_base_vars( v, base_var_dict, base_cfg) elif isinstance(cfg, tuple): cfg = tuple( Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg) elif isinstance(cfg, list): cfg = [ Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg ] elif isinstance(cfg, str) and cfg in base_var_dict: new_v = base_cfg for new_k in base_var_dict[cfg].split('.'): new_v = new_v[new_k] cfg = new_v return cfg @staticmethod def _file2dict(filename, use_predefined_variables=True, extra_base_cfg_dict={}): filename = osp.abspath(osp.expanduser(filename))
check_file_exist(filename)
1
2023-10-17 04:48:46+00:00
4k