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 |
|---|---|---|---|---|---|---|---|---|---|---|
DLYuanGod/TinyGPT-V | minigpt4/processors/blip_processors.py | [
{
"identifier": "registry",
"path": "minigpt4/common/registry.py",
"snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_task(cls, name):\n def wrap(task_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def ... | import re
from minigpt4.common.registry import registry
from minigpt4.processors.base_processor import BaseProcessor
from minigpt4.processors.randaugment import RandomAugment
from omegaconf import OmegaConf
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode | 756 | """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
| """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
| class BlipImageBaseProcessor(BaseProcessor): | 1 | 2023-12-28 05:47:18+00:00 | 2k |
jianchang512/vocal-separate | start.py | [
{
"identifier": "cfg",
"path": "vocal/cfg.py",
"snippet": "LANG = \"en\" if locale.getdefaultlocale()[0].split('_')[0].lower() != 'zh' else \"zh\"\nROOT_DIR = os.getcwd()\nMODEL_DIR = os.path.join(ROOT_DIR, 'pretrained_models')\nSTATIC_DIR = os.path.join(ROOT_DIR, 'static')\nTMP_DIR = os.path.join(STATI... | import logging
import threading
import sys
import os
import subprocess
from flask import Flask, request, render_template, jsonify, send_from_directory
from gevent.pywsgi import WSGIServer, WSGIHandler,LoggingLogAdapter
from logging.handlers import RotatingFileHandler
from vocal import cfg, tool
from vocal.cfg import ROOT_DIR
from spleeter.separator import Separator | 795 |
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static',
template_folder=os.path.join(ROOT_DIR, 'templates'))
root_log = logging.getLogger() # Flask的根日志记录器
root_log.handlers = []
root_log.setLevel(logging.WARNING)
# 配置日志
app.logger.setLevel(logging.WARNING) # 设置日志级别为 INFO
# 创建 RotatingFileHandler 对象,设置写入的文件路径和大小限制
file_handler = RotatingFileHandler(os.path.join(ROOT_DIR, 'vocal.log'), maxBytes=1024 * 1024, backupCount=5)
# 创建日志的格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 设置文件处理器的级别和格式
file_handler.setLevel(logging.WARNING)
file_handler.setFormatter(formatter)
# 将文件处理器添加到日志记录器中
app.logger.addHandler(file_handler)
@app.route('/static/<path:filename>')
def static_files(filename):
return send_from_directory(app.config['STATIC_FOLDER'], filename)
@app.route('/')
def index():
return render_template("index.html",cuda=cfg.cuda, language=cfg.LANG,root_dir=ROOT_DIR.replace('\\', '/'))
# 上传音频
@app.route('/upload', methods=['POST'])
def upload():
try:
# 获取上传的文件
audio_file = request.files['audio']
# 如果是mp4
noextname, ext = os.path.splitext(audio_file.filename)
ext = ext.lower()
# 如果是视频,先分离
wav_file = os.path.join(cfg.TMP_DIR, f'{noextname}.wav')
if os.path.exists(wav_file) and os.path.getsize(wav_file) > 0:
return jsonify({'code': 0, 'msg': cfg.transobj['lang1'], "data": os.path.basename(wav_file)})
msg=""
if ext in ['.mp4', '.mov', '.avi', '.mkv', '.mpeg', '.mp3', '.flac']:
video_file = os.path.join(cfg.TMP_DIR, f'{noextname}{ext}')
audio_file.save(video_file)
params = [
"-i",
video_file,
]
if ext not in ['.mp3', '.flac']:
params.append('-vn')
params.append(wav_file)
|
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static',
template_folder=os.path.join(ROOT_DIR, 'templates'))
root_log = logging.getLogger() # Flask的根日志记录器
root_log.handlers = []
root_log.setLevel(logging.WARNING)
# 配置日志
app.logger.setLevel(logging.WARNING) # 设置日志级别为 INFO
# 创建 RotatingFileHandler 对象,设置写入的文件路径和大小限制
file_handler = RotatingFileHandler(os.path.join(ROOT_DIR, 'vocal.log'), maxBytes=1024 * 1024, backupCount=5)
# 创建日志的格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 设置文件处理器的级别和格式
file_handler.setLevel(logging.WARNING)
file_handler.setFormatter(formatter)
# 将文件处理器添加到日志记录器中
app.logger.addHandler(file_handler)
@app.route('/static/<path:filename>')
def static_files(filename):
return send_from_directory(app.config['STATIC_FOLDER'], filename)
@app.route('/')
def index():
return render_template("index.html",cuda=cfg.cuda, language=cfg.LANG,root_dir=ROOT_DIR.replace('\\', '/'))
# 上传音频
@app.route('/upload', methods=['POST'])
def upload():
try:
# 获取上传的文件
audio_file = request.files['audio']
# 如果是mp4
noextname, ext = os.path.splitext(audio_file.filename)
ext = ext.lower()
# 如果是视频,先分离
wav_file = os.path.join(cfg.TMP_DIR, f'{noextname}.wav')
if os.path.exists(wav_file) and os.path.getsize(wav_file) > 0:
return jsonify({'code': 0, 'msg': cfg.transobj['lang1'], "data": os.path.basename(wav_file)})
msg=""
if ext in ['.mp4', '.mov', '.avi', '.mkv', '.mpeg', '.mp3', '.flac']:
video_file = os.path.join(cfg.TMP_DIR, f'{noextname}{ext}')
audio_file.save(video_file)
params = [
"-i",
video_file,
]
if ext not in ['.mp3', '.flac']:
params.append('-vn')
params.append(wav_file) | rs = tool.runffmpeg(params) | 1 | 2023-12-26 06:20:35+00:00 | 2k |
ali-vilab/dreamtalk | core/networks/dynamic_fc_decoder.py | [
{
"identifier": "_get_activation_fn",
"path": "core/networks/transformer.py",
"snippet": "def _get_activation_fn(activation):\r\n \"\"\"Return an activation function given a string\"\"\"\r\n if activation == \"relu\":\r\n return F.relu\r\n if activation == \"gelu\":\r\n return F.g... | import torch.nn as nn
import torch
from core.networks.transformer import _get_activation_fn, _get_clones
from core.networks.dynamic_linear import DynamicLinear | 1,476 |
class DynamicFCDecoderLayer(nn.Module):
def __init__(
self,
d_model,
nhead,
d_style,
dynamic_K,
dynamic_ratio,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
# Implementation of Feedforward model
# self.linear1 = nn.Linear(d_model, dim_feedforward)
self.linear1 = DynamicLinear(d_model, dim_feedforward, d_style, K=dynamic_K, ratio=dynamic_ratio)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
# self.linear2 = DynamicLinear(dim_feedforward, d_model, d_style, K=dynamic_K, ratio=dynamic_ratio)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.norm3 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
self.normalize_before = normalize_before
def with_pos_embed(self, tensor, pos):
return tensor if pos is None else tensor + pos
def forward_post(
self,
tgt,
memory,
style,
tgt_mask=None,
memory_mask=None,
tgt_key_padding_mask=None,
memory_key_padding_mask=None,
pos=None,
query_pos=None,
):
# q = k = self.with_pos_embed(tgt, query_pos)
tgt2 = self.self_attn(tgt, tgt, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
tgt2 = self.multihead_attn(
query=tgt, key=memory, value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask
)[0]
tgt = tgt + self.dropout2(tgt2)
tgt = self.norm2(tgt)
# tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt, style))), style)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt, style))))
tgt = tgt + self.dropout3(tgt2)
tgt = self.norm3(tgt)
return tgt
# def forward_pre(
# self,
# tgt,
# memory,
# tgt_mask=None,
# memory_mask=None,
# tgt_key_padding_mask=None,
# memory_key_padding_mask=None,
# pos=None,
# query_pos=None,
# ):
# tgt2 = self.norm1(tgt)
# # q = k = self.with_pos_embed(tgt2, query_pos)
# tgt2 = self.self_attn(tgt2, tgt2, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
# tgt = tgt + self.dropout1(tgt2)
# tgt2 = self.norm2(tgt)
# tgt2 = self.multihead_attn(
# query=tgt2, key=memory, value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask
# )[0]
# tgt = tgt + self.dropout2(tgt2)
# tgt2 = self.norm3(tgt)
# tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
# tgt = tgt + self.dropout3(tgt2)
# return tgt
def forward(
self,
tgt,
memory,
style,
tgt_mask=None,
memory_mask=None,
tgt_key_padding_mask=None,
memory_key_padding_mask=None,
pos=None,
query_pos=None,
):
if self.normalize_before:
raise NotImplementedError
# return self.forward_pre(
# tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos
# )
return self.forward_post(
tgt, memory, style, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos
)
class DynamicFCDecoder(nn.Module):
def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
super().__init__()
|
class DynamicFCDecoderLayer(nn.Module):
def __init__(
self,
d_model,
nhead,
d_style,
dynamic_K,
dynamic_ratio,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
# Implementation of Feedforward model
# self.linear1 = nn.Linear(d_model, dim_feedforward)
self.linear1 = DynamicLinear(d_model, dim_feedforward, d_style, K=dynamic_K, ratio=dynamic_ratio)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
# self.linear2 = DynamicLinear(dim_feedforward, d_model, d_style, K=dynamic_K, ratio=dynamic_ratio)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.norm3 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
self.normalize_before = normalize_before
def with_pos_embed(self, tensor, pos):
return tensor if pos is None else tensor + pos
def forward_post(
self,
tgt,
memory,
style,
tgt_mask=None,
memory_mask=None,
tgt_key_padding_mask=None,
memory_key_padding_mask=None,
pos=None,
query_pos=None,
):
# q = k = self.with_pos_embed(tgt, query_pos)
tgt2 = self.self_attn(tgt, tgt, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
tgt2 = self.multihead_attn(
query=tgt, key=memory, value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask
)[0]
tgt = tgt + self.dropout2(tgt2)
tgt = self.norm2(tgt)
# tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt, style))), style)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt, style))))
tgt = tgt + self.dropout3(tgt2)
tgt = self.norm3(tgt)
return tgt
# def forward_pre(
# self,
# tgt,
# memory,
# tgt_mask=None,
# memory_mask=None,
# tgt_key_padding_mask=None,
# memory_key_padding_mask=None,
# pos=None,
# query_pos=None,
# ):
# tgt2 = self.norm1(tgt)
# # q = k = self.with_pos_embed(tgt2, query_pos)
# tgt2 = self.self_attn(tgt2, tgt2, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
# tgt = tgt + self.dropout1(tgt2)
# tgt2 = self.norm2(tgt)
# tgt2 = self.multihead_attn(
# query=tgt2, key=memory, value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask
# )[0]
# tgt = tgt + self.dropout2(tgt2)
# tgt2 = self.norm3(tgt)
# tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
# tgt = tgt + self.dropout3(tgt2)
# return tgt
def forward(
self,
tgt,
memory,
style,
tgt_mask=None,
memory_mask=None,
tgt_key_padding_mask=None,
memory_key_padding_mask=None,
pos=None,
query_pos=None,
):
if self.normalize_before:
raise NotImplementedError
# return self.forward_pre(
# tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos
# )
return self.forward_post(
tgt, memory, style, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos
)
class DynamicFCDecoder(nn.Module):
def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
super().__init__() | self.layers = _get_clones(decoder_layer, num_layers) | 1 | 2023-12-28 05:39:31+00:00 | 2k |
jiawei-ren/dreamgaussian4d | diffusers/src/diffusers/models/activations.py | [
{
"identifier": "USE_PEFT_BACKEND",
"path": "diffusers/src/diffusers/utils/constants.py",
"snippet": "USE_PEFT_BACKEND = _required_peft_version and _required_transformers_version"
},
{
"identifier": "LoRACompatibleLinear",
"path": "diffusers/src/diffusers/models/lora.py",
"snippet": "cla... | import torch
import torch.nn.functional as F
from torch import nn
from ..utils import USE_PEFT_BACKEND
from .lora import LoRACompatibleLinear | 1,423 | # coding=utf-8
# Copyright 2023 HuggingFace Inc.
#
# 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.
ACTIVATION_FUNCTIONS = {
"swish": nn.SiLU(),
"silu": nn.SiLU(),
"mish": nn.Mish(),
"gelu": nn.GELU(),
"relu": nn.ReLU(),
}
def get_activation(act_fn: str) -> nn.Module:
"""Helper function to get activation function from string.
Args:
act_fn (str): Name of activation function.
Returns:
nn.Module: Activation function.
"""
act_fn = act_fn.lower()
if act_fn in ACTIVATION_FUNCTIONS:
return ACTIVATION_FUNCTIONS[act_fn]
else:
raise ValueError(f"Unsupported activation function: {act_fn}")
class GELU(nn.Module):
r"""
GELU activation function with tanh approximation support with `approximate="tanh"`.
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channels in the output.
approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
"""
def __init__(self, dim_in: int, dim_out: int, approximate: str = "none"):
super().__init__()
self.proj = nn.Linear(dim_in, dim_out)
self.approximate = approximate
def gelu(self, gate: torch.Tensor) -> torch.Tensor:
if gate.device.type != "mps":
return F.gelu(gate, approximate=self.approximate)
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
def forward(self, hidden_states):
hidden_states = self.proj(hidden_states)
hidden_states = self.gelu(hidden_states)
return hidden_states
class GEGLU(nn.Module):
r"""
A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channels in the output.
"""
def __init__(self, dim_in: int, dim_out: int):
super().__init__()
| # coding=utf-8
# Copyright 2023 HuggingFace Inc.
#
# 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.
ACTIVATION_FUNCTIONS = {
"swish": nn.SiLU(),
"silu": nn.SiLU(),
"mish": nn.Mish(),
"gelu": nn.GELU(),
"relu": nn.ReLU(),
}
def get_activation(act_fn: str) -> nn.Module:
"""Helper function to get activation function from string.
Args:
act_fn (str): Name of activation function.
Returns:
nn.Module: Activation function.
"""
act_fn = act_fn.lower()
if act_fn in ACTIVATION_FUNCTIONS:
return ACTIVATION_FUNCTIONS[act_fn]
else:
raise ValueError(f"Unsupported activation function: {act_fn}")
class GELU(nn.Module):
r"""
GELU activation function with tanh approximation support with `approximate="tanh"`.
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channels in the output.
approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
"""
def __init__(self, dim_in: int, dim_out: int, approximate: str = "none"):
super().__init__()
self.proj = nn.Linear(dim_in, dim_out)
self.approximate = approximate
def gelu(self, gate: torch.Tensor) -> torch.Tensor:
if gate.device.type != "mps":
return F.gelu(gate, approximate=self.approximate)
# mps: gelu is not implemented for float16
return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
def forward(self, hidden_states):
hidden_states = self.proj(hidden_states)
hidden_states = self.gelu(hidden_states)
return hidden_states
class GEGLU(nn.Module):
r"""
A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
Parameters:
dim_in (`int`): The number of channels in the input.
dim_out (`int`): The number of channels in the output.
"""
def __init__(self, dim_in: int, dim_out: int):
super().__init__() | linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear | 1 | 2023-12-28 08:17:40+00:00 | 2k |
Meituan-AutoML/MobileVLM | mobilevlm/model/mobilevlm.py | [
{
"identifier": "build_vision_tower",
"path": "mobilevlm/model/vision_encoder.py",
"snippet": "def build_vision_tower(model_cfg, **kwargs):\n vision_tower = getattr(model_cfg, 'mm_vision_tower', getattr(model_cfg, 'vision_tower', None))\n is_absolute_path_exists = os.path.exists(vision_tower)\n ... | import torch
import torch.nn as nn
from abc import ABC, abstractmethod
from transformers import AutoTokenizer, BitsAndBytesConfig
from mobilevlm.model.vision_encoder import build_vision_tower
from mobilevlm.model.vision_projector import build_vision_projector
from mobilevlm.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, \
DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from mobilevlm.model.mobilellama import MobileLlamaForCausalLM | 1,423 |
class MobileVLMMetaModel:
def __init__(self, config):
super(MobileVLMMetaModel, self).__init__(config)
if hasattr(config, "mm_vision_tower"):
self.vision_tower = build_vision_tower(config, delay_load=False)
self.mm_projector = build_vision_projector(config)
def get_vision_tower(self):
vision_tower = getattr(self, 'vision_tower', None)
if type(vision_tower) is list:
vision_tower = vision_tower[0]
return vision_tower
def initialize_vision_modules(self, model_args, fsdp=None):
mm_vision_select_layer = model_args.mm_vision_select_layer
mm_vision_select_feature = model_args.mm_vision_select_feature
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
self.config.mm_vision_tower = model_args.vision_tower
self.config.use_mm_proj = True
self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
self.config.mm_vision_select_layer = mm_vision_select_layer
self.config.mm_vision_select_feature = mm_vision_select_feature
# Build VisionTower
vision_tower = build_vision_tower(model_args)
if fsdp is not None and len(fsdp) > 0:
self.vision_tower = [vision_tower]
else:
self.vision_tower = vision_tower
self.config.mm_hidden_size = vision_tower.hidden_size
# Build Vision-Projector
self.mm_projector = build_vision_projector(self.config)
if pretrain_mm_mlp_adapter is not None:
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
def get_w(weights, keyword):
return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
class MobileVLMMetaForCausalLM(ABC):
@abstractmethod
def get_model(self):
pass
def get_vision_tower(self):
return self.get_model().get_vision_tower()
def encode_images(self, images):
image_features = self.get_model().get_vision_tower()(images)
image_features = self.get_model().mm_projector(image_features)
return image_features
def prepare_inputs_labels_for_multimodal(
self, input_ids, attention_mask, past_key_values, labels, images
):
vision_tower = self.get_vision_tower()
if vision_tower is None or images is None or input_ids.shape[1] == 1:
if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
return input_ids, attention_mask, past_key_values, None, labels
if type(images) is list or images.ndim == 5:
concat_images = torch.cat([image for image in images], dim=0)
image_features = self.encode_images(concat_images)
split_sizes = [image.shape[0] for image in images]
image_features = torch.split(image_features, split_sizes, dim=0)
image_features = [x.flatten(0, 1) for x in image_features]
else:
image_features = self.encode_images(images)
new_input_embeds = []
new_labels = [] if labels is not None else None
cur_image_idx = 0
for batch_idx, cur_input_ids in enumerate(input_ids):
|
class MobileVLMMetaModel:
def __init__(self, config):
super(MobileVLMMetaModel, self).__init__(config)
if hasattr(config, "mm_vision_tower"):
self.vision_tower = build_vision_tower(config, delay_load=False)
self.mm_projector = build_vision_projector(config)
def get_vision_tower(self):
vision_tower = getattr(self, 'vision_tower', None)
if type(vision_tower) is list:
vision_tower = vision_tower[0]
return vision_tower
def initialize_vision_modules(self, model_args, fsdp=None):
mm_vision_select_layer = model_args.mm_vision_select_layer
mm_vision_select_feature = model_args.mm_vision_select_feature
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
self.config.mm_vision_tower = model_args.vision_tower
self.config.use_mm_proj = True
self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
self.config.mm_vision_select_layer = mm_vision_select_layer
self.config.mm_vision_select_feature = mm_vision_select_feature
# Build VisionTower
vision_tower = build_vision_tower(model_args)
if fsdp is not None and len(fsdp) > 0:
self.vision_tower = [vision_tower]
else:
self.vision_tower = vision_tower
self.config.mm_hidden_size = vision_tower.hidden_size
# Build Vision-Projector
self.mm_projector = build_vision_projector(self.config)
if pretrain_mm_mlp_adapter is not None:
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
def get_w(weights, keyword):
return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
class MobileVLMMetaForCausalLM(ABC):
@abstractmethod
def get_model(self):
pass
def get_vision_tower(self):
return self.get_model().get_vision_tower()
def encode_images(self, images):
image_features = self.get_model().get_vision_tower()(images)
image_features = self.get_model().mm_projector(image_features)
return image_features
def prepare_inputs_labels_for_multimodal(
self, input_ids, attention_mask, past_key_values, labels, images
):
vision_tower = self.get_vision_tower()
if vision_tower is None or images is None or input_ids.shape[1] == 1:
if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
return input_ids, attention_mask, past_key_values, None, labels
if type(images) is list or images.ndim == 5:
concat_images = torch.cat([image for image in images], dim=0)
image_features = self.encode_images(concat_images)
split_sizes = [image.shape[0] for image in images]
image_features = torch.split(image_features, split_sizes, dim=0)
image_features = [x.flatten(0, 1) for x in image_features]
else:
image_features = self.encode_images(images)
new_input_embeds = []
new_labels = [] if labels is not None else None
cur_image_idx = 0
for batch_idx, cur_input_ids in enumerate(input_ids): | if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0: | 3 | 2023-12-29 03:35:49+00:00 | 2k |
kinggongzilla/ai-clone-whatsapp | utils/config_utils.py | [
{
"identifier": "datasets",
"path": "configs/datasets.py",
"snippet": "class custom_dataset:"
},
{
"identifier": "lora_config",
"path": "configs/peft.py",
"snippet": "class lora_config:\n r: int=8\n lora_alpha: int=32\n target_modules: List[str] = field(default_factory=lambda... | import inspect
import torch.distributed as dist
from dataclasses import asdict
from torch.utils.data import DistributedSampler
from peft import (
LoraConfig,
AdaptionPromptConfig,
PrefixTuningConfig,
)
from transformers import default_data_collator
from transformers.data import DataCollatorForSeq2Seq
from configs import datasets, lora_config, llama_adapter_config, prefix_config, train_config
from data.sampler import LengthBasedBatchSampler, DistributedLengthBasedBatchSampler
from utils.dataset_utils import DATASET_PREPROC | 1,507 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
def update_config(config, **kwargs):
if isinstance(config, (tuple, list)):
for c in config:
update_config(c, **kwargs)
else:
for k, v in kwargs.items():
if hasattr(config, k):
setattr(config, k, v)
elif "." in k:
# allow --some_config.some_param=True
config_name, param_name = k.split(".")
if type(config).__name__ == config_name:
if hasattr(config, param_name):
setattr(config, param_name, v)
else:
# In case of specialized config we can warm user
print(f"Warning: {config_name} does not accept parameter: {k}")
elif isinstance(config, train_config):
print(f"Warning: unknown parameter {k}")
def generate_peft_config(train_config, kwargs):
| # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
def update_config(config, **kwargs):
if isinstance(config, (tuple, list)):
for c in config:
update_config(c, **kwargs)
else:
for k, v in kwargs.items():
if hasattr(config, k):
setattr(config, k, v)
elif "." in k:
# allow --some_config.some_param=True
config_name, param_name = k.split(".")
if type(config).__name__ == config_name:
if hasattr(config, param_name):
setattr(config, param_name, v)
else:
# In case of specialized config we can warm user
print(f"Warning: {config_name} does not accept parameter: {k}")
elif isinstance(config, train_config):
print(f"Warning: unknown parameter {k}")
def generate_peft_config(train_config, kwargs): | configs = (lora_config, llama_adapter_config, prefix_config) | 1 | 2023-12-28 00:02:08+00:00 | 2k |
FoundationVision/UniRef | projects/UniRef/uniref/models/deformable_detr/matcher.py | [
{
"identifier": "box_cxcywh_to_xyxy",
"path": "projects/UniRef/uniref/util/box_ops.py",
"snippet": "def box_cxcywh_to_xyxy(x):\n # print('box:\\n', x)\n\n x_c, y_c, w, h = x.unbind(-1)\n b = [(x_c - 0.5 * w), (y_c - 0.5 * h),\n (x_c + 0.5 * w), (y_c + 0.5 * h)]\n return torch.stack(b... | import torch
import torch.nn.functional as F
import torchvision.ops as ops
from scipy.optimize import linear_sum_assignment
from torch import nn
from ...util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou | 1,206 | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# ------------------------------------------------------------------------
"""
Modules to compute the matching cost and solve the corresponding LSAP.
"""
class HungarianMatcher(nn.Module):
"""This class computes an assignment between the targets and the predictions of the network
For efficiency reasons, the targets don't include the no_object. Because of this, in general,
there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
while the others are un-matched (and thus treated as non-objects).
"""
def __init__(self,
cost_class: float = 1,
cost_bbox: float = 1,
cost_giou: float = 1):
"""Creates the matcher
Params:
cost_class: This is the relative weight of the classification error in the matching cost
cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
"""
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0"
def forward_ota(self, outputs, targets):
""" simOTA for detr
"""
with torch.no_grad():
bs, num_queries = outputs["pred_logits"].shape[:2]
out_prob = outputs["pred_logits"].sigmoid()
out_bbox = outputs["pred_boxes"] # 跳过frame 维度
indices = []
matched_ids = []
for batch_idx in range(bs):
bz_boxes = out_bbox[batch_idx] #[300,4]
bz_out_prob = out_prob[batch_idx]
bz_tgt_ids = targets[batch_idx]["labels"]
num_insts = len(bz_tgt_ids)
bz_gtboxs = targets[batch_idx]['boxes'].reshape(num_insts,4) #[num_gt, 4]
fg_mask, is_in_boxes_and_center = \
self.get_in_boxes_info(bz_boxes,bz_gtboxs,expanded_strides=32)
pair_wise_ious = ops.box_iou(box_cxcywh_to_xyxy(bz_boxes), box_cxcywh_to_xyxy(bz_gtboxs))
# pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8)
# Compute the classification cost.
alpha = 0.25
gamma = 2.0
neg_cost_class = (1 - alpha) * (bz_out_prob ** gamma) * (-(1 - bz_out_prob + 1e-8).log())
pos_cost_class = alpha * ((1 - bz_out_prob) ** gamma) * (-(bz_out_prob + 1e-8).log())
cost_class = pos_cost_class[:, bz_tgt_ids] - neg_cost_class[:, bz_tgt_ids]
| # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# ------------------------------------------------------------------------
"""
Modules to compute the matching cost and solve the corresponding LSAP.
"""
class HungarianMatcher(nn.Module):
"""This class computes an assignment between the targets and the predictions of the network
For efficiency reasons, the targets don't include the no_object. Because of this, in general,
there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
while the others are un-matched (and thus treated as non-objects).
"""
def __init__(self,
cost_class: float = 1,
cost_bbox: float = 1,
cost_giou: float = 1):
"""Creates the matcher
Params:
cost_class: This is the relative weight of the classification error in the matching cost
cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
"""
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0"
def forward_ota(self, outputs, targets):
""" simOTA for detr
"""
with torch.no_grad():
bs, num_queries = outputs["pred_logits"].shape[:2]
out_prob = outputs["pred_logits"].sigmoid()
out_bbox = outputs["pred_boxes"] # 跳过frame 维度
indices = []
matched_ids = []
for batch_idx in range(bs):
bz_boxes = out_bbox[batch_idx] #[300,4]
bz_out_prob = out_prob[batch_idx]
bz_tgt_ids = targets[batch_idx]["labels"]
num_insts = len(bz_tgt_ids)
bz_gtboxs = targets[batch_idx]['boxes'].reshape(num_insts,4) #[num_gt, 4]
fg_mask, is_in_boxes_and_center = \
self.get_in_boxes_info(bz_boxes,bz_gtboxs,expanded_strides=32)
pair_wise_ious = ops.box_iou(box_cxcywh_to_xyxy(bz_boxes), box_cxcywh_to_xyxy(bz_gtboxs))
# pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8)
# Compute the classification cost.
alpha = 0.25
gamma = 2.0
neg_cost_class = (1 - alpha) * (bz_out_prob ** gamma) * (-(1 - bz_out_prob + 1e-8).log())
pos_cost_class = alpha * ((1 - bz_out_prob) ** gamma) * (-(bz_out_prob + 1e-8).log())
cost_class = pos_cost_class[:, bz_tgt_ids] - neg_cost_class[:, bz_tgt_ids] | cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(bz_boxes), box_cxcywh_to_xyxy(bz_gtboxs)) | 1 | 2023-12-22 13:31:33+00:00 | 2k |
xhuangcv/humannorm | threestudio/models/materials/neural_radiance_material.py | [
{
"identifier": "BaseMaterial",
"path": "threestudio/models/materials/base.py",
"snippet": "class BaseMaterial(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n requires_normal: bool = False\n requires_tangent: bool = False\n\n def configure(s... | import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import threestudio
from dataclasses import dataclass, field
from threestudio.models.materials.base import BaseMaterial
from threestudio.models.networks import get_encoding, get_mlp
from threestudio.utils.ops import dot, get_activation
from threestudio.utils.typing import * | 1,149 |
@threestudio.register("neural-radiance-material")
class NeuralRadianceMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
input_feature_dims: int = 8
color_activation: str = "sigmoid"
dir_encoding_config: dict = field(
default_factory=lambda: {"otype": "SphericalHarmonics", "degree": 3}
)
mlp_network_config: dict = field(
default_factory=lambda: {
"otype": "FullyFusedMLP",
"activation": "ReLU",
"n_neurons": 16,
"n_hidden_layers": 2,
}
)
cfg: Config
def configure(self) -> None:
|
@threestudio.register("neural-radiance-material")
class NeuralRadianceMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
input_feature_dims: int = 8
color_activation: str = "sigmoid"
dir_encoding_config: dict = field(
default_factory=lambda: {"otype": "SphericalHarmonics", "degree": 3}
)
mlp_network_config: dict = field(
default_factory=lambda: {
"otype": "FullyFusedMLP",
"activation": "ReLU",
"n_neurons": 16,
"n_hidden_layers": 2,
}
)
cfg: Config
def configure(self) -> None: | self.encoding = get_encoding(3, self.cfg.dir_encoding_config) | 1 | 2023-12-23 12:37:48+00:00 | 2k |
jianchang512/stt | start.py | [
{
"identifier": "cfg",
"path": "stslib/cfg.py",
"snippet": "LANG = \"en\" if locale.getdefaultlocale()[0].split('_')[0].lower() != 'zh' else \"zh\"\nROOT_DIR = os.getcwd()\nMODEL_DIR = os.path.join(ROOT_DIR, 'models')\nSTATIC_DIR = os.path.join(ROOT_DIR, 'static')\nTMP_DIR = os.path.join(STATIC_DIR, 'tm... | import logging
import re
import threading
import sys
import torch
import os
from flask import Flask, request, render_template, jsonify, send_from_directory
from gevent.pywsgi import WSGIServer, WSGIHandler, LoggingLogAdapter
from logging.handlers import RotatingFileHandler
from stslib import cfg, tool
from stslib.cfg import ROOT_DIR
from faster_whisper import WhisperModel | 836 |
device = "cuda" if torch.cuda.is_available() else "cpu"
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 配置日志
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static',
template_folder=os.path.join(ROOT_DIR, 'templates'))
root_log = logging.getLogger() # Flask的根日志记录器
root_log.handlers = []
root_log.setLevel(logging.WARNING)
# 配置日志
app.logger.setLevel(logging.WARNING) # 设置日志级别为 INFO
# 创建 RotatingFileHandler 对象,设置写入的文件路径和大小限制
file_handler = RotatingFileHandler(os.path.join(ROOT_DIR, 'sts.log'), maxBytes=1024 * 1024, backupCount=5)
# 创建日志的格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 设置文件处理器的级别和格式
file_handler.setLevel(logging.WARNING)
file_handler.setFormatter(formatter)
# 将文件处理器添加到日志记录器中
app.logger.addHandler(file_handler)
@app.route('/static/<path:filename>')
def static_files(filename):
return send_from_directory(app.config['STATIC_FOLDER'], filename)
@app.route('/')
def index():
return render_template("index.html",
cuda=cfg.cuda,
lang_code=cfg.lang_code,
language=cfg.LANG,
root_dir=ROOT_DIR.replace('\\', '/'))
# 上传音频
@app.route('/upload', methods=['POST'])
def upload():
try:
# 获取上传的文件
audio_file = request.files['audio']
# 如果是mp4
noextname, ext = os.path.splitext(audio_file.filename)
ext = ext.lower()
# 如果是视频,先分离
wav_file = os.path.join(cfg.TMP_DIR, f'{noextname}.wav')
if os.path.exists(wav_file) and os.path.getsize(wav_file) > 0:
return jsonify({'code': 0, 'msg': cfg.transobj['lang1'], "data": os.path.basename(wav_file)})
msg = ""
if ext in ['.mp4', '.mov', '.avi', '.mkv', '.mpeg', '.mp3', '.flac']:
video_file = os.path.join(cfg.TMP_DIR, f'{noextname}{ext}')
audio_file.save(video_file)
params = [
"-i",
video_file,
]
if ext not in ['.mp3', '.flac']:
params.append('-vn')
params.append(wav_file)
|
device = "cuda" if torch.cuda.is_available() else "cpu"
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 配置日志
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static',
template_folder=os.path.join(ROOT_DIR, 'templates'))
root_log = logging.getLogger() # Flask的根日志记录器
root_log.handlers = []
root_log.setLevel(logging.WARNING)
# 配置日志
app.logger.setLevel(logging.WARNING) # 设置日志级别为 INFO
# 创建 RotatingFileHandler 对象,设置写入的文件路径和大小限制
file_handler = RotatingFileHandler(os.path.join(ROOT_DIR, 'sts.log'), maxBytes=1024 * 1024, backupCount=5)
# 创建日志的格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 设置文件处理器的级别和格式
file_handler.setLevel(logging.WARNING)
file_handler.setFormatter(formatter)
# 将文件处理器添加到日志记录器中
app.logger.addHandler(file_handler)
@app.route('/static/<path:filename>')
def static_files(filename):
return send_from_directory(app.config['STATIC_FOLDER'], filename)
@app.route('/')
def index():
return render_template("index.html",
cuda=cfg.cuda,
lang_code=cfg.lang_code,
language=cfg.LANG,
root_dir=ROOT_DIR.replace('\\', '/'))
# 上传音频
@app.route('/upload', methods=['POST'])
def upload():
try:
# 获取上传的文件
audio_file = request.files['audio']
# 如果是mp4
noextname, ext = os.path.splitext(audio_file.filename)
ext = ext.lower()
# 如果是视频,先分离
wav_file = os.path.join(cfg.TMP_DIR, f'{noextname}.wav')
if os.path.exists(wav_file) and os.path.getsize(wav_file) > 0:
return jsonify({'code': 0, 'msg': cfg.transobj['lang1'], "data": os.path.basename(wav_file)})
msg = ""
if ext in ['.mp4', '.mov', '.avi', '.mkv', '.mpeg', '.mp3', '.flac']:
video_file = os.path.join(cfg.TMP_DIR, f'{noextname}{ext}')
audio_file.save(video_file)
params = [
"-i",
video_file,
]
if ext not in ['.mp3', '.flac']:
params.append('-vn')
params.append(wav_file) | rs = tool.runffmpeg(params) | 1 | 2023-12-28 16:02:55+00:00 | 2k |
jesenzhang/ComfyUI_StreamDiffusion | streamdiffusion/pipeline.py | [
{
"identifier": "SimilarImageFilter",
"path": "streamdiffusion/image_filter.py",
"snippet": "class SimilarImageFilter:\n def __init__(self, threshold: float = 0.98, max_skip_frame: float = 10) -> None:\n self.threshold = threshold\n self.prev_tensor = None\n self.cos = torch.nn.C... | import time
import numpy as np
import PIL.Image
import torch
from typing import List, Optional, Union, Any, Dict, Tuple, Literal
from diffusers import LCMScheduler, StableDiffusionPipeline
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img import (
retrieve_latents,
)
from .image_filter import SimilarImageFilter
from .image_utils import postprocess_image | 1,162 |
class StreamDiffusion:
def __init__(
self,
pipe: StableDiffusionPipeline,
t_index_list: List[int],
torch_dtype: torch.dtype = torch.float16,
width: int = 512,
height: int = 512,
do_add_noise: bool = True,
use_denoising_batch: bool = True,
frame_buffer_size: int = 1,
cfg_type: Literal["none", "full", "self", "initialize"] = "self",
) -> None:
self.device = pipe.device
self.dtype = torch_dtype
self.generator = None
self.height = height
self.width = width
self.latent_height = int(height // pipe.vae_scale_factor)
self.latent_width = int(width // pipe.vae_scale_factor)
self.frame_bff_size = frame_buffer_size
self.denoising_steps_num = len(t_index_list)
self.cfg_type = cfg_type
if use_denoising_batch:
self.batch_size = self.denoising_steps_num * frame_buffer_size
if self.cfg_type == "initialize":
self.trt_unet_batch_size = (
self.denoising_steps_num + 1
) * self.frame_bff_size
elif self.cfg_type == "full":
self.trt_unet_batch_size = (
2 * self.denoising_steps_num * self.frame_bff_size
)
else:
self.trt_unet_batch_size = self.denoising_steps_num * frame_buffer_size
else:
self.trt_unet_batch_size = self.frame_bff_size
self.batch_size = frame_buffer_size
self.t_list = t_index_list
self.do_add_noise = do_add_noise
self.use_denoising_batch = use_denoising_batch
self.similar_image_filter = False
|
class StreamDiffusion:
def __init__(
self,
pipe: StableDiffusionPipeline,
t_index_list: List[int],
torch_dtype: torch.dtype = torch.float16,
width: int = 512,
height: int = 512,
do_add_noise: bool = True,
use_denoising_batch: bool = True,
frame_buffer_size: int = 1,
cfg_type: Literal["none", "full", "self", "initialize"] = "self",
) -> None:
self.device = pipe.device
self.dtype = torch_dtype
self.generator = None
self.height = height
self.width = width
self.latent_height = int(height // pipe.vae_scale_factor)
self.latent_width = int(width // pipe.vae_scale_factor)
self.frame_bff_size = frame_buffer_size
self.denoising_steps_num = len(t_index_list)
self.cfg_type = cfg_type
if use_denoising_batch:
self.batch_size = self.denoising_steps_num * frame_buffer_size
if self.cfg_type == "initialize":
self.trt_unet_batch_size = (
self.denoising_steps_num + 1
) * self.frame_bff_size
elif self.cfg_type == "full":
self.trt_unet_batch_size = (
2 * self.denoising_steps_num * self.frame_bff_size
)
else:
self.trt_unet_batch_size = self.denoising_steps_num * frame_buffer_size
else:
self.trt_unet_batch_size = self.frame_bff_size
self.batch_size = frame_buffer_size
self.t_list = t_index_list
self.do_add_noise = do_add_noise
self.use_denoising_batch = use_denoising_batch
self.similar_image_filter = False | self.similar_filter = SimilarImageFilter() | 0 | 2023-12-29 09:00:03+00:00 | 2k |
neobundy/MLX-Stable-Diffusion-WebUI | model_inspector.py | [
{
"identifier": "PathConfig",
"path": "stable_diffusion/config.py",
"snippet": "class DiffuserModelPathConfig:\nclass BaseConfig:\nclass AutoencoderConfig(BaseConfig):\nclass CLIPTextModelConfig(BaseConfig):\nclass UNetConfig(BaseConfig):\nclass DiffusionConfig(BaseConfig):\n def __init__(self, model... | from stable_diffusion.config import PathConfig
from stable_diffusion.model_io import preload_models_from_safetensor_weights
from utils import _state_dict
from utils import get_state_dict_from_safetensor | 1,090 |
INSPECTION_FILE = "model_inspection.txt"
NUM_ITEMS = 100
MODEL_FILE = "./models/v2-1_512-ema-pruned.safetensors"
MODEL_FILE1 = "./unet/diffusion_pytorch_model_test.safetensors"
MODEL_FILE2 = "./unet/xxmix9realistic_v40.safetensors"
# Recreate the inspection file at every execution of the script
with open(INSPECTION_FILE, 'w') as f:
pass
def write_to_file(*args, **kwargs):
"""Write the text to the inspection file."""
# Convert the arguments to a string
message = ' '.join(map(str, args))
# Print the message to the console
print(message, **kwargs)
# Open the log file in append mode and write the message
with open(INSPECTION_FILE, 'a') as f:
f.write(message + '\n')
def inspect_model(path_config: PathConfig, keys_only=True):
"""Inspect the contents of the models."""
# Load the models using the provided config and weights paths
unet_model = load_unet_local(path_config.unet_config, MODEL_FILE)
text_encoder_model = load_text_encoder_local(MODEL_FILE)
autoencoder_model = load_autoencoder_local(MODEL_FILE)
diffusion_config = load_diffusion_config_local(path_config.diffusion_config)
tokenizer = load_tokenizer_local(path_config.tokenizer_vocab, path_config.tokenizer_merges)
# Convert the models' state_dict to a dictionary and iterate over it
for model_name, model in zip(["unet", "text_encoder", "autoencoder"], [unet_model, text_encoder_model, autoencoder_model]):
write_to_file("-" * 50)
write_to_file(f"Model: {model_name}")
write_to_file("-" * 50)
|
INSPECTION_FILE = "model_inspection.txt"
NUM_ITEMS = 100
MODEL_FILE = "./models/v2-1_512-ema-pruned.safetensors"
MODEL_FILE1 = "./unet/diffusion_pytorch_model_test.safetensors"
MODEL_FILE2 = "./unet/xxmix9realistic_v40.safetensors"
# Recreate the inspection file at every execution of the script
with open(INSPECTION_FILE, 'w') as f:
pass
def write_to_file(*args, **kwargs):
"""Write the text to the inspection file."""
# Convert the arguments to a string
message = ' '.join(map(str, args))
# Print the message to the console
print(message, **kwargs)
# Open the log file in append mode and write the message
with open(INSPECTION_FILE, 'a') as f:
f.write(message + '\n')
def inspect_model(path_config: PathConfig, keys_only=True):
"""Inspect the contents of the models."""
# Load the models using the provided config and weights paths
unet_model = load_unet_local(path_config.unet_config, MODEL_FILE)
text_encoder_model = load_text_encoder_local(MODEL_FILE)
autoencoder_model = load_autoencoder_local(MODEL_FILE)
diffusion_config = load_diffusion_config_local(path_config.diffusion_config)
tokenizer = load_tokenizer_local(path_config.tokenizer_vocab, path_config.tokenizer_merges)
# Convert the models' state_dict to a dictionary and iterate over it
for model_name, model in zip(["unet", "text_encoder", "autoencoder"], [unet_model, text_encoder_model, autoencoder_model]):
write_to_file("-" * 50)
write_to_file(f"Model: {model_name}")
write_to_file("-" * 50) | for key, value in _state_dict(model).items(): | 2 | 2023-12-25 05:49:34+00:00 | 2k |
ffmemes/ff-backend | src/storage/service.py | [
{
"identifier": "language",
"path": "src/database.py",
"snippet": "DATABASE_URL = str(settings.DATABASE_URL)\nasync def fetch_one(select_query: Select | Insert | Update) -> dict[str, Any] | None:\nasync def fetch_all(select_query: Select | Insert | Update) -> list[dict[str, Any]]:\nasync def execute(sel... | from typing import Any
from datetime import datetime
from sqlalchemy import select, nulls_first, text
from sqlalchemy.dialects.postgresql import insert
from src.database import (
language,
meme,
meme_source,
meme_raw_telegram,
meme_raw_vk,
execute, fetch_one, fetch_all,
)
from src.storage.parsers.schemas import TgChannelPostParsingResult, VkGroupPostParsingResult
from src.storage.constants import (
MemeSourceType,
MemeSourceStatus,
MemeType,
MemeStatus,
MEME_RAW_TELEGRAM_MEME_SOURCE_POST_UNIQUE_CONSTRAINT,
MEME_RAW_VK_MEME_SOURCE_POST_UNIQUE_CONSTRAINT,
) | 1,154 |
async def insert_parsed_posts_from_telegram(
meme_source_id: int,
telegram_posts: list[TgChannelPostParsingResult],
) -> None:
posts = [
post.model_dump() | {"meme_source_id": meme_source_id}
for post in telegram_posts
]
insert_statement = insert(meme_raw_telegram).values(posts)
insert_posts_query = insert_statement.on_conflict_do_update(
constraint=MEME_RAW_TELEGRAM_MEME_SOURCE_POST_UNIQUE_CONSTRAINT,
set_={
"media": insert_statement.excluded.media,
"views": insert_statement.excluded.views,
"updated_at": datetime.utcnow(),
},
)
await execute(insert_posts_query)
async def insert_parsed_posts_from_vk(
meme_source_id: int,
vk_posts: list[VkGroupPostParsingResult],
) -> None:
posts = [
post.model_dump() | {"meme_source_id": meme_source_id}
for post in vk_posts
]
insert_statement = insert(meme_raw_vk).values(posts)
insert_posts_query = insert_statement.on_conflict_do_update(
constraint=MEME_RAW_VK_MEME_SOURCE_POST_UNIQUE_CONSTRAINT,
set_={
"media": insert_statement.excluded.media,
"views": insert_statement.excluded.views,
"likes": insert_statement.excluded.likes,
"reposts": insert_statement.excluded.reposts,
"comments": insert_statement.excluded.comments,
"updated_at": datetime.utcnow(),
},
)
await execute(insert_posts_query)
async def get_telegram_sources_to_parse(limit=10) -> list[dict[str, Any]]:
select_query = (
select(meme_source)
|
async def insert_parsed_posts_from_telegram(
meme_source_id: int,
telegram_posts: list[TgChannelPostParsingResult],
) -> None:
posts = [
post.model_dump() | {"meme_source_id": meme_source_id}
for post in telegram_posts
]
insert_statement = insert(meme_raw_telegram).values(posts)
insert_posts_query = insert_statement.on_conflict_do_update(
constraint=MEME_RAW_TELEGRAM_MEME_SOURCE_POST_UNIQUE_CONSTRAINT,
set_={
"media": insert_statement.excluded.media,
"views": insert_statement.excluded.views,
"updated_at": datetime.utcnow(),
},
)
await execute(insert_posts_query)
async def insert_parsed_posts_from_vk(
meme_source_id: int,
vk_posts: list[VkGroupPostParsingResult],
) -> None:
posts = [
post.model_dump() | {"meme_source_id": meme_source_id}
for post in vk_posts
]
insert_statement = insert(meme_raw_vk).values(posts)
insert_posts_query = insert_statement.on_conflict_do_update(
constraint=MEME_RAW_VK_MEME_SOURCE_POST_UNIQUE_CONSTRAINT,
set_={
"media": insert_statement.excluded.media,
"views": insert_statement.excluded.views,
"likes": insert_statement.excluded.likes,
"reposts": insert_statement.excluded.reposts,
"comments": insert_statement.excluded.comments,
"updated_at": datetime.utcnow(),
},
)
await execute(insert_posts_query)
async def get_telegram_sources_to_parse(limit=10) -> list[dict[str, Any]]:
select_query = (
select(meme_source) | .where(meme_source.c.type == MemeSourceType.TELEGRAM) | 3 | 2023-12-23 12:55:43+00:00 | 2k |
Con6924/SPM | src/configs/prompt.py | [
{
"identifier": "imagenet_templates",
"path": "src/misc/clip_templates.py",
"snippet": ""
},
{
"identifier": "encode_prompts",
"path": "src/engine/train_util.py",
"snippet": "def encode_prompts(\n tokenizer: CLIPTokenizer,\n text_encoder: CLIPTokenizer,\n prompts: list[str],\n ... | from typing import Literal, Optional, Union
from pathlib import Path
from pydantic import BaseModel, root_validator
from transformers import CLIPTextModel, CLIPTokenizer
from src.misc.clip_templates import imagenet_templates
from src.engine.train_util import encode_prompts
import yaml
import pandas as pd
import random
import torch | 1,147 |
class PromptEmbedsXL:
text_embeds: torch.FloatTensor
pooled_embeds: torch.FloatTensor
def __init__(self, embeds) -> None:
self.text_embeds, self.pooled_embeds = embeds
PROMPT_EMBEDDING = Union[torch.FloatTensor, PromptEmbedsXL]
class PromptEmbedsCache:
prompts: dict[str, PROMPT_EMBEDDING] = {}
def __setitem__(self, __name: str, __value: PROMPT_EMBEDDING) -> None:
self.prompts[__name] = __value
def __getitem__(self, __name: str) -> Optional[PROMPT_EMBEDDING]:
if __name in self.prompts:
return self.prompts[__name]
else:
return None
class PromptSettings(BaseModel): # yaml
target: str
positive: str = None # if None, target will be used
unconditional: str = "" # default is ""
neutral: str = None # if None, unconditional will be used
action: ACTION_TYPES = "erase" # default is "erase"
guidance_scale: float = 1.0 # default is 1.0
resolution: int = 512 # default is 512
dynamic_resolution: bool = False # default is False
batch_size: int = 1 # default is 1
dynamic_crops: bool = False # default is False. only used when model is XL
use_template: bool = False # default is False
la_strength: float = 1000.0
sampling_batch_size: int = 4
seed: int = None
case_number: int = 0
@root_validator(pre=True)
def fill_prompts(cls, values):
keys = values.keys()
if "target" not in keys:
raise ValueError("target must be specified")
if "positive" not in keys:
values["positive"] = values["target"]
if "unconditional" not in keys:
values["unconditional"] = ""
if "neutral" not in keys:
values["neutral"] = values["unconditional"]
return values
class PromptEmbedsPair:
target: PROMPT_EMBEDDING # the concept that do not want to generate
positive: PROMPT_EMBEDDING # generate the concept
unconditional: PROMPT_EMBEDDING # uncondition (default should be empty)
neutral: PROMPT_EMBEDDING # base condition (default should be empty)
use_template: bool = False # use clip template or not
guidance_scale: float
resolution: int
dynamic_resolution: bool
batch_size: int
dynamic_crops: bool
loss_fn: torch.nn.Module
action: ACTION_TYPES
def __init__(
self,
loss_fn: torch.nn.Module,
target: PROMPT_EMBEDDING,
positive: PROMPT_EMBEDDING,
unconditional: PROMPT_EMBEDDING,
neutral: PROMPT_EMBEDDING,
settings: PromptSettings,
) -> None:
self.loss_fn = loss_fn
self.target = target
self.positive = positive
self.unconditional = unconditional
self.neutral = neutral
self.settings = settings
self.use_template = settings.use_template
self.guidance_scale = settings.guidance_scale
self.resolution = settings.resolution
self.dynamic_resolution = settings.dynamic_resolution
self.batch_size = settings.batch_size
self.dynamic_crops = settings.dynamic_crops
self.action = settings.action
self.la_strength = settings.la_strength
self.sampling_batch_size = settings.sampling_batch_size
def _prepare_embeddings(
self,
cache: PromptEmbedsCache,
tokenizer: CLIPTokenizer,
text_encoder: CLIPTextModel,
):
"""
Prepare embeddings for training. When use_template is True, the embeddings will be
format using a template, and then be processed by the model.
"""
if not self.use_template:
return
template = random.choice(imagenet_templates)
target_prompt = template.format(self.settings.target)
if cache[target_prompt]:
self.target = cache[target_prompt]
else:
|
ACTION_TYPES = Literal[
"erase",
"erase_with_la",
]
class PromptEmbedsXL:
text_embeds: torch.FloatTensor
pooled_embeds: torch.FloatTensor
def __init__(self, embeds) -> None:
self.text_embeds, self.pooled_embeds = embeds
PROMPT_EMBEDDING = Union[torch.FloatTensor, PromptEmbedsXL]
class PromptEmbedsCache:
prompts: dict[str, PROMPT_EMBEDDING] = {}
def __setitem__(self, __name: str, __value: PROMPT_EMBEDDING) -> None:
self.prompts[__name] = __value
def __getitem__(self, __name: str) -> Optional[PROMPT_EMBEDDING]:
if __name in self.prompts:
return self.prompts[__name]
else:
return None
class PromptSettings(BaseModel): # yaml
target: str
positive: str = None # if None, target will be used
unconditional: str = "" # default is ""
neutral: str = None # if None, unconditional will be used
action: ACTION_TYPES = "erase" # default is "erase"
guidance_scale: float = 1.0 # default is 1.0
resolution: int = 512 # default is 512
dynamic_resolution: bool = False # default is False
batch_size: int = 1 # default is 1
dynamic_crops: bool = False # default is False. only used when model is XL
use_template: bool = False # default is False
la_strength: float = 1000.0
sampling_batch_size: int = 4
seed: int = None
case_number: int = 0
@root_validator(pre=True)
def fill_prompts(cls, values):
keys = values.keys()
if "target" not in keys:
raise ValueError("target must be specified")
if "positive" not in keys:
values["positive"] = values["target"]
if "unconditional" not in keys:
values["unconditional"] = ""
if "neutral" not in keys:
values["neutral"] = values["unconditional"]
return values
class PromptEmbedsPair:
target: PROMPT_EMBEDDING # the concept that do not want to generate
positive: PROMPT_EMBEDDING # generate the concept
unconditional: PROMPT_EMBEDDING # uncondition (default should be empty)
neutral: PROMPT_EMBEDDING # base condition (default should be empty)
use_template: bool = False # use clip template or not
guidance_scale: float
resolution: int
dynamic_resolution: bool
batch_size: int
dynamic_crops: bool
loss_fn: torch.nn.Module
action: ACTION_TYPES
def __init__(
self,
loss_fn: torch.nn.Module,
target: PROMPT_EMBEDDING,
positive: PROMPT_EMBEDDING,
unconditional: PROMPT_EMBEDDING,
neutral: PROMPT_EMBEDDING,
settings: PromptSettings,
) -> None:
self.loss_fn = loss_fn
self.target = target
self.positive = positive
self.unconditional = unconditional
self.neutral = neutral
self.settings = settings
self.use_template = settings.use_template
self.guidance_scale = settings.guidance_scale
self.resolution = settings.resolution
self.dynamic_resolution = settings.dynamic_resolution
self.batch_size = settings.batch_size
self.dynamic_crops = settings.dynamic_crops
self.action = settings.action
self.la_strength = settings.la_strength
self.sampling_batch_size = settings.sampling_batch_size
def _prepare_embeddings(
self,
cache: PromptEmbedsCache,
tokenizer: CLIPTokenizer,
text_encoder: CLIPTextModel,
):
"""
Prepare embeddings for training. When use_template is True, the embeddings will be
format using a template, and then be processed by the model.
"""
if not self.use_template:
return
template = random.choice(imagenet_templates)
target_prompt = template.format(self.settings.target)
if cache[target_prompt]:
self.target = cache[target_prompt]
else: | self.target = encode_prompts(tokenizer, text_encoder, [target_prompt]) | 1 | 2023-12-26 03:19:16+00:00 | 2k |
dakpinaroglu/Frame2seq | frame2seq/utils/score.py | [
{
"identifier": "residue_constants",
"path": "frame2seq/utils/residue_constants.py",
"snippet": "def load_stereo_chemical_props() -> Tuple[Mapping[str, List[Bond]],\n def make_bond_key(atom1_name, atom2_name):\ndef sequence_to_onehot(\n sequence: str,\n mapping: Mapping[str, int],\n) -> np.ndarra... | import os
import torch
from tqdm import tqdm
from frame2seq.utils import residue_constants
from frame2seq.utils.util import get_neg_pll, read_fasta_file
from frame2seq.utils.pdb2input import get_inference_inputs
from frame2seq.utils.pred2output import output_csv, output_indiv_csv | 1,471 |
def score(self, pdb_file, chain_id, fasta_file, save_indiv_neg_pll):
temperature = 1.0
seq_mask, aatype, X = get_inference_inputs(pdb_file, chain_id)
seq_mask = seq_mask.to(self.device)
aatype = aatype.to(self.device)
X = X.to(self.device)
str_form = [residue_constants.ID_TO_AA[int(i)] for i in aatype[0]]
input_aatype_onehot = residue_constants.sequence_to_onehot(
sequence=str_form,
mapping=residue_constants.AA_TO_ID,
)
input_aatype_onehot = torch.from_numpy(input_aatype_onehot).float()
input_aatype_onehot = input_aatype_onehot.unsqueeze(0)
input_aatype_onehot = input_aatype_onehot.to(self.device)
input_aatype_onehot = torch.zeros_like(input_aatype_onehot)
input_aatype_onehot[:, :,
20] = 1 # all positions are masked (set to unknown)
scores, preds = {}, []
with torch.no_grad():
pred_seq1 = self.models[0].forward(X, seq_mask, input_aatype_onehot)
pred_seq2 = self.models[1].forward(X, seq_mask, input_aatype_onehot)
pred_seq3 = self.models[2].forward(X, seq_mask, input_aatype_onehot)
pred_seq = (pred_seq1 + pred_seq2 + pred_seq3) / 3 # ensemble
pred_seq = pred_seq / temperature
pred_seq = torch.nn.functional.softmax(pred_seq, dim=-1)
pred_seq = pred_seq[seq_mask]
if fasta_file is not None:
|
def score(self, pdb_file, chain_id, fasta_file, save_indiv_neg_pll):
temperature = 1.0
seq_mask, aatype, X = get_inference_inputs(pdb_file, chain_id)
seq_mask = seq_mask.to(self.device)
aatype = aatype.to(self.device)
X = X.to(self.device)
str_form = [residue_constants.ID_TO_AA[int(i)] for i in aatype[0]]
input_aatype_onehot = residue_constants.sequence_to_onehot(
sequence=str_form,
mapping=residue_constants.AA_TO_ID,
)
input_aatype_onehot = torch.from_numpy(input_aatype_onehot).float()
input_aatype_onehot = input_aatype_onehot.unsqueeze(0)
input_aatype_onehot = input_aatype_onehot.to(self.device)
input_aatype_onehot = torch.zeros_like(input_aatype_onehot)
input_aatype_onehot[:, :,
20] = 1 # all positions are masked (set to unknown)
scores, preds = {}, []
with torch.no_grad():
pred_seq1 = self.models[0].forward(X, seq_mask, input_aatype_onehot)
pred_seq2 = self.models[1].forward(X, seq_mask, input_aatype_onehot)
pred_seq3 = self.models[2].forward(X, seq_mask, input_aatype_onehot)
pred_seq = (pred_seq1 + pred_seq2 + pred_seq3) / 3 # ensemble
pred_seq = pred_seq / temperature
pred_seq = torch.nn.functional.softmax(pred_seq, dim=-1)
pred_seq = pred_seq[seq_mask]
if fasta_file is not None: | input_seqs = read_fasta_file(fasta_file) | 2 | 2023-12-25 09:29:36+00:00 | 2k |
davep/oshit | oshit/app/oshit.py | [
{
"identifier": "load_configuration",
"path": "oshit/app/data/config.py",
"snippet": "@lru_cache(maxsize=None)\ndef load_configuration() -> Configuration:\n \"\"\"Load the configuration.\n\n Returns:\n The configuration.\n\n Note:\n As a side-effect, if the configuration doesn't e... | from textual.app import App
from .data import load_configuration, save_configuration
from .screens import Main | 1,359 | """The main application class."""
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class OSHit(App[None]):
"""The Orange Site Hit application."""
ENABLE_COMMAND_PALETTE = False
def __init__(self) -> None:
"""Initialise the application."""
super().__init__()
self.dark = load_configuration().dark_mode
def on_mount(self) -> None:
"""Get things going once the app is up and running."""
| """The main application class."""
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class OSHit(App[None]):
"""The Orange Site Hit application."""
ENABLE_COMMAND_PALETTE = False
def __init__(self) -> None:
"""Initialise the application."""
super().__init__()
self.dark = load_configuration().dark_mode
def on_mount(self) -> None:
"""Get things going once the app is up and running.""" | self.push_screen(Main()) | 2 | 2023-12-25 14:06:07+00:00 | 2k |
Maximilian-Winter/llama-cpp-agent | src/llama_cpp_agent/agent_memory/memory_tools.py | [
{
"identifier": "LlamaCppFunctionTool",
"path": "src/llama_cpp_agent/function_calling.py",
"snippet": "class LlamaCppFunctionTool:\n def __init__(self, pydantic_model: Type[BaseModel], has_markdown_code_block=False, has_triple_quoted_string=False,\n **additional_parameters):\n ... | from pydantic import BaseModel, Field
from ..function_calling import LlamaCppFunctionTool
from .core_memory_manager import CoreMemoryManager
from .retrieval_memory_manager import RetrievalMemoryManager, RetrievalMemory | 1,362 |
class AddCoreMemory(BaseModel):
"""
Add a new entry to the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry.")
field: str = Field(..., description="A secondary key or field within the core memory entry.")
value: str = Field(..., description="The value or data to be stored in the specified core memory entry.")
def run(self, core_memory_manager: CoreMemoryManager):
return core_memory_manager.add_to_core_memory(self.key, self.field, self.value)
# Replace Core Memory Model
class ReplaceCoreMemory(BaseModel):
"""
Replace an entry in the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry.")
field: str = Field(..., description="The specific field within the core memory entry to be replaced.")
new_value: str = Field(...,
description="The new value to replace the existing data in the specified core memory field.")
def run(self, core_memory_manager: CoreMemoryManager):
return core_memory_manager.replace_in_core_memory(self.key, self.field, self.value)
class RemoveCoreMemory(BaseModel):
"""
Remove an entry in the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry to be removed.")
field: str = Field(..., description="The specific field within the core memory entry to be removed.")
def run(self, core_memory_manager: CoreMemoryManager):
return core_memory_manager.remove_from_core_memory(self.key, self.field)
class RetrieveMemories(BaseModel):
"""
Retrieve memories from the retrieval memory based on a query.
"""
query: str = Field(..., description="The query to be used to retrieve memories from the retrieval memory.")
def run(self, retrieval_memory_manager: RetrievalMemoryManager):
return retrieval_memory_manager.retrieve_memories(self.query)
class AddRetrievalMemory(BaseModel):
"""
Add memory to the retrieval memory.
"""
memory: str = Field(..., description="The memory to be added to the retrieval memory.")
importance: float = Field(..., description="The importance of the memory to be added to the retrieval memory.")
def run(self, retrieval_memory_manager: RetrievalMemoryManager):
return retrieval_memory_manager.add_memory_to_retrieval(self.memory, self.importance)
class AgentRetrievalMemory:
def __init__(self, persistent_db_path="./retrieval_memory", embedding_model_name="all-MiniLM-L6-v2",
collection_name="retrieval_memory_collection"):
|
class AddCoreMemory(BaseModel):
"""
Add a new entry to the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry.")
field: str = Field(..., description="A secondary key or field within the core memory entry.")
value: str = Field(..., description="The value or data to be stored in the specified core memory entry.")
def run(self, core_memory_manager: CoreMemoryManager):
return core_memory_manager.add_to_core_memory(self.key, self.field, self.value)
# Replace Core Memory Model
class ReplaceCoreMemory(BaseModel):
"""
Replace an entry in the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry.")
field: str = Field(..., description="The specific field within the core memory entry to be replaced.")
new_value: str = Field(...,
description="The new value to replace the existing data in the specified core memory field.")
def run(self, core_memory_manager: CoreMemoryManager):
return core_memory_manager.replace_in_core_memory(self.key, self.field, self.value)
class RemoveCoreMemory(BaseModel):
"""
Remove an entry in the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry to be removed.")
field: str = Field(..., description="The specific field within the core memory entry to be removed.")
def run(self, core_memory_manager: CoreMemoryManager):
return core_memory_manager.remove_from_core_memory(self.key, self.field)
class RetrieveMemories(BaseModel):
"""
Retrieve memories from the retrieval memory based on a query.
"""
query: str = Field(..., description="The query to be used to retrieve memories from the retrieval memory.")
def run(self, retrieval_memory_manager: RetrievalMemoryManager):
return retrieval_memory_manager.retrieve_memories(self.query)
class AddRetrievalMemory(BaseModel):
"""
Add memory to the retrieval memory.
"""
memory: str = Field(..., description="The memory to be added to the retrieval memory.")
importance: float = Field(..., description="The importance of the memory to be added to the retrieval memory.")
def run(self, retrieval_memory_manager: RetrievalMemoryManager):
return retrieval_memory_manager.add_memory_to_retrieval(self.memory, self.importance)
class AgentRetrievalMemory:
def __init__(self, persistent_db_path="./retrieval_memory", embedding_model_name="all-MiniLM-L6-v2",
collection_name="retrieval_memory_collection"): | self.retrieval_memory = RetrievalMemory(persistent_db_path, embedding_model_name, collection_name) | 2 | 2023-12-29 16:54:39+00:00 | 2k |
tedivm/paracelsus | paracelsus/cli.py | [
{
"identifier": "Dot",
"path": "paracelsus/transformers/dot.py",
"snippet": "class Dot:\n comment_format: str = \"dot\"\n metadata: MetaData\n graph: pydot.Dot\n\n def __init__(self, metaclass: MetaData) -> None:\n self.metadata = metaclass\n self.graph = pydot.Dot(\"database\"... | import importlib
import re
import sys
import typer
from enum import Enum
from pathlib import Path
from typing import List
from typing_extensions import Annotated
from .transformers.dot import Dot
from .transformers.mermaid import Mermaid
from . import _version | 1,289 |
app = typer.Typer()
transformers = {
"mmd": Mermaid,
"mermaid": Mermaid,
|
app = typer.Typer()
transformers = {
"mmd": Mermaid,
"mermaid": Mermaid, | "dot": Dot, | 0 | 2023-12-29 22:13:23+00:00 | 2k |
winniesi/tg-gemini-bot | api/handle.py | [
{
"identifier": "is_authorized",
"path": "api/auth.py",
"snippet": "def is_authorized(from_id: int, user_name: str) -> bool:\n if str(user_name) in ALLOWED_USERS:\n return True\n return False"
},
{
"identifier": "ChatManager",
"path": "api/context.py",
"snippet": "class Chat... | from .auth import is_authorized
from .context import ChatManager, ImageChatManger
from .telegram import Update, send_message | 971 | """
All the chat that comes through the Telegram bot gets passed to the
handle_message function. This function checks out if the user has the
green light to chat with the bot. Once that's sorted, it figures out if
the user sent words or an image and deals with it accordingly.
For text messages, it fires up the ChatManager class that keeps track of
the back-and-forth with that user.
As for images, in Gemini pro, they're context-free, so you can handle
them pretty straight-up without much fuss.
"""
chat_manager = ChatManager()
def handle_message(update_data):
update = Update(update_data)
authorized = is_authorized(update.from_id, update.user_name)
if not authorized:
| """
All the chat that comes through the Telegram bot gets passed to the
handle_message function. This function checks out if the user has the
green light to chat with the bot. Once that's sorted, it figures out if
the user sent words or an image and deals with it accordingly.
For text messages, it fires up the ChatManager class that keeps track of
the back-and-forth with that user.
As for images, in Gemini pro, they're context-free, so you can handle
them pretty straight-up without much fuss.
"""
chat_manager = ChatManager()
def handle_message(update_data):
update = Update(update_data)
authorized = is_authorized(update.from_id, update.user_name)
if not authorized: | send_message(update.from_id, "😫 You are not allowed to use this bot.") | 4 | 2023-12-25 03:27:43+00:00 | 2k |
usail-hkust/LLMTSCS | run_advanced_maxpressure.py | [
{
"identifier": "oneline_wrapper",
"path": "utils/utils.py",
"snippet": "def oneline_wrapper(dic_agent_conf, dic_traffic_env_conf, dic_path, roadnet, trafficflow):\n results_table = []\n all_rewards = []\n all_queue_len = []\n all_travel_time = []\n for i in range(1):\n dic_path[\"... | from utils.utils import oneline_wrapper
from utils import error
from multiprocessing import Process
import os
import time
import argparse | 1,154 |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--memo", type=str, default='AdvancedMaxPressure')
parser.add_argument("--model", type=str, default="AdvancedMaxPressure")
parser.add_argument("--proj_name", type=str, default="chatgpt-TSCS")
parser.add_argument("--eightphase", action="store_true", default=False)
parser.add_argument("--multi_process", action="store_true", default=True)
parser.add_argument("--workers", type=int, default=1)
parser.add_argument("--dataset", type=str, default="template")
parser.add_argument("--traffic_file", type=str, default="flow_main_stream.json")
return parser.parse_args()
def main(in_args):
traffic_file_list = []
if in_args.dataset == 'jinan':
count = 3600
road_net = "3_4"
traffic_file_list = ["anon_3_4_jinan_real.json", "anon_3_4_jinan_real_2000.json", "anon_3_4_jinan_real_2500.json"]
template = "Jinan"
elif in_args.dataset == 'hangzhou':
count = 3600
road_net = "4_4"
traffic_file_list = ["anon_4_4_hangzhou_real.json", "anon_4_4_hangzhou_real_5816.json"]
template = "Hangzhou"
elif in_args.dataset == 'newyork_16x3':
count = 3600
road_net = "16_3"
traffic_file_list = ["anon_16_3_newyork_real.json"]
template = "NewYork"
elif in_args.dataset == 'newyork_28x7':
count = 3600
road_net = "28_7"
traffic_file_list = ["anon_28_7_newyork_real_double.json", "anon_28_7_newyork_real_triple.json"]
template = "NewYork"
elif in_args.dataset == 'template':
count = 3600
road_net = "1_1"
traffic_file_list = ["flow_main_stream.json"]
template = "template"
# flow_file error
try:
if in_args.traffic_file not in traffic_file_list:
|
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--memo", type=str, default='AdvancedMaxPressure')
parser.add_argument("--model", type=str, default="AdvancedMaxPressure")
parser.add_argument("--proj_name", type=str, default="chatgpt-TSCS")
parser.add_argument("--eightphase", action="store_true", default=False)
parser.add_argument("--multi_process", action="store_true", default=True)
parser.add_argument("--workers", type=int, default=1)
parser.add_argument("--dataset", type=str, default="template")
parser.add_argument("--traffic_file", type=str, default="flow_main_stream.json")
return parser.parse_args()
def main(in_args):
traffic_file_list = []
if in_args.dataset == 'jinan':
count = 3600
road_net = "3_4"
traffic_file_list = ["anon_3_4_jinan_real.json", "anon_3_4_jinan_real_2000.json", "anon_3_4_jinan_real_2500.json"]
template = "Jinan"
elif in_args.dataset == 'hangzhou':
count = 3600
road_net = "4_4"
traffic_file_list = ["anon_4_4_hangzhou_real.json", "anon_4_4_hangzhou_real_5816.json"]
template = "Hangzhou"
elif in_args.dataset == 'newyork_16x3':
count = 3600
road_net = "16_3"
traffic_file_list = ["anon_16_3_newyork_real.json"]
template = "NewYork"
elif in_args.dataset == 'newyork_28x7':
count = 3600
road_net = "28_7"
traffic_file_list = ["anon_28_7_newyork_real_double.json", "anon_28_7_newyork_real_triple.json"]
template = "NewYork"
elif in_args.dataset == 'template':
count = 3600
road_net = "1_1"
traffic_file_list = ["flow_main_stream.json"]
template = "template"
# flow_file error
try:
if in_args.traffic_file not in traffic_file_list: | raise error.flowFileException('Flow file does not exist.') | 1 | 2023-12-26 08:31:47+00:00 | 2k |
ohadmata/shmessy | src/shmessy/types/unix_timestamp.py | [
{
"identifier": "InferredField",
"path": "src/shmessy/schema.py",
"snippet": "class InferredField(BaseModel):\n inferred_type: Optional[str] = None\n inferred_pattern: Optional[Any] = None"
},
{
"identifier": "ValidatorTypes",
"path": "src/shmessy/schema.py",
"snippet": "class Vali... | import logging
import math
from datetime import datetime
from enum import Enum
from typing import Optional
from numpy import ndarray
from pandas import Series, to_datetime
from ..schema import InferredField, ValidatorTypes
from .base import BaseType | 669 |
logger = logging.getLogger(__name__)
class TimestampResolution(str, Enum):
SECONDS = "s"
MILLISECONDS = "ms"
NANOSECONDS = "ns"
class UnixTimestampType(BaseType):
weight = 4
validator_types = (ValidatorTypes.NUMERIC,)
min_valid_year: int = 1980
max_valid_year: int = 2100
@staticmethod
def _unix_timestamp_resolution(value: float) -> TimestampResolution:
number_of_digits = len(str(int(value)))
if number_of_digits == 10:
return TimestampResolution.SECONDS
if number_of_digits == 13:
return TimestampResolution.MILLISECONDS
if number_of_digits == 16:
return TimestampResolution.NANOSECONDS
@staticmethod
def _fix_input_resolution(
value: float, selected_resolution: TimestampResolution
) -> float:
if selected_resolution == TimestampResolution.SECONDS:
return value
if selected_resolution == TimestampResolution.MILLISECONDS:
return value / 1000
if selected_resolution == TimestampResolution.NANOSECONDS:
return value / 1000 / 1000
|
logger = logging.getLogger(__name__)
class TimestampResolution(str, Enum):
SECONDS = "s"
MILLISECONDS = "ms"
NANOSECONDS = "ns"
class UnixTimestampType(BaseType):
weight = 4
validator_types = (ValidatorTypes.NUMERIC,)
min_valid_year: int = 1980
max_valid_year: int = 2100
@staticmethod
def _unix_timestamp_resolution(value: float) -> TimestampResolution:
number_of_digits = len(str(int(value)))
if number_of_digits == 10:
return TimestampResolution.SECONDS
if number_of_digits == 13:
return TimestampResolution.MILLISECONDS
if number_of_digits == 16:
return TimestampResolution.NANOSECONDS
@staticmethod
def _fix_input_resolution(
value: float, selected_resolution: TimestampResolution
) -> float:
if selected_resolution == TimestampResolution.SECONDS:
return value
if selected_resolution == TimestampResolution.MILLISECONDS:
return value / 1000
if selected_resolution == TimestampResolution.NANOSECONDS:
return value / 1000 / 1000
| def validate(self, data: ndarray) -> Optional[InferredField]: | 0 | 2023-12-27 20:15:01+00:00 | 2k |
kokiez/solana-sniper | monitor_price_strategy.py | [
{
"identifier": "get_price",
"path": "birdeye.py",
"snippet": "def get_price(token_address):\r\n url = f\"https://api.dexscreener.com/latest/dex/tokens/{token_address}\"\r\n exclude = ['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB']\r\n response =... | import time
from birdeye import get_price, getSymbol
from webhook import sendWebhook
| 1,376 |
"""If you have ton of trades then best to use Simulate Transaction and modify this part of code to your needs"""
"""
Only Take Profit
"""
def limit_order(bought_token_price,desired_token_address, take_profit_ratio, execution_time, txB):
token_symbol, SOl_Symbol = getSymbol(desired_token_address)
# CALCULATE SELL LIMIT
sell_limit_token_price = bought_token_price * take_profit_ratio
print("-" * 79)
print(f"| {'Bought Price':<12} | {'Sell Limit':<12} | {'Tx Buy':<50} |")
print("-" * 79)
print(f"|{bought_token_price:.12f} | {sell_limit_token_price:.12f} {txB:<50} |")
print("-" * 79)
sendWebhook(f"msg_b|BUY INFO {token_symbol}",f"Bought Price: {bought_token_price:.12f}\n**Sell Limit: {sell_limit_token_price:.15f}**\nTotal Buy Execution time: {execution_time} seconds\nBuy TXN: https://solscan.io/tx/{txB} |")
# LOOP = CHECK IF PRICE >= SELL LIMIT | checks price every 5 seconds
priceLow = True
# while priceLow and isTimePassed(time_limit) == False:
while priceLow:
# Check if time limit has been passed for the token bought or not
|
"""If you have ton of trades then best to use Simulate Transaction and modify this part of code to your needs"""
"""
Only Take Profit
"""
def limit_order(bought_token_price,desired_token_address, take_profit_ratio, execution_time, txB):
token_symbol, SOl_Symbol = getSymbol(desired_token_address)
# CALCULATE SELL LIMIT
sell_limit_token_price = bought_token_price * take_profit_ratio
print("-" * 79)
print(f"| {'Bought Price':<12} | {'Sell Limit':<12} | {'Tx Buy':<50} |")
print("-" * 79)
print(f"|{bought_token_price:.12f} | {sell_limit_token_price:.12f} {txB:<50} |")
print("-" * 79)
sendWebhook(f"msg_b|BUY INFO {token_symbol}",f"Bought Price: {bought_token_price:.12f}\n**Sell Limit: {sell_limit_token_price:.15f}**\nTotal Buy Execution time: {execution_time} seconds\nBuy TXN: https://solscan.io/tx/{txB} |")
# LOOP = CHECK IF PRICE >= SELL LIMIT | checks price every 5 seconds
priceLow = True
# while priceLow and isTimePassed(time_limit) == False:
while priceLow:
# Check if time limit has been passed for the token bought or not
| bought_token_curr_price = get_price(desired_token_address)
| 0 | 2023-12-26 11:40:05+00:00 | 2k |
enochyearn/MLX_RoBERTa | mlx_roberta.py | [
{
"identifier": "LayerNormBasselCorrected",
"path": "custom/nn/layers/normalization.py",
"snippet": "class LayerNormBasselCorrected(Module):\n r\"\"\"Applies layer normalization [1] on the inputs with Bessel's Correction used by default like PyTorch.\n\n Computes\n\n .. math::\n\n y = \\... | import argparse
import time
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import math
from mlx.utils import tree_unflatten
from collections import OrderedDict
from custom.nn.layers.normalization import LayerNormBasselCorrected, LayerNormTorchAlike
from transformers import RobertaTokenizer
from dataclasses import dataclass | 1,439 |
# utils
@dataclass
class ModelConfig:
intermediate_size: int = 3072
hidden_size: int = 768
no_heads: int = 12
hidden_layers: int = 12
vocab_size: int = 50265
attention_probs_dropout_prob: float = 0.1
hidden_dropout_prob: float = 0.1
layer_norm_eps: float = 1e-5
max_position_embeddings: int = 514
# QA model's parameters
num_labels: int = 2
type_vocab_size: int = 2
pad_token_id: int = 1
chunk_size_feed_forward: int = 0
model_configs = {
"deepset/roberta-base-squad2": ModelConfig(),
"roberta-base": ModelConfig(),
}
model_types = {
"deepset/roberta-base-squad2": "qa",
"roberta-base": "base",
}
class RobertaEmbeddings(nn.Module):
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
# utils
@dataclass
class ModelConfig:
intermediate_size: int = 3072
hidden_size: int = 768
no_heads: int = 12
hidden_layers: int = 12
vocab_size: int = 50265
attention_probs_dropout_prob: float = 0.1
hidden_dropout_prob: float = 0.1
layer_norm_eps: float = 1e-5
max_position_embeddings: int = 514
# QA model's parameters
num_labels: int = 2
type_vocab_size: int = 2
pad_token_id: int = 1
chunk_size_feed_forward: int = 0
model_configs = {
"deepset/roberta-base-squad2": ModelConfig(),
"roberta-base": ModelConfig(),
}
model_types = {
"deepset/roberta-base-squad2": "qa",
"roberta-base": "base",
}
class RobertaEmbeddings(nn.Module):
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
| self.LayerNorm = LayerNormTorchAlike(config.hidden_size, eps=config.layer_norm_eps, correction=True) | 1 | 2023-12-22 05:48:57+00:00 | 2k |
zy7y/dfs-generate | main.py | [
{
"identifier": "CodeGen",
"path": "entity.py",
"snippet": "class CodeGen(BaseVo):\n name: str\n code: str\n\n @field_serializer(\"code\")\n def serialize_code(self, code: str, _info):\n _code = black.format_str(code, mode=black.FileMode())\n return isort.code(_code)"
},
{
... | from fastapi import FastAPI, Query
from fastapi.requests import Request
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from entity import CodeGen, Conf, DBConf, R, RList, Table
from generate.main import generate_code
import uvicorn | 789 |
app = FastAPI(
title="dfs-generate", description="FastAPI SQLModel 逆向生成代码", docs_url=None
)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", include_in_schema=False)
def index():
return FileResponse("static/index.html")
|
app = FastAPI(
title="dfs-generate", description="FastAPI SQLModel 逆向生成代码", docs_url=None
)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", include_in_schema=False)
def index():
return FileResponse("static/index.html")
| @app.get("/tables", response_model=RList[Table]) | 5 | 2023-12-23 08:32:58+00:00 | 2k |
CrawlScript/Torch-MGDCF | torch_mgdcf/evaluation/ranking.py | [
{
"identifier": "ndcg_score",
"path": "torch_mgdcf/metrics/ranking.py",
"snippet": "def ndcg_score(reference, hypothesis):\n \"\"\"\n Normalized Discounted Cumulative Gain (nDCG)\n Normalized version of DCG:\n nDCG = DCG(hypothesis)/DCG(reference)\n\n Parameters:\n reference ... | from tqdm import tqdm
from torch_mgdcf.metrics.ranking import ndcg_score, precision_score, recall_score
from torch_mgdcf.vector_search.vector_search import VectorSearchEngine
import numpy as np
import torch | 765 | # coding=utf-8
# The code is from our another project GRecX: https://github.com/maenzhier/grecx_datasets
def score(ground_truth, pred_items, k_list, metrics):
pred_match = [1 if item in ground_truth else 0 for item in pred_items]
max_k = k_list[-1]
if len(ground_truth) > max_k:
ndcg_gold = [1] * max_k
else:
ndcg_gold = [1] * len(ground_truth) + [0] * (max_k - len(ground_truth))
res_score = []
for metric in metrics:
if metric == "ndcg":
score_func = ndcg_score
elif metric == "precision":
score_func = precision_score
elif metric == "recall":
score_func = recall_score
else:
raise Exception("Not Found Metric : {}".format(metric))
for k in k_list:
if metric == "ndcg":
res_score.append(score_func(ndcg_gold[:k], pred_match[:k]))
else:
res_score.append(score_func(ground_truth, pred_match[:k]))
return res_score
def evaluate_mean_global_metrics(user_items_dict, user_mask_items_dict,
user_embedding, item_embedding,
k_list=[10, 20], metrics=["ndcg"]):
| # coding=utf-8
# The code is from our another project GRecX: https://github.com/maenzhier/grecx_datasets
def score(ground_truth, pred_items, k_list, metrics):
pred_match = [1 if item in ground_truth else 0 for item in pred_items]
max_k = k_list[-1]
if len(ground_truth) > max_k:
ndcg_gold = [1] * max_k
else:
ndcg_gold = [1] * len(ground_truth) + [0] * (max_k - len(ground_truth))
res_score = []
for metric in metrics:
if metric == "ndcg":
score_func = ndcg_score
elif metric == "precision":
score_func = precision_score
elif metric == "recall":
score_func = recall_score
else:
raise Exception("Not Found Metric : {}".format(metric))
for k in k_list:
if metric == "ndcg":
res_score.append(score_func(ndcg_gold[:k], pred_match[:k]))
else:
res_score.append(score_func(ground_truth, pred_match[:k]))
return res_score
def evaluate_mean_global_metrics(user_items_dict, user_mask_items_dict,
user_embedding, item_embedding,
k_list=[10, 20], metrics=["ndcg"]):
| v_search = VectorSearchEngine(item_embedding) | 3 | 2023-12-26 10:26:50+00:00 | 2k |
KyanChen/TTP | opencd/models/data_preprocessor.py | [
{
"identifier": "SampleList",
"path": "mmseg/utils/typing_utils.py",
"snippet": ""
},
{
"identifier": "MODELS",
"path": "opencd/registry.py",
"snippet": "MODELS = Registry('model', parent=MMENGINE_MODELS, locations=['opencd.models'])"
}
] | from numbers import Number
from typing import Any, Dict, List, Optional, Sequence, Union
from mmengine.model import BaseDataPreprocessor
from mmseg.utils import SampleList
from opencd.registry import MODELS
import numpy as np
import torch
import torch.nn.functional as F | 1,234 | # Copyright (c) Open-CD. All rights reserved.
def stack_batch(inputs: List[torch.Tensor],
data_samples: Optional[SampleList] = None,
size: Optional[tuple] = None,
size_divisor: Optional[int] = None,
pad_val: Union[int, float] = 0,
seg_pad_val: Union[int, float] = 255) -> torch.Tensor:
"""Stack multiple inputs to form a batch and pad the images and gt_sem_segs
to the max shape use the right bottom padding mode.
Args:
inputs (List[Tensor]): The input multiple tensors. each is a
CHW 3D-tensor.
data_samples (list[:obj:`SegDataSample`]): The list of data samples.
It usually includes information such as `gt_sem_seg`.
size (tuple, optional): Fixed padding size.
size_divisor (int, optional): The divisor of padded size.
pad_val (int, float): The padding value. Defaults to 0
seg_pad_val (int, float): The padding value. Defaults to 255
Returns:
Tensor: The 4D-tensor.
List[:obj:`SegDataSample`]: After the padding of the gt_seg_map.
"""
assert isinstance(inputs, list), \
f'Expected input type to be list, but got {type(inputs)}'
assert len({tensor.ndim for tensor in inputs}) == 1, \
f'Expected the dimensions of all inputs must be the same, ' \
f'but got {[tensor.ndim for tensor in inputs]}'
assert inputs[0].ndim == 3, f'Expected tensor dimension to be 3, ' \
f'but got {inputs[0].ndim}'
assert len({tensor.shape[0] for tensor in inputs}) == 1, \
f'Expected the channels of all inputs must be the same, ' \
f'but got {[tensor.shape[0] for tensor in inputs]}'
# only one of size and size_divisor should be valid
assert (size is not None) ^ (size_divisor is not None), \
'only one of size and size_divisor should be valid'
padded_inputs = []
padded_samples = []
inputs_sizes = [(img.shape[-2], img.shape[-1]) for img in inputs]
max_size = np.stack(inputs_sizes).max(0)
if size_divisor is not None and size_divisor > 1:
# the last two dims are H,W, both subject to divisibility requirement
max_size = (max_size +
(size_divisor - 1)) // size_divisor * size_divisor
for i in range(len(inputs)):
tensor = inputs[i]
if size is not None:
width = max(size[-1] - tensor.shape[-1], 0)
height = max(size[-2] - tensor.shape[-2], 0)
# (padding_left, padding_right, padding_top, padding_bottom)
padding_size = (0, width, 0, height)
elif size_divisor is not None:
width = max(max_size[-1] - tensor.shape[-1], 0)
height = max(max_size[-2] - tensor.shape[-2], 0)
padding_size = (0, width, 0, height)
else:
padding_size = [0, 0, 0, 0]
# pad img
pad_img = F.pad(tensor, padding_size, value=pad_val)
padded_inputs.append(pad_img)
# pad gt_sem_seg
if data_samples is not None:
data_sample = data_samples[i]
gt_sem_seg = data_sample.gt_sem_seg.data
del data_sample.gt_sem_seg.data
data_sample.gt_sem_seg.data = F.pad(
gt_sem_seg, padding_size, value=seg_pad_val)
if 'gt_edge_map' in data_sample:
gt_edge_map = data_sample.gt_edge_map.data
del data_sample.gt_edge_map.data
data_sample.gt_edge_map.data = F.pad(
gt_edge_map, padding_size, value=seg_pad_val)
if 'gt_seg_map_from' in data_sample:
gt_seg_map_from = data_sample.gt_seg_map_from.data
del data_sample.gt_seg_map_from.data
data_sample.gt_seg_map_from.data = F.pad(
gt_seg_map_from, padding_size, value=seg_pad_val)
if 'gt_seg_map_to' in data_sample:
gt_seg_map_to = data_sample.gt_seg_map_to.data
del data_sample.gt_seg_map_to.data
data_sample.gt_seg_map_to.data = F.pad(
gt_seg_map_to, padding_size, value=seg_pad_val)
data_sample.set_metainfo({
'img_shape': tensor.shape[-2:],
'pad_shape': data_sample.gt_sem_seg.shape,
'padding_size': padding_size
})
padded_samples.append(data_sample)
else:
padded_samples.append(
dict(
img_padding_size=padding_size,
pad_shape=pad_img.shape[-2:]))
return torch.stack(padded_inputs, dim=0), padded_samples
| # Copyright (c) Open-CD. All rights reserved.
def stack_batch(inputs: List[torch.Tensor],
data_samples: Optional[SampleList] = None,
size: Optional[tuple] = None,
size_divisor: Optional[int] = None,
pad_val: Union[int, float] = 0,
seg_pad_val: Union[int, float] = 255) -> torch.Tensor:
"""Stack multiple inputs to form a batch and pad the images and gt_sem_segs
to the max shape use the right bottom padding mode.
Args:
inputs (List[Tensor]): The input multiple tensors. each is a
CHW 3D-tensor.
data_samples (list[:obj:`SegDataSample`]): The list of data samples.
It usually includes information such as `gt_sem_seg`.
size (tuple, optional): Fixed padding size.
size_divisor (int, optional): The divisor of padded size.
pad_val (int, float): The padding value. Defaults to 0
seg_pad_val (int, float): The padding value. Defaults to 255
Returns:
Tensor: The 4D-tensor.
List[:obj:`SegDataSample`]: After the padding of the gt_seg_map.
"""
assert isinstance(inputs, list), \
f'Expected input type to be list, but got {type(inputs)}'
assert len({tensor.ndim for tensor in inputs}) == 1, \
f'Expected the dimensions of all inputs must be the same, ' \
f'but got {[tensor.ndim for tensor in inputs]}'
assert inputs[0].ndim == 3, f'Expected tensor dimension to be 3, ' \
f'but got {inputs[0].ndim}'
assert len({tensor.shape[0] for tensor in inputs}) == 1, \
f'Expected the channels of all inputs must be the same, ' \
f'but got {[tensor.shape[0] for tensor in inputs]}'
# only one of size and size_divisor should be valid
assert (size is not None) ^ (size_divisor is not None), \
'only one of size and size_divisor should be valid'
padded_inputs = []
padded_samples = []
inputs_sizes = [(img.shape[-2], img.shape[-1]) for img in inputs]
max_size = np.stack(inputs_sizes).max(0)
if size_divisor is not None and size_divisor > 1:
# the last two dims are H,W, both subject to divisibility requirement
max_size = (max_size +
(size_divisor - 1)) // size_divisor * size_divisor
for i in range(len(inputs)):
tensor = inputs[i]
if size is not None:
width = max(size[-1] - tensor.shape[-1], 0)
height = max(size[-2] - tensor.shape[-2], 0)
# (padding_left, padding_right, padding_top, padding_bottom)
padding_size = (0, width, 0, height)
elif size_divisor is not None:
width = max(max_size[-1] - tensor.shape[-1], 0)
height = max(max_size[-2] - tensor.shape[-2], 0)
padding_size = (0, width, 0, height)
else:
padding_size = [0, 0, 0, 0]
# pad img
pad_img = F.pad(tensor, padding_size, value=pad_val)
padded_inputs.append(pad_img)
# pad gt_sem_seg
if data_samples is not None:
data_sample = data_samples[i]
gt_sem_seg = data_sample.gt_sem_seg.data
del data_sample.gt_sem_seg.data
data_sample.gt_sem_seg.data = F.pad(
gt_sem_seg, padding_size, value=seg_pad_val)
if 'gt_edge_map' in data_sample:
gt_edge_map = data_sample.gt_edge_map.data
del data_sample.gt_edge_map.data
data_sample.gt_edge_map.data = F.pad(
gt_edge_map, padding_size, value=seg_pad_val)
if 'gt_seg_map_from' in data_sample:
gt_seg_map_from = data_sample.gt_seg_map_from.data
del data_sample.gt_seg_map_from.data
data_sample.gt_seg_map_from.data = F.pad(
gt_seg_map_from, padding_size, value=seg_pad_val)
if 'gt_seg_map_to' in data_sample:
gt_seg_map_to = data_sample.gt_seg_map_to.data
del data_sample.gt_seg_map_to.data
data_sample.gt_seg_map_to.data = F.pad(
gt_seg_map_to, padding_size, value=seg_pad_val)
data_sample.set_metainfo({
'img_shape': tensor.shape[-2:],
'pad_shape': data_sample.gt_sem_seg.shape,
'padding_size': padding_size
})
padded_samples.append(data_sample)
else:
padded_samples.append(
dict(
img_padding_size=padding_size,
pad_shape=pad_img.shape[-2:]))
return torch.stack(padded_inputs, dim=0), padded_samples
| @MODELS.register_module() | 1 | 2023-12-23 08:36:47+00:00 | 2k |
N0rz3/Phunter | lib/lookup.py | [
{
"identifier": "free",
"path": "lib/free_lookup.py",
"snippet": "async def free(phone_number):\r\n r = await Request(\"https://free-lookup.net/{}\".format(phone_number), headers={'user-agent': random.choice(agent)}).get()\r\n\r\n html_body = BeautifulSoup(r.text, \"html.parser\")\r\n list_info... | import phonenumbers
import json
from phonenumbers import carrier
from .reputation import *
from .free_lookup import free
from .spam import spamcalls
from lib.text import *
| 809 |
async def lookup(phone_number):
print()
parsed = phonenumbers.parse(phone_number)
operator = carrier.name_for_number(parsed, "fr")
line = phonenumbers.number_type(parsed)
if line == phonenumbers.PhoneNumberType.FIXED_LINE:
ligne = f" [{GREEN}>{WHITE}] Line type: Fixed"
elif line == phonenumbers.PhoneNumberType.MOBILE:
ligne = f" [{GREEN}>{WHITE}] Line type: Mobile"
else:
ligne = " [-] Line not found"
possible = phonenumbers.is_possible_number(parsed)
valid = phonenumbers.is_valid_number(parsed)
with open("lib/country.json", "r") as file:
read = json.load(file)
d = 0
countrys = []
for country, code in read.items():
d += 1
if phone_number.startswith(code):
countrys.append(country)
if d == 153:
break
else:
continue
else:
continue
print(f"{WHITE}📞 Phone number: {BLUE}{phone_number}{WHITE}")
if possible == True:
pos = {"possible": "✔️"}
else:
pos = {"possible": "❌"}
if valid == True:
val = {"valid": "✔️"}
else:
val = {"valid": "❌"}
print(f" [{GREEN}>{WHITE}] Possible: {pos['possible']}")
print(f" [{GREEN}>{WHITE}] Valid: {val['valid']}")
print()
if operator != "":
print(f" [{GREEN}>{WHITE}] Operator: {operator}")
else:
print(f" [-] Not Operator")
try:
print(f" [{GREEN}>{WHITE}] Possible location: " + str(countrys).replace("[", "").replace("]", "").replace("'", ""))
except:
print(f" [-] Not location")
print(ligne)
await reputation(phone_number)
|
async def lookup(phone_number):
print()
parsed = phonenumbers.parse(phone_number)
operator = carrier.name_for_number(parsed, "fr")
line = phonenumbers.number_type(parsed)
if line == phonenumbers.PhoneNumberType.FIXED_LINE:
ligne = f" [{GREEN}>{WHITE}] Line type: Fixed"
elif line == phonenumbers.PhoneNumberType.MOBILE:
ligne = f" [{GREEN}>{WHITE}] Line type: Mobile"
else:
ligne = " [-] Line not found"
possible = phonenumbers.is_possible_number(parsed)
valid = phonenumbers.is_valid_number(parsed)
with open("lib/country.json", "r") as file:
read = json.load(file)
d = 0
countrys = []
for country, code in read.items():
d += 1
if phone_number.startswith(code):
countrys.append(country)
if d == 153:
break
else:
continue
else:
continue
print(f"{WHITE}📞 Phone number: {BLUE}{phone_number}{WHITE}")
if possible == True:
pos = {"possible": "✔️"}
else:
pos = {"possible": "❌"}
if valid == True:
val = {"valid": "✔️"}
else:
val = {"valid": "❌"}
print(f" [{GREEN}>{WHITE}] Possible: {pos['possible']}")
print(f" [{GREEN}>{WHITE}] Valid: {val['valid']}")
print()
if operator != "":
print(f" [{GREEN}>{WHITE}] Operator: {operator}")
else:
print(f" [-] Not Operator")
try:
print(f" [{GREEN}>{WHITE}] Possible location: " + str(countrys).replace("[", "").replace("]", "").replace("'", ""))
except:
print(f" [-] Not location")
print(ligne)
await reputation(phone_number)
| await free(str(phone_number).replace("+", ""))
| 0 | 2023-12-30 13:21:14+00:00 | 2k |
dan-r/HomeAssistant-Ohme | custom_components/ohme/binary_sensor.py | [
{
"identifier": "DOMAIN",
"path": "custom_components/ohme/const.py",
"snippet": "DOMAIN = \"ohme\""
},
{
"identifier": "DATA_COORDINATORS",
"path": "custom_components/ohme/const.py",
"snippet": "DATA_COORDINATORS = \"coordinators\""
},
{
"identifier": "COORDINATOR_CHARGESESSIONS"... | import logging
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity
)
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import generate_entity_id
from homeassistant.util.dt import (utcnow)
from .const import DOMAIN, DATA_COORDINATORS, COORDINATOR_CHARGESESSIONS, COORDINATOR_ADVANCED, DATA_CLIENT
from .coordinator import OhmeChargeSessionsCoordinator, OhmeAdvancedSettingsCoordinator
from .utils import charge_graph_in_slot | 823 | """Platform for sensor integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Setup sensors and configure coordinator."""
client = hass.data[DOMAIN][DATA_CLIENT]
| """Platform for sensor integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Setup sensors and configure coordinator."""
client = hass.data[DOMAIN][DATA_CLIENT] | coordinator = hass.data[DOMAIN][DATA_COORDINATORS][COORDINATOR_CHARGESESSIONS] | 1 | 2023-12-24 20:59:18+00:00 | 2k |
Almas-Ali/SpyIP | spyip/backend.py | [
{
"identifier": "TooManyRequests",
"path": "spyip/exceptions.py",
"snippet": "class TooManyRequests(Exception):\n pass"
},
{
"identifier": "ConnectionTimeout",
"path": "spyip/exceptions.py",
"snippet": "class ConnectionTimeout(Exception):\n pass"
},
{
"identifier": "StatusE... | from typing import List, Union
from .exceptions import (
TooManyRequests,
ConnectionTimeout,
StatusError,
)
from .models import (
IPResponse,
DNSResponse,
)
import asyncio
import random
import string
import httpx | 1,207 |
def get_random_string(length: int = 32) -> str:
"""Generate a random string of fixed length."""
letters = string.ascii_lowercase + string.digits
return ''.join(random.sample(letters, length))
# API endpoints for IP address lookup
trace_me_url = 'http://ip-api.com/json/'
trace_ip_url = 'http://ip-api.com/json/%(query)s'
trace_dns_url = f'http://{get_random_string(32)}.edns.ip-api.com/json/'
trace_ip_batch_url = 'http://ip-api.com/batch'
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.5',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
}
def trace_me(
timeout: int = 5,
lang: str = 'en',
|
def get_random_string(length: int = 32) -> str:
"""Generate a random string of fixed length."""
letters = string.ascii_lowercase + string.digits
return ''.join(random.sample(letters, length))
# API endpoints for IP address lookup
trace_me_url = 'http://ip-api.com/json/'
trace_ip_url = 'http://ip-api.com/json/%(query)s'
trace_dns_url = f'http://{get_random_string(32)}.edns.ip-api.com/json/'
trace_ip_batch_url = 'http://ip-api.com/batch'
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.5',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
}
def trace_me(
timeout: int = 5,
lang: str = 'en', | ) -> Union[IPResponse, None]: | 3 | 2023-12-31 19:43:38+00:00 | 2k |
leopedroso45/Stable-Diffusion-ImageGen | tests/test_process_task.py | [
{
"identifier": "check_cuda_and_clear_cache",
"path": "sevsd/process_task.py",
"snippet": "def check_cuda_and_clear_cache():\n r\"\"\"\n Clears the CUDA cache if available, otherwise performs garbage collection.\n This function is called to manage memory usage, particularly when working with la... | import unittest
import sys
from unittest.mock import patch, MagicMock
from sevsd.process_task import check_cuda_and_clear_cache, process_task, check_os_path | 991 | sys.path.append('../')
class TestProcessTask(unittest.TestCase):
@patch('sevsd.process_task.generate_image')
def test_process_task(self, mock_generate_image):
mock_image = MagicMock()
mock_image.save = MagicMock()
mock_generate_image.return_value = [mock_image]
fake_job = {"prompt": "prompt", "details": (None, 50, 1, 7.5)}
fake_pipeline = MagicMock()
fake_executor = {"num_of_exec": 1, "cfg_scale": 7}
fake_path = "test_path"
| sys.path.append('../')
class TestProcessTask(unittest.TestCase):
@patch('sevsd.process_task.generate_image')
def test_process_task(self, mock_generate_image):
mock_image = MagicMock()
mock_image.save = MagicMock()
mock_generate_image.return_value = [mock_image]
fake_job = {"prompt": "prompt", "details": (None, 50, 1, 7.5)}
fake_pipeline = MagicMock()
fake_executor = {"num_of_exec": 1, "cfg_scale": 7}
fake_path = "test_path"
| process_task(fake_job, fake_pipeline, fake_executor, fake_path, parallel_exec=True) | 1 | 2023-12-28 16:19:12+00:00 | 2k |
Emperor-WS/PyEmber | ember/autograd/numeric.py | [
{
"identifier": "Hook",
"path": "ember/autograd/hook.py",
"snippet": "class Hook:\n \"\"\"\n Hook class for attaching gradient functions to tensors.\n\n Hooks allow users to attach custom gradient functions to tensors for\n monitoring or modifying gradients during backpropagation.\n\n Att... | import numpy as np
import ember
from .hook import Hook
from ._utils import numpy_unpad, inv_permutation | 742 |
def _T(t):
"""
Transpose operation on the input tensor.
Args:
- t: Input tensor.
Returns:
- Tensor: Resultant tensor with the transpose operation applied.
"""
t = ember.to_tensor(t) # Convert the input tensor to a Tensor
data = t.data.T # Transpose operation
requires_grad = t.requires_grad # Set requires_grad based on input tensor
hooks = []
# Register a hook for gradient computation if the input tensor requires it
if requires_grad:
|
def _T(t):
"""
Transpose operation on the input tensor.
Args:
- t: Input tensor.
Returns:
- Tensor: Resultant tensor with the transpose operation applied.
"""
t = ember.to_tensor(t) # Convert the input tensor to a Tensor
data = t.data.T # Transpose operation
requires_grad = t.requires_grad # Set requires_grad based on input tensor
hooks = []
# Register a hook for gradient computation if the input tensor requires it
if requires_grad: | hooks.append(Hook(t, lambda grad: grad.T)) | 0 | 2023-12-23 23:11:58+00:00 | 2k |
Hassi34/iot-device-identification | src/stage_03_preprocess_data.py | [
{
"identifier": "read_yaml",
"path": "src/utils/common.py",
"snippet": "def read_yaml(path_to_yaml: str) -> dict:\n with open(path_to_yaml) as yaml_file:\n content = yaml.safe_load(yaml_file)\n return content"
},
{
"identifier": "get_logger",
"path": "src/utils/sys_logging.py",
... | import argparse
import joblib
import pandas as pd
from src.utils.common import read_yaml
from src.utils.sys_logging import get_logger
from sklearn.preprocessing import LabelEncoder
from src.utils.common import write_dict_to_yaml
from src.utils.data_ops import gzip_np_arr
from sklearn.model_selection import train_test_split
from src.utils.data_ops import get_fitted_pipeline
from pathlib import Path | 1,022 |
STAGE = "Preprocess Data"
def preprocess_data():
complete_df = pd.read_parquet(RAW_DATA_FILE_PATH)
logger.info(
f'The raw data file has been loaded from "{RAW_DATA_FILE_PATH}" with the shape "{complete_df.shape}"'
)
duplicate_rows = complete_df.duplicated().sum()
if duplicate_rows > 0:
logger.warning(
f"Found {duplicate_rows} duplicate rows, removing duplicate rows..."
)
complete_df = complete_df.drop_duplicates(keep="first")
X = complete_df.drop([TARGET_COLUMN_NAME], axis=1)
y = complete_df[TARGET_COLUMN_NAME]
feature_cols = params["input_features_schema"]
feature_cols = list(feature_cols.keys())
logger.info(f"Read {len(feature_cols)} feature columns from params")
data_processing_pipeline = get_fitted_pipeline(
X, feature_cols, KNN_IMPUTER_NEIGHBORS=KNN_IMPUTER_NEIGHBORS
)
Path(DATA_PREPROCESSING_PIPELINE_FILE_PATH).parent.absolute().mkdir(parents=True, exist_ok=True)
joblib.dump(data_processing_pipeline, DATA_PREPROCESSING_PIPELINE_FILE_PATH, compress=1)
logger.info(f"Saved the preprocessing pipeline to {DATA_PREPROCESSING_PIPELINE_FILE_PATH}")
data_processing_pipeline = joblib.load(DATA_PREPROCESSING_PIPELINE_FILE_PATH)
data_processing_pipeline
data_processing_pipeline = joblib.load(DATA_PREPROCESSING_PIPELINE_FILE_PATH)
logger.info(
f'Loaded sklearn data preprocessing pipeline from "{DATA_PREPROCESSING_PIPELINE_FILE_PATH}"'
)
X_transformed = data_processing_pipeline.transform(X)
logger.info(f'Dataframe shape after transformation is "{X_transformed.shape}"')
le = LabelEncoder()
le.fit(y)
labels_mapping_dict = {"labels_mapping": ""}
le_dict = dict(zip(le.transform(le.classes_), le.classes_))
le_dict = {int(k): v for k, v in le_dict.items()}
labels_mapping_dict["labels_mapping"] = le_dict
logger.info(f"Label encoding map has the dictionary: {le_dict}")
write_dict_to_yaml(labels_mapping_dict, parsed_args.params)
logger.info(f'Updated the label encoding map in the file at "{parsed_args.params}"')
|
STAGE = "Preprocess Data"
def preprocess_data():
complete_df = pd.read_parquet(RAW_DATA_FILE_PATH)
logger.info(
f'The raw data file has been loaded from "{RAW_DATA_FILE_PATH}" with the shape "{complete_df.shape}"'
)
duplicate_rows = complete_df.duplicated().sum()
if duplicate_rows > 0:
logger.warning(
f"Found {duplicate_rows} duplicate rows, removing duplicate rows..."
)
complete_df = complete_df.drop_duplicates(keep="first")
X = complete_df.drop([TARGET_COLUMN_NAME], axis=1)
y = complete_df[TARGET_COLUMN_NAME]
feature_cols = params["input_features_schema"]
feature_cols = list(feature_cols.keys())
logger.info(f"Read {len(feature_cols)} feature columns from params")
data_processing_pipeline = get_fitted_pipeline(
X, feature_cols, KNN_IMPUTER_NEIGHBORS=KNN_IMPUTER_NEIGHBORS
)
Path(DATA_PREPROCESSING_PIPELINE_FILE_PATH).parent.absolute().mkdir(parents=True, exist_ok=True)
joblib.dump(data_processing_pipeline, DATA_PREPROCESSING_PIPELINE_FILE_PATH, compress=1)
logger.info(f"Saved the preprocessing pipeline to {DATA_PREPROCESSING_PIPELINE_FILE_PATH}")
data_processing_pipeline = joblib.load(DATA_PREPROCESSING_PIPELINE_FILE_PATH)
data_processing_pipeline
data_processing_pipeline = joblib.load(DATA_PREPROCESSING_PIPELINE_FILE_PATH)
logger.info(
f'Loaded sklearn data preprocessing pipeline from "{DATA_PREPROCESSING_PIPELINE_FILE_PATH}"'
)
X_transformed = data_processing_pipeline.transform(X)
logger.info(f'Dataframe shape after transformation is "{X_transformed.shape}"')
le = LabelEncoder()
le.fit(y)
labels_mapping_dict = {"labels_mapping": ""}
le_dict = dict(zip(le.transform(le.classes_), le.classes_))
le_dict = {int(k): v for k, v in le_dict.items()}
labels_mapping_dict["labels_mapping"] = le_dict
logger.info(f"Label encoding map has the dictionary: {le_dict}")
write_dict_to_yaml(labels_mapping_dict, parsed_args.params)
logger.info(f'Updated the label encoding map in the file at "{parsed_args.params}"') | labels_dict = read_yaml(parsed_args.params)["labels_mapping"] | 0 | 2023-12-25 10:40:19+00:00 | 2k |
see2023/Bert-VITS2-ext | for_deploy/infer_utils.py | [
{
"identifier": "config",
"path": "config.py",
"snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, ... | import sys
import torch
from transformers import (
AutoModelForMaskedLM,
AutoTokenizer,
DebertaV2Model,
DebertaV2Tokenizer,
ClapModel,
ClapProcessor,
)
from config import config
from text.japanese import text2sep_kata | 1,223 |
class BertFeature:
def __init__(self, model_path, language="ZH"):
self.model_path = model_path
self.language = language
self.tokenizer = None
self.model = None
self.device = None
self._prepare()
def _get_device(self, device=config.bert_gen_config.device):
if (
sys.platform == "darwin"
and torch.backends.mps.is_available()
and device == "cpu"
):
device = "mps"
if not device:
device = "cuda"
return device
def _prepare(self):
self.device = self._get_device()
if self.language == "EN":
self.tokenizer = DebertaV2Tokenizer.from_pretrained(self.model_path)
self.model = DebertaV2Model.from_pretrained(self.model_path).to(self.device)
else:
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
self.model = AutoModelForMaskedLM.from_pretrained(self.model_path).to(
self.device
)
self.model.eval()
def get_bert_feature(self, text, word2ph):
if self.language == "JP":
|
class BertFeature:
def __init__(self, model_path, language="ZH"):
self.model_path = model_path
self.language = language
self.tokenizer = None
self.model = None
self.device = None
self._prepare()
def _get_device(self, device=config.bert_gen_config.device):
if (
sys.platform == "darwin"
and torch.backends.mps.is_available()
and device == "cpu"
):
device = "mps"
if not device:
device = "cuda"
return device
def _prepare(self):
self.device = self._get_device()
if self.language == "EN":
self.tokenizer = DebertaV2Tokenizer.from_pretrained(self.model_path)
self.model = DebertaV2Model.from_pretrained(self.model_path).to(self.device)
else:
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
self.model = AutoModelForMaskedLM.from_pretrained(self.model_path).to(
self.device
)
self.model.eval()
def get_bert_feature(self, text, word2ph):
if self.language == "JP": | text = "".join(text2sep_kata(text)[0]) | 1 | 2023-12-27 03:09:11+00:00 | 2k |
chinhsuanwu/ifusion-threestudio | threestudio/models/materials/no_material.py | [
{
"identifier": "BaseMaterial",
"path": "threestudio/models/materials/base.py",
"snippet": "class BaseMaterial(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n requires_normal: bool = False\n requires_tangent: bool = False\n\n def configure(s... | import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import threestudio
from dataclasses import dataclass, field
from threestudio.models.materials.base import BaseMaterial
from threestudio.models.networks import get_encoding, get_mlp
from threestudio.utils.ops import dot, get_activation
from threestudio.utils.typing import * | 1,291 |
@threestudio.register("no-material")
class NoMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
n_output_dims: int = 3
color_activation: str = "sigmoid"
input_feature_dims: Optional[int] = None
mlp_network_config: Optional[dict] = None
requires_normal: bool = False
cfg: Config
def configure(self) -> None:
self.use_network = False
if (
self.cfg.input_feature_dims is not None
and self.cfg.mlp_network_config is not None
):
self.network = get_mlp(
self.cfg.input_feature_dims,
self.cfg.n_output_dims,
self.cfg.mlp_network_config,
)
self.use_network = True
self.requires_normal = self.cfg.requires_normal
def forward(
self, features: Float[Tensor, "B ... Nf"], **kwargs
) -> Float[Tensor, "B ... Nc"]:
if not self.use_network:
assert (
features.shape[-1] == self.cfg.n_output_dims
), f"Expected {self.cfg.n_output_dims} output dims, only got {features.shape[-1]} dims input."
|
@threestudio.register("no-material")
class NoMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
n_output_dims: int = 3
color_activation: str = "sigmoid"
input_feature_dims: Optional[int] = None
mlp_network_config: Optional[dict] = None
requires_normal: bool = False
cfg: Config
def configure(self) -> None:
self.use_network = False
if (
self.cfg.input_feature_dims is not None
and self.cfg.mlp_network_config is not None
):
self.network = get_mlp(
self.cfg.input_feature_dims,
self.cfg.n_output_dims,
self.cfg.mlp_network_config,
)
self.use_network = True
self.requires_normal = self.cfg.requires_normal
def forward(
self, features: Float[Tensor, "B ... Nf"], **kwargs
) -> Float[Tensor, "B ... Nc"]:
if not self.use_network:
assert (
features.shape[-1] == self.cfg.n_output_dims
), f"Expected {self.cfg.n_output_dims} output dims, only got {features.shape[-1]} dims input." | color = get_activation(self.cfg.color_activation)(features) | 4 | 2023-12-27 20:30:33+00:00 | 2k |
jasursadikov/mud | commands.py | [
{
"identifier": "TEXT",
"path": "utils.py",
"snippet": "TEXT = {\n 'white': '\\033[37m',\n 'gray': '\\033[90m',\n 'black': '\\033[30m',\n 'red': '\\033[31m',\n 'green': '\\033[32m',\n 'yellow': '\\033[33m',\n 'blue': '\\033[34m',\n 'magenta': '\\033[35m',\n 'cyan': '\\033[36m'... | import utils
import asyncio
import subprocess
from utils import TEXT, BACK, RESET, STYLES, END_STYLES, glyph
from typing import List, Dict
from collections import Counter
from prettytable import PrettyTable, PLAIN_COLUMNS | 880 |
class Commands:
def __init__(self, repos):
self.repos = repos
self.label_color_cache = {}
self.current_color_index = 0
# `mud status` command implementation
def status(self, repos: Dict[str, List[str]]) -> None:
table = self._get_table()
for path, tags in repos.items():
formatted_path = self._get_formatted_path(path)
branch = self._get_branch_status(path)
author = self._get_authors_name(path)
commit = self._get_commit_message(path, 30)
colored_labels = self._get_formatted_labels(tags)
# Sync with origin status
ahead_behind_cmd = subprocess.run(['git', 'rev-list', '--left-right', '--count', 'HEAD...@{upstream}'],
text=True, cwd=path, capture_output=True)
stdout = ahead_behind_cmd.stdout.strip().split()
if len(stdout) >= 2:
ahead, behind = stdout[0], stdout[1]
origin_sync = ''
if ahead and ahead != '0':
|
class Commands:
def __init__(self, repos):
self.repos = repos
self.label_color_cache = {}
self.current_color_index = 0
# `mud status` command implementation
def status(self, repos: Dict[str, List[str]]) -> None:
table = self._get_table()
for path, tags in repos.items():
formatted_path = self._get_formatted_path(path)
branch = self._get_branch_status(path)
author = self._get_authors_name(path)
commit = self._get_commit_message(path, 30)
colored_labels = self._get_formatted_labels(tags)
# Sync with origin status
ahead_behind_cmd = subprocess.run(['git', 'rev-list', '--left-right', '--count', 'HEAD...@{upstream}'],
text=True, cwd=path, capture_output=True)
stdout = ahead_behind_cmd.stdout.strip().split()
if len(stdout) >= 2:
ahead, behind = stdout[0], stdout[1]
origin_sync = ''
if ahead and ahead != '0': | origin_sync += f'{TEXT["bright_green"]}{glyph("ahead")} {ahead}{RESET}' | 5 | 2023-12-28 13:09:31+00:00 | 2k |
Q-MM/PureMM | model/PureMM_arch.py | [
{
"identifier": "build_vision_tower",
"path": "model/multimodal_encoder/builder.py",
"snippet": "def build_vision_tower(vision_tower_cfg, **kwargs):\n vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))\n is_absolute_path_exists = os.path.ex... | from abc import ABC, abstractmethod
from .multimodal_encoder.builder import build_vision_tower
from .multimodal_projector.builder import build_vision_projector
import torch
import torch.nn as nn | 837 | # Copyright 2023 Haotian Liu
#
# 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.
IGNORE_INDEX = -100
IMAGE_TOKEN_INDEX = -200
DEFAULT_IMAGE_TOKEN = "<image>"
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
DEFAULT_IM_START_TOKEN = "<im_start>"
DEFAULT_IM_END_TOKEN = "<im_end>"
def rank0_print(rank, *args):
if rank == 0:
print(*args)
class PureMMMetaModel:
def __init__(self, config):
super(PureMMMetaModel, self).__init__(config)
if hasattr(config, "mm_vision_tower"):
self.vision_tower = build_vision_tower(config, delay_load=True)
# self.mm_projector = nn.Linear(config.mm_hidden_size, config.hidden_size)
| # Copyright 2023 Haotian Liu
#
# 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.
IGNORE_INDEX = -100
IMAGE_TOKEN_INDEX = -200
DEFAULT_IMAGE_TOKEN = "<image>"
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
DEFAULT_IM_START_TOKEN = "<im_start>"
DEFAULT_IM_END_TOKEN = "<im_end>"
def rank0_print(rank, *args):
if rank == 0:
print(*args)
class PureMMMetaModel:
def __init__(self, config):
super(PureMMMetaModel, self).__init__(config)
if hasattr(config, "mm_vision_tower"):
self.vision_tower = build_vision_tower(config, delay_load=True)
# self.mm_projector = nn.Linear(config.mm_hidden_size, config.hidden_size) | self.mm_projector = build_vision_projector(config) | 1 | 2023-12-27 09:54:09+00:00 | 2k |
Ananya2001-an/spotify-py-sdk | tests/endpoints/test_recommendations.py | [
{
"identifier": "SpotifyApi",
"path": "spotify_py_sdk/spotify_api.py",
"snippet": "class SpotifyApi:\n \"\"\"Create an api instance and call the various endpoint methods.\n\n :param client_id: Client_ID for your app\n :type client_id: str\n :param client_secret: Client_Secret for your app\n ... | import json
import pytest
import os
from spotify_py_sdk import SpotifyApi
from spotify_py_sdk.endpoints.recommendations import RecommendationsRequestRequiredArguments
from dotenv import load_dotenv | 1,007 |
load_dotenv()
@pytest.fixture
def api():
|
load_dotenv()
@pytest.fixture
def api(): | return SpotifyApi(os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET")) | 0 | 2023-12-27 20:12:31+00:00 | 2k |
kyleliang919/Optimizer-Zoo | optimizer_zoo/Trainer/utils.py | [
{
"identifier": "AsyncTrainer",
"path": "optimizer_zoo/Trainer/async_trainer.py",
"snippet": "class AsyncTrainer(Trainer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.accelerator.sync_gradients = None\n\n def training_step(self, model, inputs):\n... | from transformers import Trainer, Seq2SeqTrainer
from trl import SFTTrainer, DPOTrainer
from .async_trainer import AsyncTrainer, AsyncSFTTrainer, AsyncDPOTrainer, AsyncSeq2SeqTrainer | 1,215 | def create_trainer(training_args):
if training_args.task == "pretraining":
return AsyncTrainer if training_args.async_grad else Trainer
elif training_args.task == "sft":
return AsyncSFTTrainer if training_args.async_grad else SFTTrainer
elif training_args.task == "dpo":
return AsyncDPOTrainer if training_args.async_grad else DPOTrainer
elif training_args.task == "seq2seq":
| def create_trainer(training_args):
if training_args.task == "pretraining":
return AsyncTrainer if training_args.async_grad else Trainer
elif training_args.task == "sft":
return AsyncSFTTrainer if training_args.async_grad else SFTTrainer
elif training_args.task == "dpo":
return AsyncDPOTrainer if training_args.async_grad else DPOTrainer
elif training_args.task == "seq2seq": | return AsyncSeq2SeqTrainer if training_args.async_grad else Seq2SeqTrainer | 3 | 2023-12-22 17:07:00+00:00 | 2k |
giaminhgist/3D-DAM | lib/model/DuoAttention.py | [
{
"identifier": "SpatialAttention3D",
"path": "lib/model/attention_block.py",
"snippet": "class SpatialAttention3D(nn.Module):\n def __init__(self, out_channel=64, kernel_size=3, stride=1, padding=1):\n super(SpatialAttention3D, self).__init__()\n\n self.conv = nn.Conv3d(2, out_channel,... | import numpy as np
import torch
from torch import nn
from lib.model.attention_block import SpatialAttention3D, ChannelAttention3D, residual_block | 804 |
class DAM(nn.Module):
def __init__(self, channels=64):
super(DAM, self).__init__()
self.sa = SpatialAttention3D(out_channel=channels)
self.ca = ChannelAttention3D(in_planes=channels)
def forward(self, x):
residual = x
out = self.ca(x)
out = self.sa(out)
out = out + residual
return out
class Duo_Attention(nn.Module):
def __init__(
self, input_size=(1, 169, 208, 179), num_classes=3, dropout=0
):
super().__init__()
self.conv = nn.Sequential(
nn.Conv3d(input_size[0], 8, 3, padding=1),
nn.BatchNorm3d(8),
nn.ReLU(),
# nn.MaxPool3d(2, 2),
nn.Conv3d(8, 16, 3, padding=1, stride=2),
nn.BatchNorm3d(16),
nn.ReLU(),
|
class DAM(nn.Module):
def __init__(self, channels=64):
super(DAM, self).__init__()
self.sa = SpatialAttention3D(out_channel=channels)
self.ca = ChannelAttention3D(in_planes=channels)
def forward(self, x):
residual = x
out = self.ca(x)
out = self.sa(out)
out = out + residual
return out
class Duo_Attention(nn.Module):
def __init__(
self, input_size=(1, 169, 208, 179), num_classes=3, dropout=0
):
super().__init__()
self.conv = nn.Sequential(
nn.Conv3d(input_size[0], 8, 3, padding=1),
nn.BatchNorm3d(8),
nn.ReLU(),
# nn.MaxPool3d(2, 2),
nn.Conv3d(8, 16, 3, padding=1, stride=2),
nn.BatchNorm3d(16),
nn.ReLU(), | residual_block(channel_size=16), | 2 | 2023-12-22 10:15:55+00:00 | 2k |
itsluminous/EasyEncryption | script.py | [
{
"identifier": "generate_key",
"path": "core.py",
"snippet": "def generate_key():\n \"\"\"Generate a Fernet key.\"\"\"\n return Fernet.generate_key()"
},
{
"identifier": "encrypt_message",
"path": "core.py",
"snippet": "def encrypt_message(message, key):\n \"\"\"Encrypt a messa... | from core import generate_key, encrypt_message, decrypt_message, encrypt_file, decrypt_file | 783 | """
Script providing a user interface for encryption and decryption operations.
"""
def generate_new_key():
"""
Generate a new encryption key.
Returns:
- bytes: New encryption key.
"""
key = generate_key()
print(f"\nGenerated Key: {key.decode()}")
return key
def enter_user_key():
"""
Prompt user to enter a key.
Returns:
- bytes: User-entered key.
"""
print("\nEnter the key:")
return input().encode()
def encrypt_user_message(key):
"""
Encrypt a user-entered message.
Parameters:
- key (bytes): Encryption key.
"""
if key is None:
print("\nPlease generate or enter a key first.")
else:
print("\nEnter a message to encrypt (press Enter twice to finish):")
lines = []
while True:
line = input()
if not line:
break
lines.append(line)
user_input = '\n'.join(lines)
encrypted_message = encrypt_message(user_input, key)
print(f"\nEncrypted message: {encrypted_message}")
def decrypt_user_message(key):
"""
Decrypt a user-entered message.
Parameters:
- key (bytes): Decryption key.
"""
if key is None:
print("\nPlease generate or enter a key first.")
else:
print("\nEnter the encrypted message (press Enter twice to finish):")
lines = []
while True:
line = input()
if not line:
break
lines.append(line)
encrypted_input = '\n'.join(lines)
| """
Script providing a user interface for encryption and decryption operations.
"""
def generate_new_key():
"""
Generate a new encryption key.
Returns:
- bytes: New encryption key.
"""
key = generate_key()
print(f"\nGenerated Key: {key.decode()}")
return key
def enter_user_key():
"""
Prompt user to enter a key.
Returns:
- bytes: User-entered key.
"""
print("\nEnter the key:")
return input().encode()
def encrypt_user_message(key):
"""
Encrypt a user-entered message.
Parameters:
- key (bytes): Encryption key.
"""
if key is None:
print("\nPlease generate or enter a key first.")
else:
print("\nEnter a message to encrypt (press Enter twice to finish):")
lines = []
while True:
line = input()
if not line:
break
lines.append(line)
user_input = '\n'.join(lines)
encrypted_message = encrypt_message(user_input, key)
print(f"\nEncrypted message: {encrypted_message}")
def decrypt_user_message(key):
"""
Decrypt a user-entered message.
Parameters:
- key (bytes): Decryption key.
"""
if key is None:
print("\nPlease generate or enter a key first.")
else:
print("\nEnter the encrypted message (press Enter twice to finish):")
lines = []
while True:
line = input()
if not line:
break
lines.append(line)
encrypted_input = '\n'.join(lines) | decrypted_message = decrypt_message(encrypted_input.encode(), key) | 2 | 2023-12-31 13:24:53+00:00 | 2k |
gardenifi/server | tests/api/resource_not_found_test.py | [
{
"identifier": "app",
"path": "app/main_app.py",
"snippet": "INVALID_DATA = \"Invalid data: Unable to process the provided data\"\nclass GlobalVars:\nclass WifiData(BaseModel):\nclass ValveData(BaseModel):\nclass BleData(BaseModel):\n def __init__(self):\n def refresh_set(self):\n def refresh_... | import json
import pytest
from fastapi.testclient import TestClient
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
from app.main_app import app
from app.main_app import resource_not_found | 712 | """MIT License
Copyright (c) 2023, Marios Karagiannopoulos
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.
**Attribution Requirement:**
When using or distributing the software, an attribution to Marios Karagiannopoulos must be included.
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.
"""
client = TestClient(app)
scope = {"type": "http", "http_version": "1.1", "method": "GET", "path": "/"}
@pytest.fixture(scope="function")
async def request_obj():
"""Request object creation fixture"""
return Request(scope)
class TestResourceNotFound:
"""
Test class for the 'resource_not_found' error handler function.
"""
@pytest.mark.asyncio
async def test_returns_json_response_with_status_code_404_and_detail_of_httpexception(self, obj=request_obj):
"""
Test for returning a JSONResponse object with status code 404 and the detail of the HTTPException passed as an argument.
"""
exc = HTTPException(status_code=404, detail="Not found")
| """MIT License
Copyright (c) 2023, Marios Karagiannopoulos
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.
**Attribution Requirement:**
When using or distributing the software, an attribution to Marios Karagiannopoulos must be included.
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.
"""
client = TestClient(app)
scope = {"type": "http", "http_version": "1.1", "method": "GET", "path": "/"}
@pytest.fixture(scope="function")
async def request_obj():
"""Request object creation fixture"""
return Request(scope)
class TestResourceNotFound:
"""
Test class for the 'resource_not_found' error handler function.
"""
@pytest.mark.asyncio
async def test_returns_json_response_with_status_code_404_and_detail_of_httpexception(self, obj=request_obj):
"""
Test for returning a JSONResponse object with status code 404 and the detail of the HTTPException passed as an argument.
"""
exc = HTTPException(status_code=404, detail="Not found") | response = await resource_not_found(obj, exc) | 1 | 2023-12-22 08:06:09+00:00 | 2k |
xiaoye0x0/pfgo_tg_bot | utils/task/set_args.py | [
{
"identifier": "Task",
"path": "utils/task/model.py",
"snippet": "class Task(metaclass=SingletonMeta):\n def __init__(self, args) -> None:\n self.conf_file = args.config\n\n self.bot_token: str = \"\"\n\n self.pfgo_url: str = \"\"\n self.username: str = \"\"\n self... | import os
import argparse
from .model import Task
from ..log import Logmanager | 838 |
def is_file_exists(file_path) -> bool:
r = os.path.exists(file_path)
if not r:
LOGGER.error(f"文件{file_path}不存在")
return r
def create_folder_if_not_exists(folder_path):
if not folder_path:
return
if not os.path.exists(folder_path):
os.makedirs(folder_path)
def parse_command_line_args():
"""
-c --config: 配置文件
--log: 日志存放位置
"""
parser = argparse.ArgumentParser(description="运行参数")
parser.add_argument("--config", "-c", type=str, default="./config.ini", help="配置文件")
parser.add_argument("--log", type=str, default="./", help="日志存放文件夹的位置,默认放到当前路径")
args = parser.parse_args()
# 初始化日志模块
global LOGGER
create_folder_if_not_exists(args.log)
|
def is_file_exists(file_path) -> bool:
r = os.path.exists(file_path)
if not r:
LOGGER.error(f"文件{file_path}不存在")
return r
def create_folder_if_not_exists(folder_path):
if not folder_path:
return
if not os.path.exists(folder_path):
os.makedirs(folder_path)
def parse_command_line_args():
"""
-c --config: 配置文件
--log: 日志存放位置
"""
parser = argparse.ArgumentParser(description="运行参数")
parser.add_argument("--config", "-c", type=str, default="./config.ini", help="配置文件")
parser.add_argument("--log", type=str, default="./", help="日志存放文件夹的位置,默认放到当前路径")
args = parser.parse_args()
# 初始化日志模块
global LOGGER
create_folder_if_not_exists(args.log) | Logmanager(args.log) | 1 | 2023-12-28 08:55:04+00:00 | 2k |
shibing624/chatgpt-webui | src/index_func.py | [
{
"identifier": "local_embedding",
"path": "src/config.py",
"snippet": "def retrieve_openai_api(api_key=None):\ndef retrieve_proxy(proxy=None):\ndef update_doc_config(two_column_pdf):"
},
{
"identifier": "OPENAI_API_BASE",
"path": "src/presets.py",
"snippet": "OPENAI_API_BASE = \"https:/... | import os
import re
import PyPDF2
from typing import List, Optional, Any
from langchain.schema import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from loguru import logger
from tqdm import tqdm
from src.config import local_embedding, retrieve_proxy, chunk_overlap, chunk_size, hf_emb_model_name
from src.presets import OPENAI_API_BASE
from src.utils import excel_to_string, get_files_hash, load_pkl, save_pkl
from src.pdf_func import parse_pdf
from src.config import advance_docs
from langchain.document_loaders import UnstructuredWordDocumentLoader
from langchain.document_loaders import UnstructuredPowerPointLoader
from langchain.document_loaders import UnstructuredEPubLoader
from langchain.document_loaders import TextLoader
from langchain.vectorstores import FAISS
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from langchain.embeddings import OpenAIEmbeddings | 1,337 |
pwd_path = os.path.abspath(os.path.dirname(__file__))
class ChineseRecursiveTextSplitter(RecursiveCharacterTextSplitter):
"""Recursive text splitter for Chinese text.
copy from: https://github.com/chatchat-space/Langchain-Chatchat/tree/master
"""
def __init__(
self,
separators: Optional[List[str]] = None,
keep_separator: bool = True,
is_separator_regex: bool = True,
**kwargs: Any,
) -> None:
"""Create a new TextSplitter."""
super().__init__(keep_separator=keep_separator, **kwargs)
self._separators = separators or [
"\n\n",
"\n",
"。|!|?",
"\.\s|\!\s|\?\s",
";|;\s",
",|,\s"
]
self._is_separator_regex = is_separator_regex
@staticmethod
def _split_text_with_regex_from_end(
text: str, separator: str, keep_separator: bool
) -> List[str]:
# Now that we have the separator, split the text
if separator:
if keep_separator:
# The parentheses in the pattern keep the delimiters in the result.
_splits = re.split(f"({separator})", text)
splits = ["".join(i) for i in zip(_splits[0::2], _splits[1::2])]
if len(_splits) % 2 == 1:
splits += _splits[-1:]
else:
splits = re.split(separator, text)
else:
splits = list(text)
return [s for s in splits if s != ""]
def _split_text(self, text: str, separators: List[str]) -> List[str]:
"""Split incoming text and return chunks."""
final_chunks = []
# Get appropriate separator to use
separator = separators[-1]
new_separators = []
for i, _s in enumerate(separators):
_separator = _s if self._is_separator_regex else re.escape(_s)
if _s == "":
separator = _s
break
if re.search(_separator, text):
separator = _s
new_separators = separators[i + 1:]
break
_separator = separator if self._is_separator_regex else re.escape(separator)
splits = self._split_text_with_regex_from_end(text, _separator, self._keep_separator)
# Now go merging things, recursively splitting longer texts.
_good_splits = []
_separator = "" if self._keep_separator else separator
for s in splits:
if self._length_function(s) < self._chunk_size:
_good_splits.append(s)
else:
if _good_splits:
merged_text = self._merge_splits(_good_splits, _separator)
final_chunks.extend(merged_text)
_good_splits = []
if not new_separators:
final_chunks.append(s)
else:
other_info = self._split_text(s, new_separators)
final_chunks.extend(other_info)
if _good_splits:
merged_text = self._merge_splits(_good_splits, _separator)
final_chunks.extend(merged_text)
return [re.sub(r"\n{2,}", "\n", chunk.strip()) for chunk in final_chunks if chunk.strip() != ""]
def get_documents(file_paths):
|
pwd_path = os.path.abspath(os.path.dirname(__file__))
class ChineseRecursiveTextSplitter(RecursiveCharacterTextSplitter):
"""Recursive text splitter for Chinese text.
copy from: https://github.com/chatchat-space/Langchain-Chatchat/tree/master
"""
def __init__(
self,
separators: Optional[List[str]] = None,
keep_separator: bool = True,
is_separator_regex: bool = True,
**kwargs: Any,
) -> None:
"""Create a new TextSplitter."""
super().__init__(keep_separator=keep_separator, **kwargs)
self._separators = separators or [
"\n\n",
"\n",
"。|!|?",
"\.\s|\!\s|\?\s",
";|;\s",
",|,\s"
]
self._is_separator_regex = is_separator_regex
@staticmethod
def _split_text_with_regex_from_end(
text: str, separator: str, keep_separator: bool
) -> List[str]:
# Now that we have the separator, split the text
if separator:
if keep_separator:
# The parentheses in the pattern keep the delimiters in the result.
_splits = re.split(f"({separator})", text)
splits = ["".join(i) for i in zip(_splits[0::2], _splits[1::2])]
if len(_splits) % 2 == 1:
splits += _splits[-1:]
else:
splits = re.split(separator, text)
else:
splits = list(text)
return [s for s in splits if s != ""]
def _split_text(self, text: str, separators: List[str]) -> List[str]:
"""Split incoming text and return chunks."""
final_chunks = []
# Get appropriate separator to use
separator = separators[-1]
new_separators = []
for i, _s in enumerate(separators):
_separator = _s if self._is_separator_regex else re.escape(_s)
if _s == "":
separator = _s
break
if re.search(_separator, text):
separator = _s
new_separators = separators[i + 1:]
break
_separator = separator if self._is_separator_regex else re.escape(separator)
splits = self._split_text_with_regex_from_end(text, _separator, self._keep_separator)
# Now go merging things, recursively splitting longer texts.
_good_splits = []
_separator = "" if self._keep_separator else separator
for s in splits:
if self._length_function(s) < self._chunk_size:
_good_splits.append(s)
else:
if _good_splits:
merged_text = self._merge_splits(_good_splits, _separator)
final_chunks.extend(merged_text)
_good_splits = []
if not new_separators:
final_chunks.append(s)
else:
other_info = self._split_text(s, new_separators)
final_chunks.extend(other_info)
if _good_splits:
merged_text = self._merge_splits(_good_splits, _separator)
final_chunks.extend(merged_text)
return [re.sub(r"\n{2,}", "\n", chunk.strip()) for chunk in final_chunks if chunk.strip() != ""]
def get_documents(file_paths): | text_splitter = ChineseRecursiveTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap) | 0 | 2023-12-27 12:14:26+00:00 | 2k |
ConnectAI-E/GitMaya | server/tasks/lark/pull_request.py | [
{
"identifier": "get_bot_by_application_id",
"path": "server/tasks/lark/base.py",
"snippet": "def get_bot_by_application_id(app_id):\n application = (\n db.session.query(IMApplication)\n .filter(\n or_(\n IMApplication.app_id == app_id,\n IMAppli... | import json
import logging
from celery_app import app, celery
from connectai.lark.sdk import FeishuTextMessage
from model.schema import (
ChatGroup,
CodeApplication,
CodeUser,
IMUser,
PullRequest,
Repo,
Team,
TeamMember,
db,
)
from model.team import get_assignees_by_openid
from utils.github.repo import GitHubAppRepo
from utils.lark.pr_card import PullCard
from utils.lark.pr_manual import (
PrManual,
PullRequestDiff,
PullRequestLog,
PullRequestView,
)
from utils.lark.pr_tip_failed import PrTipFailed
from utils.lark.pr_tip_success import PrTipSuccess
from .base import (
get_bot_by_application_id,
get_git_object_by_message_id,
with_authenticated_github,
) | 930 |
@celery.task()
def send_pull_request_failed_tip(
content, app_id, message_id, *args, bot=None, **kwargs
):
"""send new card message to user.
Args:
app_id: IMApplication.app_id.
message_id: lark message id.
content: error message
"""
if not bot:
|
@celery.task()
def send_pull_request_failed_tip(
content, app_id, message_id, *args, bot=None, **kwargs
):
"""send new card message to user.
Args:
app_id: IMApplication.app_id.
message_id: lark message id.
content: error message
"""
if not bot: | bot, _ = get_bot_by_application_id(app_id) | 0 | 2023-12-22 02:43:21+00:00 | 2k |
camenduru/AnyDoor-online-hf | dinov2/dinov2/layers/block.py | [
{
"identifier": "Attention",
"path": "dinov2/dinov2/layers/attention.py",
"snippet": "class Attention(nn.Module):\n def __init__(\n self,\n dim: int,\n num_heads: int = 8,\n qkv_bias: bool = False,\n proj_bias: bool = True,\n attn_drop: float = 0.0,\n ... | import logging
import torch
from typing import Callable, List, Any, Tuple, Dict
from torch import nn, Tensor
from .attention import Attention, MemEffAttention
from .drop_path import DropPath
from .layer_scale import LayerScale
from .mlp import Mlp
from xformers.ops import fmha
from xformers.ops import scaled_index_add, index_select_cat | 1,475 | # 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.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
logger = logging.getLogger("dinov2")
try:
XFORMERS_AVAILABLE = True
except ImportError:
logger.warning("xFormers not available")
XFORMERS_AVAILABLE = False
class Block(nn.Module):
def __init__(
self,
dim: int,
num_heads: int,
mlp_ratio: float = 4.0,
qkv_bias: bool = False,
proj_bias: bool = True,
ffn_bias: bool = True,
drop: float = 0.0,
attn_drop: float = 0.0,
init_values=None,
drop_path: float = 0.0,
act_layer: Callable[..., nn.Module] = nn.GELU,
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
attn_class: Callable[..., nn.Module] = Attention,
| # 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.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
logger = logging.getLogger("dinov2")
try:
XFORMERS_AVAILABLE = True
except ImportError:
logger.warning("xFormers not available")
XFORMERS_AVAILABLE = False
class Block(nn.Module):
def __init__(
self,
dim: int,
num_heads: int,
mlp_ratio: float = 4.0,
qkv_bias: bool = False,
proj_bias: bool = True,
ffn_bias: bool = True,
drop: float = 0.0,
attn_drop: float = 0.0,
init_values=None,
drop_path: float = 0.0,
act_layer: Callable[..., nn.Module] = nn.GELU,
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
attn_class: Callable[..., nn.Module] = Attention, | ffn_layer: Callable[..., nn.Module] = Mlp, | 4 | 2023-12-25 04:48:34+00:00 | 2k |
OmchainFoundation/evm-indexer | tests/test_range.py | [
{
"identifier": "Fetcher",
"path": "evm_indexer/fetcher.py",
"snippet": "class Fetcher:\n def __init__(self, node_endpoint, is_poa=True):\n self.web3 = Web3(Web3.HTTPProvider(node_endpoint))\n if is_poa:\n self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)\n \n if not se... | import sys
import os
from evm_indexer.fetcher import Fetcher
from evm_indexer.decoder import Decoder
from evm_indexer.internal_tracer import InternalTracer
from web3 import Web3 | 1,584 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
NODE_URL = 'https://seed.omchain.io'
fetcher = Fetcher(NODE_URL, is_poa=True)
| sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
NODE_URL = 'https://seed.omchain.io'
fetcher = Fetcher(NODE_URL, is_poa=True) | decoder = Decoder(fetcher=fetcher) | 1 | 2023-12-26 17:39:42+00:00 | 2k |
omkarcloud/google-scraper | src/google_scraper.py | [
{
"identifier": "write_output",
"path": "src/write_output.py",
"snippet": "def write_output(query, data, entity_type,transformer = kebab_case):\n\n query_kebab = transformer(query)\n make_folders(query_kebab)\n\n csv_path = f\"output/{query_kebab}/csv/\" \n json_path = f\"output/{query_kebab... | from typing import List,Optional, Union, Dict
from botasaurus import bt
from .write_output import write_output
from .search import FAILED_DUE_TO_CREDITS_EXHAUSTED, FAILED_DUE_TO_NO_KEY,FAILED_DUE_TO_NOT_SUBSCRIBED, FAILED_DUE_TO_UNKNOWN_ERROR, search | 1,171 |
def clean_data(social_details):
success, credits_exhausted, not_subscribed, unknown_error, no_key = [], [], [], [], []
for detail in social_details:
if detail.get("error") is None:
success.append(detail)
elif detail["error"] == FAILED_DUE_TO_CREDITS_EXHAUSTED:
credits_exhausted.append(detail)
elif detail["error"] == FAILED_DUE_TO_NOT_SUBSCRIBED:
not_subscribed.append(detail)
elif detail["error"] == FAILED_DUE_TO_UNKNOWN_ERROR:
unknown_error.append(detail)
elif detail["error"] == FAILED_DUE_TO_NO_KEY:
no_key.append(detail)
return success, credits_exhausted, not_subscribed, unknown_error, no_key
def print_data_errors(credits_exhausted, not_subscribed, unknown_error, no_key):
if credits_exhausted:
name = "queries" if len(credits_exhausted) > 1 else "query"
print(f"Could not get data for {len(credits_exhausted)} {name} due to credit exhaustion. Please consider upgrading your plan by visiting https://rapidapi.com/Chetan11dev/api/google-scraper/pricing to continue scraping data.")
if not_subscribed:
name = "queries" if len(not_subscribed) > 1 else "query"
print(f"Could not get data for {len(not_subscribed)} {name} as you are not subscribed to Google Scraper API. Please subscribe to a free plan by visiting https://rapidapi.com/Chetan11dev/api/google-scraper/pricing")
if unknown_error:
name = "queries" if len(unknown_error) > 1 else "query"
print(f"Could not get data for {len(unknown_error)} {name} due to Unknown Error.")
if no_key:
name = "queries" if len(no_key) > 1 else "query"
print(f"Could not get data for {len(no_key)} {name} as you are not subscribed to Google Scraper API. Please subscribe to a free plan by visiting https://rapidapi.com/Chetan11dev/api/google-scraper/pricing")
class Google:
@staticmethod
|
def clean_data(social_details):
success, credits_exhausted, not_subscribed, unknown_error, no_key = [], [], [], [], []
for detail in social_details:
if detail.get("error") is None:
success.append(detail)
elif detail["error"] == FAILED_DUE_TO_CREDITS_EXHAUSTED:
credits_exhausted.append(detail)
elif detail["error"] == FAILED_DUE_TO_NOT_SUBSCRIBED:
not_subscribed.append(detail)
elif detail["error"] == FAILED_DUE_TO_UNKNOWN_ERROR:
unknown_error.append(detail)
elif detail["error"] == FAILED_DUE_TO_NO_KEY:
no_key.append(detail)
return success, credits_exhausted, not_subscribed, unknown_error, no_key
def print_data_errors(credits_exhausted, not_subscribed, unknown_error, no_key):
if credits_exhausted:
name = "queries" if len(credits_exhausted) > 1 else "query"
print(f"Could not get data for {len(credits_exhausted)} {name} due to credit exhaustion. Please consider upgrading your plan by visiting https://rapidapi.com/Chetan11dev/api/google-scraper/pricing to continue scraping data.")
if not_subscribed:
name = "queries" if len(not_subscribed) > 1 else "query"
print(f"Could not get data for {len(not_subscribed)} {name} as you are not subscribed to Google Scraper API. Please subscribe to a free plan by visiting https://rapidapi.com/Chetan11dev/api/google-scraper/pricing")
if unknown_error:
name = "queries" if len(unknown_error) > 1 else "query"
print(f"Could not get data for {len(unknown_error)} {name} due to Unknown Error.")
if no_key:
name = "queries" if len(no_key) > 1 else "query"
print(f"Could not get data for {len(no_key)} {name} as you are not subscribed to Google Scraper API. Please subscribe to a free plan by visiting https://rapidapi.com/Chetan11dev/api/google-scraper/pricing")
class Google:
@staticmethod | def search(query: Union[str, List[str]], max: Optional[int] = None, key: Optional[str] =None, use_cache: bool = True) -> Dict: | 5 | 2023-12-30 08:14:05+00:00 | 2k |
AI2lab/comfyUI-tool-2lab | nodes/tool/preview.py | [
{
"identifier": "downloadFileToTempFolder",
"path": "nodes/common/utils.py",
"snippet": "def downloadFileToTempFolder(url: str) -> str:\n try:\n response = requests.get(url)\n response.raise_for_status()\n\n try:\n if not os.path.exists(temp_folder):\n o... | import numpy as np
import torch
from PIL import Image
from ..common.utils import downloadFileToTempFolder
from ..constants import get_project_name, get_project_category | 812 |
NODE_CATEGORY = get_project_category("util/preview")
class ShowText:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"string": ("STRING", {"forceInput": True}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",},
}
NAME = get_project_name('show_text')
CATEGORY = NODE_CATEGORY
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("string",)
OUTPUT_NODE = True
FUNCTION = "doWork"
def doWork(self, string, unique_id=None, extra_pnginfo=None):
return {"ui": {"string": [string, ]}, "result": (string,)}
class ShowWebImage:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image_url": ("STRING", {"multiline": False}),
"RGBA": (["false", "true"],{"default":False}),
},
}
NAME = get_project_name('show_web_image')
CATEGORY = NODE_CATEGORY
RETURN_TYPES = ("IMAGE", "MASK","TEXT","filePath")
RETURN_NAMES = ("image", "mask","image_url","filePath")
OUTPUT_NODE = True
FUNCTION = "doWork"
def doWork(self, image_url, RGBA):
print(image_url)
i = None
file_path = ''
try:
if image_url.startswith('http'):
file_path,i = self.download_image(image_url)
else:
file_path = image_url
i = Image.open(image_url)
if not i:
return
image = i
if not RGBA:
image = image.convert('RGB')
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
# RGBA - mask
if 'A' in i.getbands():
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
return (image, mask, image_url,file_path)
except :
pass
return (None, None, image_url,file_path)
def download_image(self, url):
|
NODE_CATEGORY = get_project_category("util/preview")
class ShowText:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"string": ("STRING", {"forceInput": True}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_pnginfo": "EXTRA_PNGINFO",},
}
NAME = get_project_name('show_text')
CATEGORY = NODE_CATEGORY
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("string",)
OUTPUT_NODE = True
FUNCTION = "doWork"
def doWork(self, string, unique_id=None, extra_pnginfo=None):
return {"ui": {"string": [string, ]}, "result": (string,)}
class ShowWebImage:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image_url": ("STRING", {"multiline": False}),
"RGBA": (["false", "true"],{"default":False}),
},
}
NAME = get_project_name('show_web_image')
CATEGORY = NODE_CATEGORY
RETURN_TYPES = ("IMAGE", "MASK","TEXT","filePath")
RETURN_NAMES = ("image", "mask","image_url","filePath")
OUTPUT_NODE = True
FUNCTION = "doWork"
def doWork(self, image_url, RGBA):
print(image_url)
i = None
file_path = ''
try:
if image_url.startswith('http'):
file_path,i = self.download_image(image_url)
else:
file_path = image_url
i = Image.open(image_url)
if not i:
return
image = i
if not RGBA:
image = image.convert('RGB')
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
# RGBA - mask
if 'A' in i.getbands():
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
return (image, mask, image_url,file_path)
except :
pass
return (None, None, image_url,file_path)
def download_image(self, url): | file_path = downloadFileToTempFolder(url) | 0 | 2023-12-24 14:44:13+00:00 | 2k |
Amirtheahmed/ddd-cqrs-fastapi | src/contexts/photostore/photo/application/createone/PhotoCreator.py | [
{
"identifier": "PhotoRepository",
"path": "src/contexts/photostore/photo/domain/PhotoRepository.py",
"snippet": "class PhotoRepository(ABC):\n\n async def create_one(self, photo: Photo) -> NoReturn:\n raise NotImplementedError()"
},
{
"identifier": "Photo",
"path": "src/contexts/p... | from src.contexts.photostore.photo.domain.PhotoRepository import PhotoRepository
from src.contexts.photostore.photo.domain.entities.Photo import Photo
from src.contexts.photostore.photo.domain.entities.PhotoFile import PhotoFile
from src.contexts.photostore.photo.domain.entities.PhotoId import PhotoId
from src.contexts.photostore.photo.domain.entities.PhotoName import PhotoName
from src.contexts.photostore.photo.domain.entities.UserId import UserId
from src.contexts.shared.domain.EventBus import EventBus | 891 |
class PhotoCreator:
def __init__(self, photo_repository: PhotoRepository, event_bus: EventBus):
self.__photo_repository = photo_repository
self.__event_bus = event_bus
|
class PhotoCreator:
def __init__(self, photo_repository: PhotoRepository, event_bus: EventBus):
self.__photo_repository = photo_repository
self.__event_bus = event_bus
| async def run(self, photo_id: PhotoId, name: PhotoName, user_id: UserId, file: PhotoFile): | 2 | 2023-12-27 13:58:25+00:00 | 2k |
JINO-ROHIT/RAG-with-Memory | vlite_db/main.py | [
{
"identifier": "EmbeddingModel",
"path": "vlite_db/model.py",
"snippet": "class EmbeddingModel:\n '''\n EmbeddingModel runs a transformer model and returns the embedding for a given text.\n '''\n def __init__(self, model_name='sentence-transformers/all-MiniLM-L6-v2'):\n self.tokenize... | import numpy as np
import datetime
from uuid import uuid4
from .model import EmbeddingModel
from .utils import chop_and_chunk, cos_sim | 1,156 |
class VLite:
'''
vlite is a simple vector database that stores vectors in a numpy array.
'''
def __init__(self, collection=None,device='mps',model_name=None):
# Filename must be unique between runs. Saving to the same file will append vectors to previous run's vectors
if collection is None:
current_datetime = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
collection = f"vlite_{current_datetime}.npz"
self.collection = collection
self.device = device
self.model = EmbeddingModel() if model_name is None else EmbeddingModel(model_name)
try:
with np.load(self.collection, allow_pickle=True) as data:
self.texts = data['texts'].tolist()
self.metadata = data['metadata'].tolist()
self.vectors = data['vectors']
except FileNotFoundError:
self.texts = []
self.metadata = {}
self.vectors = np.empty((0, self.model.dimension))
def add_vector(self, vector):
self.vectors = np.vstack((self.vectors, vector))
def get_similar_vectors(self, vector, top_k=5):
sims = cos_sim(vector, self.vectors)
sims = sims[0]
# print("[get_similar_vectors] Sims:", sims.shape)
top_k_idx = np.argsort(sims)[::-1][:top_k]
# print("[get_similar_vectors] Top k idx:", top_k_idx)
# print("[get_similar_vectors] Top k sims:", sims[top_k_idx])
return top_k_idx, sims[top_k_idx]
def memorize(self, text, id=None, metadata=None):
id = id or str(uuid4())
|
class VLite:
'''
vlite is a simple vector database that stores vectors in a numpy array.
'''
def __init__(self, collection=None,device='mps',model_name=None):
# Filename must be unique between runs. Saving to the same file will append vectors to previous run's vectors
if collection is None:
current_datetime = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
collection = f"vlite_{current_datetime}.npz"
self.collection = collection
self.device = device
self.model = EmbeddingModel() if model_name is None else EmbeddingModel(model_name)
try:
with np.load(self.collection, allow_pickle=True) as data:
self.texts = data['texts'].tolist()
self.metadata = data['metadata'].tolist()
self.vectors = data['vectors']
except FileNotFoundError:
self.texts = []
self.metadata = {}
self.vectors = np.empty((0, self.model.dimension))
def add_vector(self, vector):
self.vectors = np.vstack((self.vectors, vector))
def get_similar_vectors(self, vector, top_k=5):
sims = cos_sim(vector, self.vectors)
sims = sims[0]
# print("[get_similar_vectors] Sims:", sims.shape)
top_k_idx = np.argsort(sims)[::-1][:top_k]
# print("[get_similar_vectors] Top k idx:", top_k_idx)
# print("[get_similar_vectors] Top k sims:", sims[top_k_idx])
return top_k_idx, sims[top_k_idx]
def memorize(self, text, id=None, metadata=None):
id = id or str(uuid4()) | chunks = chop_and_chunk(text) | 1 | 2023-12-25 07:16:09+00:00 | 2k |
avataar/bg_electricity_regulated_pricing | custom_components/bg_electricity_regulated_pricing/sensor.py | [
{
"identifier": "CONF_TARIFF_TYPE",
"path": "custom_components/bg_electricity_regulated_pricing/const.py",
"snippet": "CONF_TARIFF_TYPE = \"tariff_type\""
},
{
"identifier": "CONF_PROVIDER",
"path": "custom_components/bg_electricity_regulated_pricing/const.py",
"snippet": "CONF_PROVIDER ... | from homeassistant.components.sensor import SensorEntity, SensorEntityDescription, \
SensorStateClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import utcnow
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from .const import CONF_TARIFF_TYPE, CONF_PROVIDER, CONF_CUSTOM_DAY_PRICE, \
CONF_CUSTOM_NIGHT_PRICE, PROVIDER_PRICES, CONF_CLOCK_OFFSET, \
BGN_PER_KILOWATT_HOUR, VAT_RATE, DOMAIN | 753 | """Sensor platform for bg_electricity_regulated_pricing integration."""
from __future__ import annotations
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize bg_electricity_regulated_pricing config entry."""
name = config_entry.title
unique_id = config_entry.entry_id
tariff_type = config_entry.options[CONF_TARIFF_TYPE]
clock_offset = config_entry.options[CONF_CLOCK_OFFSET]
provider = config_entry.options[CONF_PROVIDER]
if provider == "custom":
| """Sensor platform for bg_electricity_regulated_pricing integration."""
from __future__ import annotations
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize bg_electricity_regulated_pricing config entry."""
name = config_entry.title
unique_id = config_entry.entry_id
tariff_type = config_entry.options[CONF_TARIFF_TYPE]
clock_offset = config_entry.options[CONF_CLOCK_OFFSET]
provider = config_entry.options[CONF_PROVIDER]
if provider == "custom": | price_day = config_entry.options[CONF_CUSTOM_DAY_PRICE] | 2 | 2023-12-24 11:13:54+00:00 | 2k |
Qazalbash/jaxtro | jaxtro/main.py | [
{
"identifier": "parser",
"path": "jaxtro/utils/parser.py",
"snippet": "def parse_config(config_path: str) -> dict:"
},
{
"identifier": "PopulationGenerator",
"path": "jaxtro/utils/popgen.py",
"snippet": "class PopulationGenerator:\n \"\"\"Class to generate population and save them to... | from .utils import PopulationGenerator, parser | 981 | # Copyright 2023 The Jaxtro Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def main():
args = parser.cmd_parser.parse_args()
configuration_dict = parser.parse_config(args.my_config)
general = configuration_dict['general']
models = [configuration_dict.get('mass_model', None), configuration_dict.get('spin_model', None)]
| # Copyright 2023 The Jaxtro Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def main():
args = parser.cmd_parser.parse_args()
configuration_dict = parser.parse_config(args.my_config)
general = configuration_dict['general']
models = [configuration_dict.get('mass_model', None), configuration_dict.get('spin_model', None)]
| pg = PopulationGenerator(general=general, models=models) | 1 | 2023-12-24 21:55:35+00:00 | 2k |
smonsays/modular-hyperteacher | metax/learner/reptile.py | [
{
"identifier": "Dataset",
"path": "metax/data/base.py",
"snippet": "class Dataset(NamedTuple):\n x: Array\n y: Array\n info: Dict = dict()"
},
{
"identifier": "batch_generator",
"path": "metax/data/utils.py",
"snippet": "def batch_generator(rng, datastruct, steps, batch_size):\... | import jax
import jax.numpy as jnp
import jax.tree_util as jtu
import optax
from metax.data import Dataset, batch_generator
from metax.module import LearnedInit
from metax.module.init import LearnedInitMetaParams
from metax.utils import append_keys
from .base import MetaGradLearner | 1,497 | """
Copyright (c) Simon Schug
All rights reserved.
MIT License
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.
"""
| """
Copyright (c) Simon Schug
All rights reserved.
MIT License
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.
"""
| class Reptile(MetaGradLearner): | 5 | 2023-12-22 16:35:49+00:00 | 2k |
AContesini/Convert_PDF_to_DOCX_or_vice-versa | venv/Lib/site-packages/tqdm/contrib/concurrent.py | [
{
"identifier": "tqdm",
"path": "venv/Lib/site-packages/tqdm/auto.py",
"snippet": "class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro\n pass"
},
{
"identifier": "TqdmWarning",
"path": "venv/Lib/site-packages/tqdm/std.py",
"snippet": "class TqdmWarning(Warning... | from contextlib import contextmanager
from operator import length_hint
from os import cpu_count
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor
from warnings import warn | 1,153 | """
Thin wrappers around `concurrent.futures`.
"""
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['thread_map', 'process_map']
@contextmanager
def ensure_lock(tqdm_class, lock_name=""):
"""get (create if necessary) and then restore `tqdm_class`'s lock"""
old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock
lock = old_lock or tqdm_class.get_lock() # maybe create a new lock
lock = getattr(lock, lock_name, lock) # maybe subtype
tqdm_class.set_lock(lock)
yield lock
if old_lock is None:
del tqdm_class._lock
else:
tqdm_class.set_lock(old_lock)
def _executor_map(PoolExecutor, fn, *iterables, **tqdm_kwargs):
"""
Implementation of `thread_map` and `process_map`.
Parameters
----------
tqdm_class : [default: tqdm.auto.tqdm].
max_workers : [default: min(32, cpu_count() + 4)].
chunksize : [default: 1].
lock_name : [default: "":str].
"""
kwargs = tqdm_kwargs.copy()
if "total" not in kwargs:
kwargs["total"] = length_hint(iterables[0])
tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
max_workers = kwargs.pop("max_workers", min(32, cpu_count() + 4))
chunksize = kwargs.pop("chunksize", 1)
lock_name = kwargs.pop("lock_name", "")
with ensure_lock(tqdm_class, lock_name=lock_name) as lk:
# share lock in case workers are already using `tqdm`
with PoolExecutor(max_workers=max_workers, initializer=tqdm_class.set_lock,
initargs=(lk,)) as ex:
return list(tqdm_class(ex.map(fn, *iterables, chunksize=chunksize), **kwargs))
def thread_map(fn, *iterables, **tqdm_kwargs):
"""
Equivalent of `list(map(fn, *iterables))`
driven by `concurrent.futures.ThreadPoolExecutor`.
Parameters
----------
tqdm_class : optional
`tqdm` class to use for bars [default: tqdm.auto.tqdm].
max_workers : int, optional
Maximum number of workers to spawn; passed to
`concurrent.futures.ThreadPoolExecutor.__init__`.
[default: max(32, cpu_count() + 4)].
"""
return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
def process_map(fn, *iterables, **tqdm_kwargs):
"""
Equivalent of `list(map(fn, *iterables))`
driven by `concurrent.futures.ProcessPoolExecutor`.
Parameters
----------
tqdm_class : optional
`tqdm` class to use for bars [default: tqdm.auto.tqdm].
max_workers : int, optional
Maximum number of workers to spawn; passed to
`concurrent.futures.ProcessPoolExecutor.__init__`.
[default: min(32, cpu_count() + 4)].
chunksize : int, optional
Size of chunks sent to worker processes; passed to
`concurrent.futures.ProcessPoolExecutor.map`. [default: 1].
lock_name : str, optional
Member of `tqdm_class.get_lock()` to use [default: mp_lock].
"""
if iterables and "chunksize" not in tqdm_kwargs:
# default `chunksize=1` has poor performance for large iterables
# (most time spent dispatching items to workers).
longest_iterable_len = max(map(length_hint, iterables))
if longest_iterable_len > 1000:
warn("Iterable length %d > 1000 but `chunksize` is not set."
" This may seriously degrade multiprocess performance."
" Set `chunksize=1` or more." % longest_iterable_len,
| """
Thin wrappers around `concurrent.futures`.
"""
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['thread_map', 'process_map']
@contextmanager
def ensure_lock(tqdm_class, lock_name=""):
"""get (create if necessary) and then restore `tqdm_class`'s lock"""
old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock
lock = old_lock or tqdm_class.get_lock() # maybe create a new lock
lock = getattr(lock, lock_name, lock) # maybe subtype
tqdm_class.set_lock(lock)
yield lock
if old_lock is None:
del tqdm_class._lock
else:
tqdm_class.set_lock(old_lock)
def _executor_map(PoolExecutor, fn, *iterables, **tqdm_kwargs):
"""
Implementation of `thread_map` and `process_map`.
Parameters
----------
tqdm_class : [default: tqdm.auto.tqdm].
max_workers : [default: min(32, cpu_count() + 4)].
chunksize : [default: 1].
lock_name : [default: "":str].
"""
kwargs = tqdm_kwargs.copy()
if "total" not in kwargs:
kwargs["total"] = length_hint(iterables[0])
tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
max_workers = kwargs.pop("max_workers", min(32, cpu_count() + 4))
chunksize = kwargs.pop("chunksize", 1)
lock_name = kwargs.pop("lock_name", "")
with ensure_lock(tqdm_class, lock_name=lock_name) as lk:
# share lock in case workers are already using `tqdm`
with PoolExecutor(max_workers=max_workers, initializer=tqdm_class.set_lock,
initargs=(lk,)) as ex:
return list(tqdm_class(ex.map(fn, *iterables, chunksize=chunksize), **kwargs))
def thread_map(fn, *iterables, **tqdm_kwargs):
"""
Equivalent of `list(map(fn, *iterables))`
driven by `concurrent.futures.ThreadPoolExecutor`.
Parameters
----------
tqdm_class : optional
`tqdm` class to use for bars [default: tqdm.auto.tqdm].
max_workers : int, optional
Maximum number of workers to spawn; passed to
`concurrent.futures.ThreadPoolExecutor.__init__`.
[default: max(32, cpu_count() + 4)].
"""
return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
def process_map(fn, *iterables, **tqdm_kwargs):
"""
Equivalent of `list(map(fn, *iterables))`
driven by `concurrent.futures.ProcessPoolExecutor`.
Parameters
----------
tqdm_class : optional
`tqdm` class to use for bars [default: tqdm.auto.tqdm].
max_workers : int, optional
Maximum number of workers to spawn; passed to
`concurrent.futures.ProcessPoolExecutor.__init__`.
[default: min(32, cpu_count() + 4)].
chunksize : int, optional
Size of chunks sent to worker processes; passed to
`concurrent.futures.ProcessPoolExecutor.map`. [default: 1].
lock_name : str, optional
Member of `tqdm_class.get_lock()` to use [default: mp_lock].
"""
if iterables and "chunksize" not in tqdm_kwargs:
# default `chunksize=1` has poor performance for large iterables
# (most time spent dispatching items to workers).
longest_iterable_len = max(map(length_hint, iterables))
if longest_iterable_len > 1000:
warn("Iterable length %d > 1000 but `chunksize` is not set."
" This may seriously degrade multiprocess performance."
" Set `chunksize=1` or more." % longest_iterable_len, | TqdmWarning, stacklevel=2) | 1 | 2023-12-24 15:46:18+00:00 | 2k |
willfinnigan/RetroBioCat_2 | rbc2/expansion/expanders/action_getters/aizynthfinder/aizynthfinder_actions.py | [
{
"identifier": "does_aizynthfinder_exist",
"path": "rbc2/configs/download_data_files/download_aizynthfinder.py",
"snippet": "def does_aizynthfinder_exist() -> bool:\n if not os.path.exists(f\"{path_to_data_folder}/aizynthfinder/uspto_model.hdf5\"):\n return False\n if not os.path.exists(f\... | import time
import numpy as np
import pandas as pd
from rdkit import Chem
from rbc2.configs.download_data_files.download_aizynthfinder import does_aizynthfinder_exist, \
download_aizynthfinder_model
from rbc2.utils.add_logger import add_logger
from rbc2.configs.data_path import path_to_data_folder
from rbc2.configs.expansion_config import Expansion_Config
from rbc2.utils import load_keras_models, fingerprints | 1,573 |
data_folder = f'{path_to_data_folder}/aizynthfinder'
class AizynthfinderActionGetter():
def __init__(self,
template_column='retro_template',
cutoff_cumulative=0.995,
cutoff_number=50,
log_level='WARNING'):
self.logger = add_logger('AIZynthfinder_Actions', level=log_level)
self.policy_model = None
self.templates = None
self.template_column = template_column
self.cutoff_cumulative = cutoff_cumulative
self.cutoff_number = cutoff_number
if does_aizynthfinder_exist() == False:
download_aizynthfinder_model()
def load_model(self):
if self.policy_model == None:
policy_path = data_folder + '/uspto_model.hdf5'
self.policy_model = load_keras_models.LocalKerasModel(policy_path)
if self.templates == None:
templates_path = data_folder + '/uspto_templates.hdf5'
self.templates = pd.read_hdf(templates_path, "table")
def get_actions(self, smi):
reactions = []
priors = []
template_column = self.template_column
mol = Chem.MolFromSmiles(smi)
all_transforms_prop = self._predict(mol)
probable_transforms_idx = self._cutoff_predictions(all_transforms_prop)
possible_moves = self.templates.iloc[probable_transforms_idx]
probs = all_transforms_prop[probable_transforms_idx]
priors.extend(probs)
for idx, (move_index, move) in enumerate(possible_moves.iterrows()):
metadata = dict(move)
del metadata[template_column]
metadata["policy_probability"] = round(float(probs[idx]), 5)
metadata["template_code"] = move_index
reaction = {'smarts': move[template_column],
'metadata': metadata,
'prior': priors[idx]}
reactions.append(reaction)
return reactions
def get_rxns(self, smile):
if self.policy_model == None:
self.load_model()
reactions = self.get_actions(smile)
rxns = {}
metadata = {}
for reaction in reactions:
name = f"Chem_{reaction['metadata']['classification']}"
num = 1
extra_string = f"__{num}"
while name+extra_string in rxns:
extra_string = f"__{num}"
num += 1
name = name+extra_string
smarts = reaction['smarts']
if self._does_smarts_only_one_reactants(smarts):
rxns[name] = [smarts]
else:
rxns[name] = []
metadata[name] = reaction['metadata']
return rxns, metadata
def _predict(self, mol):
|
data_folder = f'{path_to_data_folder}/aizynthfinder'
class AizynthfinderActionGetter():
def __init__(self,
template_column='retro_template',
cutoff_cumulative=0.995,
cutoff_number=50,
log_level='WARNING'):
self.logger = add_logger('AIZynthfinder_Actions', level=log_level)
self.policy_model = None
self.templates = None
self.template_column = template_column
self.cutoff_cumulative = cutoff_cumulative
self.cutoff_number = cutoff_number
if does_aizynthfinder_exist() == False:
download_aizynthfinder_model()
def load_model(self):
if self.policy_model == None:
policy_path = data_folder + '/uspto_model.hdf5'
self.policy_model = load_keras_models.LocalKerasModel(policy_path)
if self.templates == None:
templates_path = data_folder + '/uspto_templates.hdf5'
self.templates = pd.read_hdf(templates_path, "table")
def get_actions(self, smi):
reactions = []
priors = []
template_column = self.template_column
mol = Chem.MolFromSmiles(smi)
all_transforms_prop = self._predict(mol)
probable_transforms_idx = self._cutoff_predictions(all_transforms_prop)
possible_moves = self.templates.iloc[probable_transforms_idx]
probs = all_transforms_prop[probable_transforms_idx]
priors.extend(probs)
for idx, (move_index, move) in enumerate(possible_moves.iterrows()):
metadata = dict(move)
del metadata[template_column]
metadata["policy_probability"] = round(float(probs[idx]), 5)
metadata["template_code"] = move_index
reaction = {'smarts': move[template_column],
'metadata': metadata,
'prior': priors[idx]}
reactions.append(reaction)
return reactions
def get_rxns(self, smile):
if self.policy_model == None:
self.load_model()
reactions = self.get_actions(smile)
rxns = {}
metadata = {}
for reaction in reactions:
name = f"Chem_{reaction['metadata']['classification']}"
num = 1
extra_string = f"__{num}"
while name+extra_string in rxns:
extra_string = f"__{num}"
num += 1
name = name+extra_string
smarts = reaction['smarts']
if self._does_smarts_only_one_reactants(smarts):
rxns[name] = [smarts]
else:
rxns[name] = []
metadata[name] = reaction['metadata']
return rxns, metadata
def _predict(self, mol): | fingerprint = fingerprints.get_mol_fingerprint(mol, 2, nBits=len(self.policy_model)) | 6 | 2023-12-30 11:33:41+00:00 | 2k |
DomingoJoseCab/AutoTube | utils/edition/edit.py | [
{
"identifier": "load_videos",
"path": "utils/edition/autoediting.py",
"snippet": "def load_videos(videos_path):\r\n video_list = []\r\n videos = os.listdir(videos_path)\r\n for vid in videos:\r\n video = VideoFileClip(os.path.join(videos_path,vid))\r\n video_list.append(video)\r\... | import os
import json
from moviepy.editor import CompositeVideoClip
from utils.edition.autoediting import load_videos, load_audio, generate_product, generate_intro, generate_outro
from utils.edition.autotext import title_intro
from moviepy.config import change_settings
| 943 | # ==============================================================================
# AutoTube Script
# Creado por: Domingo Caballero
# Canal de YouTube: https://www.youtube.com/@emprendedomingo?=sub_confirmation=1
# Lista de Correo: https://emprendecondomingo.substack.com/
# ==============================================================================
def main(videos_path, audios_path, output_path, names, base_path):
videos = load_videos(videos_path)
audios = load_audio(audios_path)
audio_intro = audios.pop(0)
audio_outro = audios.pop(-1)
| # ==============================================================================
# AutoTube Script
# Creado por: Domingo Caballero
# Canal de YouTube: https://www.youtube.com/@emprendedomingo?=sub_confirmation=1
# Lista de Correo: https://emprendecondomingo.substack.com/
# ==============================================================================
def main(videos_path, audios_path, output_path, names, base_path):
videos = load_videos(videos_path)
audios = load_audio(audios_path)
audio_intro = audios.pop(0)
audio_outro = audios.pop(-1)
| intro = generate_intro(videos, audio_intro)
| 3 | 2023-12-28 16:15:37+00:00 | 2k |
gregorybchris/typogenetics | tests/test_search.py | [
{
"identifier": "Editor",
"path": "typogenetics/search.py",
"snippet": "class Editor:\n PROB_MUTATE = 0.80\n PROB_INSERT = 0.10\n PROB_DELETE = 0.10\n\n @classmethod\n def edit(cls, strand: Strand, rng: Generator) -> Strand:\n edit_type = cls.select_edit_type(rng)\n if edit_... | import numpy as np
from typogenetics.search import Editor, EditType
from typogenetics.typogenetics import Strand | 993 |
class TestSearch:
def test_select_edit_type(self) -> None:
rng = np.random.default_rng(42)
assert Editor.select_edit_type(rng) == EditType.INSERT
def test_mutate(self) -> None:
rng = np.random.default_rng(42)
|
class TestSearch:
def test_select_edit_type(self) -> None:
rng = np.random.default_rng(42)
assert Editor.select_edit_type(rng) == EditType.INSERT
def test_mutate(self) -> None:
rng = np.random.default_rng(42) | strand = Strand.from_str("ACGT") | 2 | 2023-12-28 08:59:06+00:00 | 2k |
chaoren2357/gsplatstudio | gsplatstudio/data/processor/colmapWcam_processor.py | [
{
"identifier": "BaseDataProcessor",
"path": "gsplatstudio/data/processor/base_processor.py",
"snippet": "class BaseDataProcessor(ABC):\n def __init__(self, cfg, logger, source_path) -> None:\n self.cfg = parse_structured(self.config_class, cfg)\n self.logger = logger\n self.sour... | import gsplatstudio
import sqlite3
from gsplatstudio.utils.type_utils import *
from gsplatstudio.data.processor.base_processor import BaseDataProcessor
from pathlib import Path
from gsplatstudio.utils.general_utils import load_json
from gsplatstudio.utils.camera_utils import transform_camera_from_carla_matrix_to_colmap_quaternion, fov_to_focal_length | 1,346 |
@dataclass
class ColmapWithCamProcessorConfig:
use_gpu: bool = True
camera: str = "OPENCV"
map_ba_global_function_tolerance: float = 0.000001
@gsplatstudio.register("colmap_with_cam-processor")
class ColmapWithCamProcessor(BaseDataProcessor):
def __init__(self, cfg, logger, source_path) -> None:
super().__init__(cfg, logger, source_path)
@property
def config_class(self):
return ColmapWithCamProcessorConfig
@property
def should_skip(self):
cameras_file = Path(self.source_path_str) / "sparse" / "0" / "cameras.bin"
images_file = Path(self.source_path_str) / "sparse" / "0" / "images.bin"
points3D_file = Path(self.source_path_str) / "sparse" / "0" / "points3D.bin"
return cameras_file.exists() and images_file.exists() and points3D_file.exists()
def run(self):
self.logger.info("Start running ColmapWithCamProcessorConfig...")
project_folder = Path(self.source_path_str) / "distorted"
project_folder.mkdir(parents=True, exist_ok=True)
database_path = Path(self.source_path_str) / "distorted" / "database.db"
image_distorted_folder = Path(self.source_path_str) / "input"
camera_folder = Path(self.source_path_str) / "camera"
## Feature extraction
feature_extractor_cmd = "colmap feature_extractor" + \
f" --database_path {str(database_path)}" + \
f" --image_path {str(image_distorted_folder)}" + \
f" --ImageReader.single_camera 1" + \
f" --ImageReader.camera_model {self.cfg.camera}" + \
f" --SiftExtraction.use_gpu {int(self.cfg.use_gpu)}"
exit_code = self.run_command_with_realtime_output(feature_extractor_cmd)
if exit_code != 0:
self.logger.error(f"Feature extraction failed with code {exit_code}. Exiting.")
exit(exit_code)
self.logger.info("Finish feature extraction...")
## Create points3D.txt
points3D_txt_path = project_folder / 'points3D.txt'
open(str(points3D_txt_path), 'w').close()
## Create camera.txt
camera_txt_path = project_folder / 'cameras.txt'
open(str(camera_txt_path), 'w').close()
unique_cameras = {}
camera_id = 1
for camera_file in camera_folder.glob('*.json'):
camera_data = load_json(camera_file)
intrinsics = camera_data['intrinsics']
|
@dataclass
class ColmapWithCamProcessorConfig:
use_gpu: bool = True
camera: str = "OPENCV"
map_ba_global_function_tolerance: float = 0.000001
@gsplatstudio.register("colmap_with_cam-processor")
class ColmapWithCamProcessor(BaseDataProcessor):
def __init__(self, cfg, logger, source_path) -> None:
super().__init__(cfg, logger, source_path)
@property
def config_class(self):
return ColmapWithCamProcessorConfig
@property
def should_skip(self):
cameras_file = Path(self.source_path_str) / "sparse" / "0" / "cameras.bin"
images_file = Path(self.source_path_str) / "sparse" / "0" / "images.bin"
points3D_file = Path(self.source_path_str) / "sparse" / "0" / "points3D.bin"
return cameras_file.exists() and images_file.exists() and points3D_file.exists()
def run(self):
self.logger.info("Start running ColmapWithCamProcessorConfig...")
project_folder = Path(self.source_path_str) / "distorted"
project_folder.mkdir(parents=True, exist_ok=True)
database_path = Path(self.source_path_str) / "distorted" / "database.db"
image_distorted_folder = Path(self.source_path_str) / "input"
camera_folder = Path(self.source_path_str) / "camera"
## Feature extraction
feature_extractor_cmd = "colmap feature_extractor" + \
f" --database_path {str(database_path)}" + \
f" --image_path {str(image_distorted_folder)}" + \
f" --ImageReader.single_camera 1" + \
f" --ImageReader.camera_model {self.cfg.camera}" + \
f" --SiftExtraction.use_gpu {int(self.cfg.use_gpu)}"
exit_code = self.run_command_with_realtime_output(feature_extractor_cmd)
if exit_code != 0:
self.logger.error(f"Feature extraction failed with code {exit_code}. Exiting.")
exit(exit_code)
self.logger.info("Finish feature extraction...")
## Create points3D.txt
points3D_txt_path = project_folder / 'points3D.txt'
open(str(points3D_txt_path), 'w').close()
## Create camera.txt
camera_txt_path = project_folder / 'cameras.txt'
open(str(camera_txt_path), 'w').close()
unique_cameras = {}
camera_id = 1
for camera_file in camera_folder.glob('*.json'):
camera_data = load_json(camera_file)
intrinsics = camera_data['intrinsics'] | focal_length = fov_to_focal_length(intrinsics['fov'], intrinsics['width']) | 3 | 2023-12-22 08:27:26+00:00 | 2k |
ddjerqq/beam | src/util.py | [
{
"identifier": "User",
"path": "src/types/user.py",
"snippet": "class User:\n id: int\n username: str\n avatar_url: str"
},
{
"identifier": "Video",
"path": "src/types/video.py",
"snippet": "class Video:\n \"\"\"Tiktok video object\"\"\"\n\n id: str\n \"\"\"Unique iden... | import os
import httpx
from src.types.user import User
from src.types.video import Video | 661 |
def get_env(key: str, default: str = None) -> str:
"""
gets the environment variable with the given key,
or raises an exception if the default is not supplied.
"""
var = os.getenv("APP_ID", default)
if var is not None:
return var
raise Exception(f"Environment variable {key} not found.")
def humanize(num: int) -> str:
"""
converts a number to a human readable format.
"""
if num < 1000:
return str(num)
num = num / 1000
if num < 1000:
return f"{num:.1f}k"
num = num / 1000
if num < 1000:
return f"{num:.1f}m"
num = num / 1000
return f"{num:.1f}b"
|
def get_env(key: str, default: str = None) -> str:
"""
gets the environment variable with the given key,
or raises an exception if the default is not supplied.
"""
var = os.getenv("APP_ID", default)
if var is not None:
return var
raise Exception(f"Environment variable {key} not found.")
def humanize(num: int) -> str:
"""
converts a number to a human readable format.
"""
if num < 1000:
return str(num)
num = num / 1000
if num < 1000:
return f"{num:.1f}k"
num = num / 1000
if num < 1000:
return f"{num:.1f}m"
num = num / 1000
return f"{num:.1f}b"
| def video_info_to_webhook_payload(author: User, video: Video) -> dict[str, str]: | 1 | 2023-12-28 23:18:25+00:00 | 2k |
onestepai/api_rag | service.py | [
{
"identifier": "ServiceApiConfig",
"path": "src/config/ServiceApiConfig.py",
"snippet": "class ServiceApiConfig(ServiceApiConfigBase):\n def __init__(self):\n ServiceApiConfigBase.__init__(self,\n url_prefix=DockerConfig.URL_PREFIX + DockerConfig.API_VERSI... | import logging
from src.config.ServiceApiConfig import ServiceApiConfig
from src.config.DockerConfig import DockerConfig
from src.api_rag.ModelHandler import ModelHandler | 1,153 |
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == '__main__':
|
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == '__main__': | config = ServiceApiConfig() | 0 | 2023-12-28 03:13:03+00:00 | 2k |
DerwenAI/textgraphs | textgraphs/graph.py | [
{
"identifier": "Edge",
"path": "textgraphs/elem.py",
"snippet": "class Edge:\n \"\"\"\nA data class representing an edge between two nodes.\n \"\"\"\n src_node: int\n dst_node: int\n kind: RelEnum\n rel: str\n prob: float\n count: int = 1"
},
{
"identifier": "Node",
... | from collections import OrderedDict
from icecream import ic # pylint: disable=E0401
from .elem import Edge, Node, NodeEnum, RelEnum
import json
import typing
import networkx as nx # pylint: disable=E0401
import spacy # pylint: disable=E0401 | 1,287 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This class implements a generic, in-memory graph data structure used
to represent the _lemma graph_.
see copyright/license https://huggingface.co/spaces/DerwenAI/textgraphs/blob/main/README.md
"""
######################################################################
## class definitions
class SimpleGraph:
"""
An in-memory graph used to build a `MultiDiGraph` in NetworkX.
"""
def __init__ (
self
) -> None:
"""
Constructor.
"""
self.nodes: typing.Dict[ str, Node ] = OrderedDict()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This class implements a generic, in-memory graph data structure used
to represent the _lemma graph_.
see copyright/license https://huggingface.co/spaces/DerwenAI/textgraphs/blob/main/README.md
"""
######################################################################
## class definitions
class SimpleGraph:
"""
An in-memory graph used to build a `MultiDiGraph` in NetworkX.
"""
def __init__ (
self
) -> None:
"""
Constructor.
"""
self.nodes: typing.Dict[ str, Node ] = OrderedDict() | self.edges: typing.Dict[ str, Edge ] = {} | 0 | 2023-12-25 11:42:53+00:00 | 2k |
Noubissie237/StockManagment | StockManagment/App/views.py | [
{
"identifier": "panier_cookie",
"path": "StockManagment/App/utils.py",
"snippet": "def panier_cookie(request):\n articles = []\n\n commande = {\n 'get_panier_total':0,\n 'get_panier_article':0,\n 'produit_physique': True,\n }\n\n nombre_article = commande['get_panier_ar... | from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from .models import *
from django.contrib.auth.decorators import login_required
from datetime import datetime
from .utils import panier_cookie, data_cookie, getDataFromApi
from .forms import LoginForm
from django.contrib.auth import authenticate, login, logout
import json, requests | 1,475 |
@login_required(login_url='/login')
def shop(request, *args, **kwargs):
"""Vue des produits"""
produits = Produit.objects.all()
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'produits': produits,
'nombre_article': nombre_article
}
return render(request, 'shop/index.html', context)
@login_required(login_url='/login')
def panier(request, *args, **kwargs):
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'articles' : articles,
'commande': commande,
'nombre_article': nombre_article
}
return render(request, 'shop/panier.html', context)
@login_required(login_url='/login')
def commande(request, *args, **kwargs):
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'articles' : articles,
'commande': commande,
'nombre_article': nombre_article
}
return render(request, 'shop/commande.html', context)
@login_required(login_url='/login')
def update_article(request, *args, **kwargs):
data = json.loads(request.body)
produit_id = data['produit_id']
action = data['action']
produit = Produit.objects.get(id=produit_id)
client = request.user.client
commande, created = Commande.objects.get_or_create(client=client, complete=False)
commande_article, created = CommandeArticle.objects.get_or_create(commande=commande, produit=produit)
if action == "add":
commande_article.quantite += 1
if action == "remove":
commande_article.quantite -=1
commande_article.save()
if commande_article.quantite <= 0:
commande_article.delete()
return JsonResponse("panier modifié", safe=False)
@login_required(login_url='/login')
def commandeAnonyme(request, data):
name = data['form']['name']
username = data['form']['username']
email = data['form']['email']
phone = data['form']['phone']
|
@login_required(login_url='/login')
def shop(request, *args, **kwargs):
"""Vue des produits"""
produits = Produit.objects.all()
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'produits': produits,
'nombre_article': nombre_article
}
return render(request, 'shop/index.html', context)
@login_required(login_url='/login')
def panier(request, *args, **kwargs):
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'articles' : articles,
'commande': commande,
'nombre_article': nombre_article
}
return render(request, 'shop/panier.html', context)
@login_required(login_url='/login')
def commande(request, *args, **kwargs):
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'articles' : articles,
'commande': commande,
'nombre_article': nombre_article
}
return render(request, 'shop/commande.html', context)
@login_required(login_url='/login')
def update_article(request, *args, **kwargs):
data = json.loads(request.body)
produit_id = data['produit_id']
action = data['action']
produit = Produit.objects.get(id=produit_id)
client = request.user.client
commande, created = Commande.objects.get_or_create(client=client, complete=False)
commande_article, created = CommandeArticle.objects.get_or_create(commande=commande, produit=produit)
if action == "add":
commande_article.quantite += 1
if action == "remove":
commande_article.quantite -=1
commande_article.save()
if commande_article.quantite <= 0:
commande_article.delete()
return JsonResponse("panier modifié", safe=False)
@login_required(login_url='/login')
def commandeAnonyme(request, data):
name = data['form']['name']
username = data['form']['username']
email = data['form']['email']
phone = data['form']['phone']
| cookie_panier = panier_cookie(request) | 0 | 2023-12-29 11:13:34+00:00 | 2k |
kokiez/raydium-convert-SOLorTokens | main.py | [
{
"identifier": "fetch_pool_keys",
"path": "pools.py",
"snippet": "def fetch_pool_keys(mint: str):\r\n amm_info = {}\r\n all_pools = {}\r\n try:\r\n # Using this so it will be faster else no option, we go the slower way.\r\n with open('all_pools.json', 'r') as file:\r\n ... | from solana.rpc.commitment import Commitment
from solana.rpc.api import Client
from solana.transaction import Transaction
from solders.keypair import Keypair
from pools import fetch_pool_keys, make_simulate_pool_info_instruction
from ast import literal_eval
import re
| 1,536 |
LIQUIDITY_FEES_NUMERATOR = 25
LIQUIDITY_FEES_DENOMINATOR = 10000
"""
Required Variables
"""
endpoint = "your_rpc_url"
payer = Keypair.from_base58_string("your_private_key")
token = "ca of your mint/mint address"
solana_client = Client(endpoint, commitment=Commitment("confirmed"), blockhash_cache=True)
def calculateAmountOut(amount, pool_info):
status = pool_info['status']
SWAP_decimals = pool_info['coin_decimals'] #swap coin
SOL_decimals = pool_info['pc_decimals'] #SOL
COIN_lp_decimals = pool_info['lp_decimals'] #swap coin
pool_SOL_amount = pool_info['pool_pc_amount'] #sol
pool_SWAP_amount = pool_info['pool_coin_amount'] #coin
Coin_pool_lp_supply = pool_info['pool_lp_supply'] #coin
reserve_in = pool_SOL_amount
reserve_out = pool_SWAP_amount
current_price = reserve_out / reserve_in
# print(f"Current Price in SOL: {current_price:.12f}")
amount_in = amount * 10 ** SOL_decimals
Fees = (amount_in * LIQUIDITY_FEES_NUMERATOR)/LIQUIDITY_FEES_DENOMINATOR
amount_in_with_fee = amount_in - Fees
amountOutRaw = (reserve_out * amount_in_with_fee) / (reserve_in + amount_in_with_fee)
# Slippage = 1 + slippage
# minimumAmountOut = amountOutRaw / slippage
return amountOutRaw / 10 ** SWAP_decimals
def calculateAmountIn(amount, pool_info):
SWAP_decimals = pool_info['coin_decimals'] #swap coin
SOL_decimals = pool_info['pc_decimals'] #SOL
COIN_lp_decimals = pool_info['lp_decimals'] #swap coin
pool_SOL_amount = pool_info['pool_pc_amount'] #sol
pool_SWAP_amount = pool_info['pool_coin_amount'] #coin
Coin_pool_lp_supply = pool_info['pool_lp_supply'] #coin
reserve_in = pool_SWAP_amount
reserve_out = pool_SOL_amount
current_price = reserve_out / reserve_in
# print(f"Current Price in SOL: {current_price:.12f}")
amount_in = amount * 10 ** SWAP_decimals
Fees = (amount_in * LIQUIDITY_FEES_NUMERATOR)/LIQUIDITY_FEES_DENOMINATOR
amount_in_with_fee = amount_in - Fees
amountOutRaw = (reserve_out * amount_in_with_fee) / (reserve_in + amount_in_with_fee)
# Slippage = 1 + slippage
# minimumAmountOut = amountOutRaw / slippage
return amountOutRaw / 10 ** SOL_decimals
def PoolInfo(mint):
while True:
quote = ""
|
LIQUIDITY_FEES_NUMERATOR = 25
LIQUIDITY_FEES_DENOMINATOR = 10000
"""
Required Variables
"""
endpoint = "your_rpc_url"
payer = Keypair.from_base58_string("your_private_key")
token = "ca of your mint/mint address"
solana_client = Client(endpoint, commitment=Commitment("confirmed"), blockhash_cache=True)
def calculateAmountOut(amount, pool_info):
status = pool_info['status']
SWAP_decimals = pool_info['coin_decimals'] #swap coin
SOL_decimals = pool_info['pc_decimals'] #SOL
COIN_lp_decimals = pool_info['lp_decimals'] #swap coin
pool_SOL_amount = pool_info['pool_pc_amount'] #sol
pool_SWAP_amount = pool_info['pool_coin_amount'] #coin
Coin_pool_lp_supply = pool_info['pool_lp_supply'] #coin
reserve_in = pool_SOL_amount
reserve_out = pool_SWAP_amount
current_price = reserve_out / reserve_in
# print(f"Current Price in SOL: {current_price:.12f}")
amount_in = amount * 10 ** SOL_decimals
Fees = (amount_in * LIQUIDITY_FEES_NUMERATOR)/LIQUIDITY_FEES_DENOMINATOR
amount_in_with_fee = amount_in - Fees
amountOutRaw = (reserve_out * amount_in_with_fee) / (reserve_in + amount_in_with_fee)
# Slippage = 1 + slippage
# minimumAmountOut = amountOutRaw / slippage
return amountOutRaw / 10 ** SWAP_decimals
def calculateAmountIn(amount, pool_info):
SWAP_decimals = pool_info['coin_decimals'] #swap coin
SOL_decimals = pool_info['pc_decimals'] #SOL
COIN_lp_decimals = pool_info['lp_decimals'] #swap coin
pool_SOL_amount = pool_info['pool_pc_amount'] #sol
pool_SWAP_amount = pool_info['pool_coin_amount'] #coin
Coin_pool_lp_supply = pool_info['pool_lp_supply'] #coin
reserve_in = pool_SWAP_amount
reserve_out = pool_SOL_amount
current_price = reserve_out / reserve_in
# print(f"Current Price in SOL: {current_price:.12f}")
amount_in = amount * 10 ** SWAP_decimals
Fees = (amount_in * LIQUIDITY_FEES_NUMERATOR)/LIQUIDITY_FEES_DENOMINATOR
amount_in_with_fee = amount_in - Fees
amountOutRaw = (reserve_out * amount_in_with_fee) / (reserve_in + amount_in_with_fee)
# Slippage = 1 + slippage
# minimumAmountOut = amountOutRaw / slippage
return amountOutRaw / 10 ** SOL_decimals
def PoolInfo(mint):
while True:
quote = ""
| pool_keys = fetch_pool_keys(mint)
| 0 | 2023-12-29 12:35:38+00:00 | 2k |
proger/nanokitchen | blockdiag_linear.py | [
{
"identifier": "StructuredLinear",
"path": "structured_linear.py",
"snippet": "class StructuredLinear(nn.Module):\n\n def __init__(self, in_features, out_features, bias=True, device=None, dtype=None):\n \"\"\"Subclasses should call reset_parameters\n \"\"\"\n factory_kwargs = {'... | import math
import torch
import torch.nn as nn
from einops import rearrange
from structured_linear import StructuredLinear
from blockdiag_multiply import blockdiag_multiply | 1,073 | # Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers
class BlockdiagLinear(StructuredLinear):
def __init__(self, *args, nblocks=4, shuffle=False, **kwargs):
"""shuffle: apply channel_shuffle operation before the matmul as in ShuffleNet
"""
super().__init__(*args, **kwargs)
in_blksz = int(math.ceil(self.in_features / nblocks))
out_blksz = int(math.ceil(self.out_features / nblocks))
self.in_features_extended = in_blksz * nblocks
self.out_features_extended = out_blksz * nblocks
self.shuffle = shuffle
self.weight = nn.Parameter(torch.empty(nblocks, out_blksz, in_blksz))
self.reset_parameters()
def set_weights_from_dense_init(self, dense_init_fn_):
dense_weight = torch.empty(self.out_features_extended, self.in_features_extended,
device=self.weight.device, dtype=self.weight.dtype)
dense_init_fn_(dense_weight)
# Scale by sqrt because the weight is sparse
scaling = math.sqrt(dense_weight.numel() / self.weight.numel())
dense_weight *= scaling
with torch.no_grad():
nblocks = self.weight.shape[0]
self.weight.copy_(rearrange(dense_weight, '(b o) (b1 i) -> b b1 o i',
b=nblocks, b1=nblocks)[0])
@property
def saving(self):
return self.weight.numel() / (self.in_features * self.out_features)
def forward_matmul(self, x):
x = self.preprocess(x)
if self.shuffle:
x = rearrange(x, '... (group c_per_group) -> ... (c_per_group group)',
group=self.weight.shape[0]) # group=nblocks
| # Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers
class BlockdiagLinear(StructuredLinear):
def __init__(self, *args, nblocks=4, shuffle=False, **kwargs):
"""shuffle: apply channel_shuffle operation before the matmul as in ShuffleNet
"""
super().__init__(*args, **kwargs)
in_blksz = int(math.ceil(self.in_features / nblocks))
out_blksz = int(math.ceil(self.out_features / nblocks))
self.in_features_extended = in_blksz * nblocks
self.out_features_extended = out_blksz * nblocks
self.shuffle = shuffle
self.weight = nn.Parameter(torch.empty(nblocks, out_blksz, in_blksz))
self.reset_parameters()
def set_weights_from_dense_init(self, dense_init_fn_):
dense_weight = torch.empty(self.out_features_extended, self.in_features_extended,
device=self.weight.device, dtype=self.weight.dtype)
dense_init_fn_(dense_weight)
# Scale by sqrt because the weight is sparse
scaling = math.sqrt(dense_weight.numel() / self.weight.numel())
dense_weight *= scaling
with torch.no_grad():
nblocks = self.weight.shape[0]
self.weight.copy_(rearrange(dense_weight, '(b o) (b1 i) -> b b1 o i',
b=nblocks, b1=nblocks)[0])
@property
def saving(self):
return self.weight.numel() / (self.in_features * self.out_features)
def forward_matmul(self, x):
x = self.preprocess(x)
if self.shuffle:
x = rearrange(x, '... (group c_per_group) -> ... (c_per_group group)',
group=self.weight.shape[0]) # group=nblocks | output = blockdiag_multiply(x, self.weight) | 1 | 2023-12-27 12:13:00+00:00 | 2k |
karloskar/homeassistant-goecontroller-mqtt | custom_components/goecontroller_mqtt/switch.py | [
{
"identifier": "SWITCHES",
"path": "custom_components/goecontroller_mqtt/definitions/switch.py",
"snippet": "SWITCHES: tuple[GoEControllerSwitchEntityDescription, ...] = (\n GoEControllerSwitchEntityDescription(\n key=\"tse\",\n name=\"Time server enabled\",\n entity_category=En... | import logging
from homeassistant import config_entries, core
from homeassistant.components import mqtt
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import callback
from .definitions.switch import SWITCHES, GoEControllerSwitchEntityDescription
from .entity import GoEControllerEntity | 776 | """The go-eController (MQTT) switch."""
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Config entry setup."""
async_add_entities(
GoEControllerSwitch(config_entry, description)
for description in SWITCHES
if not description.disabled
)
class GoEControllerSwitch(GoEControllerEntity, SwitchEntity):
"""Representation of a go-eController switch that is updated via MQTT."""
| """The go-eController (MQTT) switch."""
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Config entry setup."""
async_add_entities(
GoEControllerSwitch(config_entry, description)
for description in SWITCHES
if not description.disabled
)
class GoEControllerSwitch(GoEControllerEntity, SwitchEntity):
"""Representation of a go-eController switch that is updated via MQTT."""
| entity_description: GoEControllerSwitchEntityDescription | 1 | 2023-12-22 11:32:11+00:00 | 2k |
T0kyoB0y/PotatoWidgets | PotatoWidgets/Widget/_Common/_BasicProps.py | [
{
"identifier": "Listener",
"path": "PotatoWidgets/Variable/_Listener.py",
"snippet": "class Listener(Variable):\n def __init__(self, callback, initial_value=None):\n super().__init__(initial_value)\n self._callback = callback\n self._thread = None\n self._stop_thread = th... | from ...__Import import *
from ...Variable import Listener, Poll, Variable | 1,380 |
class BasicProps(Gtk.Widget):
def __init__(
self,
halign,
valign,
hexpand,
vexpand,
active,
visible,
classname,
# tooltip,
css,
size=[10, 10],
):
Gtk.Widget.__init__(self)
self.set_hexpand(True if hexpand else False)
self.set_vexpand(True if vexpand else False)
self.set_halign(halign)
self.set_valign(valign)
self.set_visible(visible)
self.set_sensitive(active) if active is not None else None
self.set_classname(classname)
self.__clasif_size(size)
self.apply_css(css) if css else None
for key, value in locals().items():
callback = {
"halign": self.set_halign,
"valign": self.set_valign,
"hexpand": self.set_hexpand,
"vexpand": self.set_vexpand,
"active": self.set_sensitive,
"visible": self.set_visible,
"size": self.set_size,
"classname": self.set_classname,
}.get(key)
self.bind(value, callback) if callback else None
def set_size(self, size):
self.__clasif_size(size)
def set_halign(self, param):
super().set_halign(self.__clasif_align(str(param)))
def set_valign(self, param):
super().set_valign(self.__clasif_align(str(param)))
def __clasif_size(self, size):
if isinstance(size, int):
self.set_size_request(size, size)
elif isinstance(size, list):
if len(size) == 2:
self.set_size_request(size[0], size[1])
elif len(size) == 1:
self.set_size_request(size[0], size[0])
def __clasif_align(self, param):
dict = {
"fill": Gtk.Align.FILL,
"start": Gtk.Align.START,
"end": Gtk.Align.END,
"center": Gtk.Align.CENTER,
"baseline": Gtk.Align.BASELINE,
}
return dict.get(param.lower(), Gtk.Align.FILL)
def set_classname(self, param):
if isinstance(param, (str)):
context = self.get_style_context()
[context.add_class(i) for i in param.split(" ") if i != " "]
elif isinstance(param, (list)):
for i in param:
|
class BasicProps(Gtk.Widget):
def __init__(
self,
halign,
valign,
hexpand,
vexpand,
active,
visible,
classname,
# tooltip,
css,
size=[10, 10],
):
Gtk.Widget.__init__(self)
self.set_hexpand(True if hexpand else False)
self.set_vexpand(True if vexpand else False)
self.set_halign(halign)
self.set_valign(valign)
self.set_visible(visible)
self.set_sensitive(active) if active is not None else None
self.set_classname(classname)
self.__clasif_size(size)
self.apply_css(css) if css else None
for key, value in locals().items():
callback = {
"halign": self.set_halign,
"valign": self.set_valign,
"hexpand": self.set_hexpand,
"vexpand": self.set_vexpand,
"active": self.set_sensitive,
"visible": self.set_visible,
"size": self.set_size,
"classname": self.set_classname,
}.get(key)
self.bind(value, callback) if callback else None
def set_size(self, size):
self.__clasif_size(size)
def set_halign(self, param):
super().set_halign(self.__clasif_align(str(param)))
def set_valign(self, param):
super().set_valign(self.__clasif_align(str(param)))
def __clasif_size(self, size):
if isinstance(size, int):
self.set_size_request(size, size)
elif isinstance(size, list):
if len(size) == 2:
self.set_size_request(size[0], size[1])
elif len(size) == 1:
self.set_size_request(size[0], size[0])
def __clasif_align(self, param):
dict = {
"fill": Gtk.Align.FILL,
"start": Gtk.Align.START,
"end": Gtk.Align.END,
"center": Gtk.Align.CENTER,
"baseline": Gtk.Align.BASELINE,
}
return dict.get(param.lower(), Gtk.Align.FILL)
def set_classname(self, param):
if isinstance(param, (str)):
context = self.get_style_context()
[context.add_class(i) for i in param.split(" ") if i != " "]
elif isinstance(param, (list)):
for i in param: | if isinstance(i, (Listener, Variable, Poll)): | 1 | 2023-12-30 01:34:01+00:00 | 2k |
Zerohertz/Streamlit-Quant | lib/visual.py | [
{
"identifier": "_main",
"path": "lib/layout.py",
"snippet": "def _main():\n layout = _default()\n layout.height = 500 * st.session_state[\"scale\"]\n layout.width = 1000\n layout.xaxis = {\n \"type\": \"category\",\n \"gridcolor\": \"black\",\n \"tickangle\": -45,\n ... | import plotly.graph_objs as go
import streamlit as st
import zerohertzLib as zz
from plotly.subplots import make_subplots
from lib.layout import _main, _transaction
from lib.util import _color | 714 |
def candle():
data, xdata = st.session_state["cache"]["data"], st.session_state["cache"]["xdata"]
st.session_state["cache"]["candle"] = go.Candlestick(
x=xdata,
open=data.Open,
high=data.High,
low=data.Low,
close=data.Close,
increasing={"line": {"color": "red"}},
decreasing={"line": {"color": "blue"}},
name=st.session_state["cache"]["name"],
)
st.session_state["logger"].info(
f"""[Plot] Candle Chart: {st.session_state["cache"]["name"]} ({st.session_state["cache"]["symbol"]})"""
)
def moving_average():
xdata = st.session_state["cache"]["xdata"]
st.session_state["cache"]["ma"] = []
|
def candle():
data, xdata = st.session_state["cache"]["data"], st.session_state["cache"]["xdata"]
st.session_state["cache"]["candle"] = go.Candlestick(
x=xdata,
open=data.Open,
high=data.High,
low=data.Low,
close=data.Close,
increasing={"line": {"color": "red"}},
decreasing={"line": {"color": "blue"}},
name=st.session_state["cache"]["name"],
)
st.session_state["logger"].info(
f"""[Plot] Candle Chart: {st.session_state["cache"]["name"]} ({st.session_state["cache"]["symbol"]})"""
)
def moving_average():
xdata = st.session_state["cache"]["xdata"]
st.session_state["cache"]["ma"] = [] | colors = _color(4, 0.5, "Set1") | 2 | 2023-12-26 11:29:06+00:00 | 2k |
acman/py_june | comments/views.py | [
{
"identifier": "Post",
"path": "posts/models.py",
"snippet": "class Post(SlugModel):\n title = models.CharField(max_length=50)\n content = models.TextField(max_length=500, blank=True)\n author = models.ForeignKey(\"users.ForumUser\", on_delete=models.CASCADE)\n category = models.ForeignKey(... | from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.views import View
from posts.models import Post
from .forms import CommentForm
from .models import Comment | 779 |
class CreateCommentView(LoginRequiredMixin, View):
template_name = "comments/comment_form.html"
login_url = "/users/login/"
def get(self, request: HttpRequest, post_slug: str) -> HttpResponse:
post = get_object_or_404(Post, slug=post_slug)
form = CommentForm()
return render(request, self.template_name, {"form": form, "post": post})
def post(self, request: HttpRequest, post_slug: str) -> HttpResponse:
form = CommentForm(request.POST)
post = get_object_or_404(Post, slug=post_slug)
if form.is_valid():
comment = form.save(commit=False)
comment.author = self.request.user
comment.post_id = post.pk
comment.save()
return redirect("categories:detail", category_slug=post.category.slug)
return render(request, self.template_name, {"form": form, "post": post})
class UpdateCommentView(UserPassesTestMixin, View):
template_name = "comments/comment_update.html"
def test_func(self) -> bool:
comment_pk = self.kwargs.get("comment_pk")
|
class CreateCommentView(LoginRequiredMixin, View):
template_name = "comments/comment_form.html"
login_url = "/users/login/"
def get(self, request: HttpRequest, post_slug: str) -> HttpResponse:
post = get_object_or_404(Post, slug=post_slug)
form = CommentForm()
return render(request, self.template_name, {"form": form, "post": post})
def post(self, request: HttpRequest, post_slug: str) -> HttpResponse:
form = CommentForm(request.POST)
post = get_object_or_404(Post, slug=post_slug)
if form.is_valid():
comment = form.save(commit=False)
comment.author = self.request.user
comment.post_id = post.pk
comment.save()
return redirect("categories:detail", category_slug=post.category.slug)
return render(request, self.template_name, {"form": form, "post": post})
class UpdateCommentView(UserPassesTestMixin, View):
template_name = "comments/comment_update.html"
def test_func(self) -> bool:
comment_pk = self.kwargs.get("comment_pk") | comment = get_object_or_404(Comment, pk=comment_pk) | 2 | 2023-12-23 09:36:46+00:00 | 2k |
pkariz/grin-explorer | backend/api/signals/receivers.py | [
{
"identifier": "Block",
"path": "backend/api/models.py",
"snippet": "class Block(TimeStampedModel):\n blockchain = models.ForeignKey(\n Blockchain, related_name='blocks', on_delete=models.CASCADE)\n hash = models.CharField(\n primary_key=True,\n max_length=64,\n valida... | from django.db.models.signals import post_save
from django.dispatch import receiver
from backend.api.models import Block, Reorg
from backend.api.helpers import fix_outputs_and_inputs_from_reorg
import logging | 1,477 |
logger = logging.getLogger(__name__)
@receiver(
post_save,
|
logger = logging.getLogger(__name__)
@receiver(
post_save, | sender=Block, | 0 | 2023-12-24 22:15:11+00:00 | 2k |
CodeWithEmad/num2fa | num2fa/converters/word_converter.py | [
{
"identifier": "DEFAULT_SCIENTIFIC_SEPARATOR",
"path": "num2fa/constants.py",
"snippet": "DEFAULT_SCIENTIFIC_SEPARATOR = \" در ده به توان \""
},
{
"identifier": "WORDS_DECIMAL_SEPARATOR",
"path": "num2fa/constants.py",
"snippet": "WORDS_DECIMAL_SEPARATOR = \" و \""
},
{
"identif... | from decimal import Decimal
from fractions import Fraction
from functools import singledispatch
from typing import Union
from num2fa.constants import (
DEFAULT_SCIENTIFIC_SEPARATOR,
WORDS_DECIMAL_SEPARATOR,
WORDS_FRACTION_SEPARATOR,
WORDS_NEGATIVE,
ZERO,
)
from num2fa.utils import _natural_words, _normalize_str, _point_words | 1,135 | """Provide functions to convert a number to Persian words."""
def _exp_words(
number: str,
positive: str,
negative: str,
decimal_separator: str,
scientific_separator: str,
) -> str:
# exponent
base, e, exponent = number.partition("e")
if exponent:
return (
_point_words(base, decimal_separator)
+ scientific_separator
+ words(int(exponent), positive, negative)
)
return _point_words(base, decimal_separator)
@singledispatch
def words(
number: Union[int, float, str, Decimal, Fraction],
positive: str = "",
negative: str = WORDS_NEGATIVE,
decimal_separator: str = WORDS_DECIMAL_SEPARATOR,
fraction_separator: str = WORDS_FRACTION_SEPARATOR,
ordinal_denominator: bool = True,
scientific_separator: str = DEFAULT_SCIENTIFIC_SEPARATOR,
) -> str:
"""Return the word form of number.
If input is a string it should be in the form of a valid Python
representation for one of the other accepted types. The only exceptions are
that digits can be in Persian, for example words('۴۲') is valid.
"""
raise TypeError("invalid input type for words function", number)
@words.register(str)
@words.register(Decimal)
def _(
number: str,
positive: str = "",
negative: str = WORDS_NEGATIVE,
decimal_separator: str = WORDS_DECIMAL_SEPARATOR,
fraction_separator: str = WORDS_FRACTION_SEPARATOR,
ordinal_denominator: bool = True,
scientific_separator: str = DEFAULT_SCIENTIFIC_SEPARATOR,
) -> str:
# Normalize the number string
number = _normalize_str(number)
# sign
c0 = number[0]
if c0 == "-":
sign = negative
number = number[1:]
elif c0 == "0":
sign = ""
else:
sign = positive
numerator, e, denominator = number.partition("/")
if denominator:
if ordinal_denominator:
return (
sign
| """Provide functions to convert a number to Persian words."""
def _exp_words(
number: str,
positive: str,
negative: str,
decimal_separator: str,
scientific_separator: str,
) -> str:
# exponent
base, e, exponent = number.partition("e")
if exponent:
return (
_point_words(base, decimal_separator)
+ scientific_separator
+ words(int(exponent), positive, negative)
)
return _point_words(base, decimal_separator)
@singledispatch
def words(
number: Union[int, float, str, Decimal, Fraction],
positive: str = "",
negative: str = WORDS_NEGATIVE,
decimal_separator: str = WORDS_DECIMAL_SEPARATOR,
fraction_separator: str = WORDS_FRACTION_SEPARATOR,
ordinal_denominator: bool = True,
scientific_separator: str = DEFAULT_SCIENTIFIC_SEPARATOR,
) -> str:
"""Return the word form of number.
If input is a string it should be in the form of a valid Python
representation for one of the other accepted types. The only exceptions are
that digits can be in Persian, for example words('۴۲') is valid.
"""
raise TypeError("invalid input type for words function", number)
@words.register(str)
@words.register(Decimal)
def _(
number: str,
positive: str = "",
negative: str = WORDS_NEGATIVE,
decimal_separator: str = WORDS_DECIMAL_SEPARATOR,
fraction_separator: str = WORDS_FRACTION_SEPARATOR,
ordinal_denominator: bool = True,
scientific_separator: str = DEFAULT_SCIENTIFIC_SEPARATOR,
) -> str:
# Normalize the number string
number = _normalize_str(number)
# sign
c0 = number[0]
if c0 == "-":
sign = negative
number = number[1:]
elif c0 == "0":
sign = ""
else:
sign = positive
numerator, e, denominator = number.partition("/")
if denominator:
if ordinal_denominator:
return (
sign | + _natural_words(numerator) | 5 | 2023-12-30 14:28:57+00:00 | 2k |
the-seeds/cardinal | src/cardinal/core/extractor/base_extractor.py | [
{
"identifier": "Extractor",
"path": "src/cardinal/core/schema/extractor.py",
"snippet": "class Extractor(ABC):\n @abstractmethod\n def load(self, input_files: List[Path], user_id: str, verbose: Optional[bool] = False) -> None:\n r\"\"\"\n Loads the files into database.\n\n Ar... | import os
from multiprocessing import Pool
from pathlib import Path
from typing import TYPE_CHECKING, List, Optional
from tqdm import tqdm
from ..schema import Extractor, Leaf, LeafIndex
from ..splitter import CJKTextSplitter
from ..model import EmbedOpenAI
from ..schema import StringKeyedStorage, VectorStore
from ..model import EmbedOpenAI
from ..storage import RedisStorage
from ..vectorstore import Milvus | 780 |
if TYPE_CHECKING:
class BaseExtractor(Extractor):
def __init__(
self, vectorizer: "EmbedOpenAI", storage: "StringKeyedStorage[Leaf]", vectorstore: "VectorStore[LeafIndex]"
) -> None:
self._vectorizer = vectorizer
self._storage = storage
self._vectorstore = vectorstore
self._splitter = CJKTextSplitter()
def load(self, input_files: List[Path], user_id: str, verbose: Optional[bool] = False) -> None:
file_contents: List[str] = []
for file_path in tqdm(input_files, desc="Extract content", disable=(not verbose)):
if file_path.suffix == ".txt":
with open(file_path, "r", encoding="utf-8") as f:
file_contents.append(f.read())
else:
raise NotImplementedError
text_chunks = []
with Pool(processes=int(os.environ.get("NUM_CPU_CORE"))) as pool:
for chunks in tqdm(
pool.imap_unordered(self._splitter.split, file_contents),
total=len(file_contents),
desc="Split content",
disable=(not verbose),
):
text_chunks.extend(chunks)
leaf_indexes = []
for chunk in tqdm(text_chunks, desc="Build index", disable=(not verbose)):
|
if TYPE_CHECKING:
class BaseExtractor(Extractor):
def __init__(
self, vectorizer: "EmbedOpenAI", storage: "StringKeyedStorage[Leaf]", vectorstore: "VectorStore[LeafIndex]"
) -> None:
self._vectorizer = vectorizer
self._storage = storage
self._vectorstore = vectorstore
self._splitter = CJKTextSplitter()
def load(self, input_files: List[Path], user_id: str, verbose: Optional[bool] = False) -> None:
file_contents: List[str] = []
for file_path in tqdm(input_files, desc="Extract content", disable=(not verbose)):
if file_path.suffix == ".txt":
with open(file_path, "r", encoding="utf-8") as f:
file_contents.append(f.read())
else:
raise NotImplementedError
text_chunks = []
with Pool(processes=int(os.environ.get("NUM_CPU_CORE"))) as pool:
for chunks in tqdm(
pool.imap_unordered(self._splitter.split, file_contents),
total=len(file_contents),
desc="Split content",
disable=(not verbose),
):
text_chunks.extend(chunks)
leaf_indexes = []
for chunk in tqdm(text_chunks, desc="Build index", disable=(not verbose)): | leaf_index = LeafIndex(user_id=user_id) | 2 | 2023-12-26 14:16:40+00:00 | 2k |
datrocity/pond | tests/test_conventions.py | [
{
"identifier": "METADATA_DIRNAME",
"path": "pond/conventions.py",
"snippet": "METADATA_DIRNAME = '_pond'"
},
{
"identifier": "MANIFEST_FILENAME",
"path": "pond/conventions.py",
"snippet": "MANIFEST_FILENAME = 'manifest.yml'"
},
{
"identifier": "version_data_location",
"path"... | from pond.conventions import (
METADATA_DIRNAME,
MANIFEST_FILENAME,
version_data_location,
version_manifest_location,
version_uri,
urijoinpath,
)
from pond.version_name import SimpleVersionName | 744 |
def test_urijoinpath():
joined = urijoinpath('a', 'b/', 'c/')
expected = 'a/b/c'
assert joined == expected
def test_data_location():
|
def test_urijoinpath():
joined = urijoinpath('a', 'b/', 'c/')
expected = 'a/b/c'
assert joined == expected
def test_data_location(): | location = version_data_location('abc/', 'blah.bin') | 2 | 2023-12-24 13:05:58+00:00 | 2k |
Zitronenjoghurt/Colonaut | src/constants/locale_translator.py | [
{
"identifier": "construct_path",
"path": "src/utils/file_operations.py",
"snippet": "def construct_path(relative_path: str) -> str:\n path_parts = relative_path.split(\"/\")\n absolute_path = os.path.join(ROOT_DIR, *path_parts)\n return absolute_path"
},
{
"identifier": "files_in_direc... | from src.utils.file_operations import construct_path, files_in_directory, file_to_dict, str_to_file
from .locales import Locales | 1,010 |
LOCALES_FILE_PATH = construct_path("src/data/locale/{language}/")
OUTPUT_TXT_FILE_PATH = construct_path("locale_{language}.txt")
LANGUAGES = ["en"]
class LocaleTranslator():
_instance = None
|
LOCALES_FILE_PATH = construct_path("src/data/locale/{language}/")
OUTPUT_TXT_FILE_PATH = construct_path("locale_{language}.txt")
LANGUAGES = ["en"]
class LocaleTranslator():
_instance = None | KEYS = Locales | 4 | 2023-12-22 21:24:33+00:00 | 2k |
daojiAnime/aio_retrying | tests/test_condition_error.py | [
{
"identifier": "ConditionError",
"path": "aio_retrying.py",
"snippet": "class ConditionError(Exception):\n pass"
},
{
"identifier": "retry",
"path": "aio_retrying.py",
"snippet": "def retry(\n fn: Callable = None,\n *,\n attempts: int = 0,\n callback: Optional[Callable] =... | import asyncio
import pytest
from aio_retrying import ConditionError, retry | 745 |
async def test_timeout_is_not_none_and_not_async():
@retry(timeout=0.5)
def not_coro():
pass
|
async def test_timeout_is_not_none_and_not_async():
@retry(timeout=0.5)
def not_coro():
pass
| with pytest.raises(ConditionError): | 0 | 2023-12-30 02:48:40+00:00 | 2k |
xIMRANx/secret_postcard | app/handlers/user/file.py | [
{
"identifier": "User",
"path": "app/db/functions.py",
"snippet": "class User(models.User):\n @classmethod\n async def is_registered(cls, telegram_id: int) -> Union[models.User, bool]:\n try:\n return await cls.get(telegram_id=telegram_id)\n except DoesNotExist:\n ... | from aiogram import Router, Bot, F
from aiogram.types import Message
from app.db.functions import User
from app.db.functions import Card
from app.keyboards.inline import get_approve_keyboard
from app.config import Config | 1,167 |
router = Router()
@router.message(F.content_type.in_({"photo", "video", "animation"}))
async def get_postcard(message: Message, bot: Bot, config: Config):
if await Card.check_exists(message.from_user.id):
await message.answer("Вы уже отправили свою открытку!")
return
postcard_type = message.content_type
if message.photo is not None:
file_id = message.photo[-1].file_id
elif message.video is not None:
file_id = message.video.file_id
elif message.animation is not None:
file_id = message.animation.file_id
else:
file_id = None
user_id = message.from_user.id
chat_id = config.settings.chat_id
|
router = Router()
@router.message(F.content_type.in_({"photo", "video", "animation"}))
async def get_postcard(message: Message, bot: Bot, config: Config):
if await Card.check_exists(message.from_user.id):
await message.answer("Вы уже отправили свою открытку!")
return
postcard_type = message.content_type
if message.photo is not None:
file_id = message.photo[-1].file_id
elif message.video is not None:
file_id = message.video.file_id
elif message.animation is not None:
file_id = message.animation.file_id
else:
file_id = None
user_id = message.from_user.id
chat_id = config.settings.chat_id | if not await User.is_registered(user_id): | 0 | 2023-12-30 07:57:10+00:00 | 2k |
akkoaya/ArticleSpider | ArticleSpider/spiders/cnblog.py | [
{
"identifier": "CnblogItem",
"path": "ArticleSpider/items.py",
"snippet": "class CnblogItem(scrapy.Item):\n url = scrapy.Field()\n url_object_id = scrapy.Field()\n title = scrapy.Field()\n date = scrapy.Field()\n writer_id = scrapy.Field()\n views_num = scrapy.Field()\n comments_n... | import scrapy
import datetime
import re
from scrapy.http import Request
from urllib import parse
from ..items import CnblogItem
from ..utils.common import get_md5
from scrapy.loader import ItemLoader
from scrapy_redis.spiders import RedisSpider | 1,196 |
class CnblogSpider(scrapy.Spider):
name = "cnblog"
allowed_domains = ["www.cnblogs.com"]
start_urls = ["https://www.cnblogs.com/sitehome/p/1"]
# redis_key = 'cnblog:start_urls'
next_url = "https://www.cnblogs.com/sitehome/p/{0}"
# headers = {
# "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
# }
def parse(self, response):
all_urls = response.css('div.post-list a::attr(href)').extract()
all_urls = [parse.urljoin(response.url, url) for url in all_urls]
for url in all_urls:
match_obj = re.match('(.*.cnblogs.com/(.*)/p/.*.html)',url)
if match_obj:
request_url = match_obj.group(1)
writer_id = match_obj.group(2)
yield Request(url=request_url,meta={'writer_id':writer_id},callback=self.parse_detail)
for x in range(2,100):
yield Request(url=self.next_url.format(x), callback=self.parse)
def parse_detail(self,response):
item_loader = ItemLoader(item=CnblogItem(), response=response)
item_loader.add_value("url", response.url)
|
class CnblogSpider(scrapy.Spider):
name = "cnblog"
allowed_domains = ["www.cnblogs.com"]
start_urls = ["https://www.cnblogs.com/sitehome/p/1"]
# redis_key = 'cnblog:start_urls'
next_url = "https://www.cnblogs.com/sitehome/p/{0}"
# headers = {
# "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
# }
def parse(self, response):
all_urls = response.css('div.post-list a::attr(href)').extract()
all_urls = [parse.urljoin(response.url, url) for url in all_urls]
for url in all_urls:
match_obj = re.match('(.*.cnblogs.com/(.*)/p/.*.html)',url)
if match_obj:
request_url = match_obj.group(1)
writer_id = match_obj.group(2)
yield Request(url=request_url,meta={'writer_id':writer_id},callback=self.parse_detail)
for x in range(2,100):
yield Request(url=self.next_url.format(x), callback=self.parse)
def parse_detail(self,response):
item_loader = ItemLoader(item=CnblogItem(), response=response)
item_loader.add_value("url", response.url) | item_loader.add_value("url_object_id", get_md5(response.url)) | 1 | 2023-12-29 15:05:22+00:00 | 2k |
Asa-Nisi-Masa/christmas-tree | christmas_tree/calculations/compute_coords.py | [
{
"identifier": "PATH_SAVE",
"path": "christmas_tree/common/settings.py",
"snippet": "PATH_SAVE = \"coordinates.csv\""
},
{
"identifier": "TOTAL_LEDS",
"path": "christmas_tree/common/settings.py",
"snippet": "TOTAL_LEDS = 500"
}
] | from collections import defaultdict, namedtuple
from pathlib import Path
from typing import Dict, List, Optional
from tqdm import tqdm
from christmas_tree.common.settings import PATH_SAVE, TOTAL_LEDS
import cv2
import numpy as np | 1,251 | contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
centers = []
for contour in contours:
M = cv2.moments(contour)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
centers.append(Point(cX, cY))
return centers
def _compute_correct_positions(contour_centers: List[Point]) -> Optional[Point]:
if len(contour_centers) == 0:
return None
if len(contour_centers) == 1:
return contour_centers[0]
min_dist = float("inf")
for i in range(len(contour_centers)):
for j in range(i, len(contour_centers)):
if i == j:
continue
xi, yi = contour_centers[i]
xj, yj = contour_centers[j]
dist2 = (xi - xj) ** 2 + (yi - yj) ** 2
if dist2 < min_dist:
min_dist = dist2
if min_dist < MAX_DIST**2:
centers = np.array(contour_centers).mean(axis=0)
return Point(int(centers[0]), int(centers[1]))
return None
def _get_map_from_index_to_position(angle: int) -> Dict[int, Point]:
map_index_to_position = {}
total_errors = 0
for i in range(TOTAL_LEDS):
path = Path("frames") / str(angle) / f"{i}.jpg"
frame = cv2.imread(str(path))
contour_centers = _compute_naive_positions(frame)
center = _compute_correct_positions(contour_centers)
if center is None:
total_errors += 1
map_index_to_position[i] = None
else:
map_index_to_position[i] = _get_uv(center, width, height)
return map_index_to_position
def get_map_index_to_angle_position() -> Dict[int, Dict[int, Point]]:
# map_index_to_angle_position = map from LED index to a map from angle to LED position
angles_to_centers = {}
map_index_to_angle_position = defaultdict(dict)
for angle in tqdm(ANGLES):
map_index_to_position = _get_map_from_index_to_position(angle)
angles_to_centers[angle] = map_index_to_position
for i in range(TOTAL_LEDS):
map_index_to_angle_position[i][angle] = map_index_to_position[i]
return map_index_to_angle_position
def validate_led_positions(map_index_to_angle_position: Dict[int, Dict[int, Point]]) -> None:
total_no_centers = 0
for i in range(TOTAL_LEDS):
num_angles_center_is_defined = sum(el is not None for el in map_index_to_angle_position[i].values())
if num_angles_center_is_defined < 1:
print(f"No center can be found for {i} LED")
total_no_centers += 1
print("Total no LED positions found:", total_no_centers)
def get_frames_to_xyz(map_index_to_angle_position: Dict[int, Dict[int, Point]]) -> Dict[int, tuple]:
# frames_to_xyz = map from LED index to LED position
frames_to_xyz = {}
for i in range(TOTAL_LEDS):
sum_x = 0
sum_z = 0
sum_y = 0
non_nulls = 0
for angle in ANGLES:
radian = np.pi / 180 * angle
center = map_index_to_angle_position[i][angle]
if center is not None:
sum_x += center.x * np.cos(radian)
sum_z += center.x * np.sin(radian)
sum_y += center.y
non_nulls += 1
if non_nulls > 0:
x = 1 / non_nulls * sum_x
z = 1 / non_nulls * sum_z
y = 1 / non_nulls * sum_y
frames_to_xyz[i] = (x, y, z)
else:
frames_to_xyz[i] = None
return frames_to_xyz
def save_to_file(frames_to_xyz: Dict[int, tuple]):
|
### Adjust these three parameters if lots of LEDs cannot be detected
LOWER_THRESHOLD = 135
UPPER_THRESHOLD = 255
MAX_DIST = 40
###
ANGLES = [0, 45, 90, 135, 180, 225, 270, 315]
Point = namedtuple("Point", ["x", "y"])
# get height and width of images from one of the frames
path = Path("frames") / str(ANGLES[0]) / "0.jpg"
frame = cv2.imread(str(path))
height, width, _ = frame.shape
def _get_uv(center: Point, width: int, height: int) -> Point:
px, py = center
u = 2 / width * px - 1
v = -2 / height * py + 1
return Point(u, v)
def _compute_naive_positions(image: np.ndarray) -> List[Point]:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, LOWER_THRESHOLD, UPPER_THRESHOLD, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
centers = []
for contour in contours:
M = cv2.moments(contour)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
centers.append(Point(cX, cY))
return centers
def _compute_correct_positions(contour_centers: List[Point]) -> Optional[Point]:
if len(contour_centers) == 0:
return None
if len(contour_centers) == 1:
return contour_centers[0]
min_dist = float("inf")
for i in range(len(contour_centers)):
for j in range(i, len(contour_centers)):
if i == j:
continue
xi, yi = contour_centers[i]
xj, yj = contour_centers[j]
dist2 = (xi - xj) ** 2 + (yi - yj) ** 2
if dist2 < min_dist:
min_dist = dist2
if min_dist < MAX_DIST**2:
centers = np.array(contour_centers).mean(axis=0)
return Point(int(centers[0]), int(centers[1]))
return None
def _get_map_from_index_to_position(angle: int) -> Dict[int, Point]:
map_index_to_position = {}
total_errors = 0
for i in range(TOTAL_LEDS):
path = Path("frames") / str(angle) / f"{i}.jpg"
frame = cv2.imread(str(path))
contour_centers = _compute_naive_positions(frame)
center = _compute_correct_positions(contour_centers)
if center is None:
total_errors += 1
map_index_to_position[i] = None
else:
map_index_to_position[i] = _get_uv(center, width, height)
return map_index_to_position
def get_map_index_to_angle_position() -> Dict[int, Dict[int, Point]]:
# map_index_to_angle_position = map from LED index to a map from angle to LED position
angles_to_centers = {}
map_index_to_angle_position = defaultdict(dict)
for angle in tqdm(ANGLES):
map_index_to_position = _get_map_from_index_to_position(angle)
angles_to_centers[angle] = map_index_to_position
for i in range(TOTAL_LEDS):
map_index_to_angle_position[i][angle] = map_index_to_position[i]
return map_index_to_angle_position
def validate_led_positions(map_index_to_angle_position: Dict[int, Dict[int, Point]]) -> None:
total_no_centers = 0
for i in range(TOTAL_LEDS):
num_angles_center_is_defined = sum(el is not None for el in map_index_to_angle_position[i].values())
if num_angles_center_is_defined < 1:
print(f"No center can be found for {i} LED")
total_no_centers += 1
print("Total no LED positions found:", total_no_centers)
def get_frames_to_xyz(map_index_to_angle_position: Dict[int, Dict[int, Point]]) -> Dict[int, tuple]:
# frames_to_xyz = map from LED index to LED position
frames_to_xyz = {}
for i in range(TOTAL_LEDS):
sum_x = 0
sum_z = 0
sum_y = 0
non_nulls = 0
for angle in ANGLES:
radian = np.pi / 180 * angle
center = map_index_to_angle_position[i][angle]
if center is not None:
sum_x += center.x * np.cos(radian)
sum_z += center.x * np.sin(radian)
sum_y += center.y
non_nulls += 1
if non_nulls > 0:
x = 1 / non_nulls * sum_x
z = 1 / non_nulls * sum_z
y = 1 / non_nulls * sum_y
frames_to_xyz[i] = (x, y, z)
else:
frames_to_xyz[i] = None
return frames_to_xyz
def save_to_file(frames_to_xyz: Dict[int, tuple]): | with open(PATH_SAVE, "w") as file: | 0 | 2023-12-30 12:25:19+00:00 | 2k |
YYJeffrey/july_server | app/api/v2/message.py | [
{
"identifier": "auth",
"path": "app/lib/token.py",
"snippet": "def verify_token(token):\ndef generate_token(user_id):"
},
{
"identifier": "db",
"path": "app/model/base.py",
"snippet": "class BaseModel(db.Model):\n def __getitem__(self, key):\n def init_on_load(self):\n def __se... | from flask import g
from app import auth, db
from app.lib.exception import Success, Updated
from app.lib.red_print import RedPrint
from app.model.message import Message
from app.service.message import get_message_list | 1,304 | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2023 by Jeffrey.
:license: Apache 2.0, see LICENSE for more details.
"""
api = RedPrint('message')
@api.route('/', methods=['GET'])
@auth.login_required
def get_messages():
"""
获取消息
"""
messages = get_message_list()
return Success(data=messages)
@api.route('/read', methods=['POST'])
@auth.login_required
def read_messages():
"""
已读信息
"""
with db.auto_commit():
db.session.query(Message).filter_by(user_id=g.user.id, is_read=False).update({Message.is_read: True})
| # -*- coding: utf-8 -*-
"""
:copyright: (c) 2023 by Jeffrey.
:license: Apache 2.0, see LICENSE for more details.
"""
api = RedPrint('message')
@api.route('/', methods=['GET'])
@auth.login_required
def get_messages():
"""
获取消息
"""
messages = get_message_list()
return Success(data=messages)
@api.route('/read', methods=['POST'])
@auth.login_required
def read_messages():
"""
已读信息
"""
with db.auto_commit():
db.session.query(Message).filter_by(user_id=g.user.id, is_read=False).update({Message.is_read: True})
| return Updated() | 3 | 2023-12-30 04:08:35+00:00 | 2k |
lchen1019/Image_Cropper | ISAT/widgets/polygon.py | [
{
"identifier": "Object",
"path": "ISAT/annotation.py",
"snippet": "class Object:\n def __init__(self, category:str, group:int, segmentation, area, layer, bbox, iscrowd=0, note=''):\n self.category = category\n self.group = group\n self.segmentation = segmentation\n self.a... | from PyQt5 import QtCore, QtWidgets, QtGui
from ISAT.annotation import Object
from ISAT.configs import STATUSMode, CLICKMode, DRAWMode, CONTOURMode
import typing | 1,085 | # -*- coding: utf-8 -*-
# @Author : LG
class PromptPoint(QtWidgets.QGraphicsPathItem):
def __init__(self, pos, type=0):
super(PromptPoint, self).__init__()
self.color = QtGui.QColor('#0000FF') if type==0 else QtGui.QColor('#00FF00')
self.color.setAlpha(255)
self.painterpath = QtGui.QPainterPath()
self.painterpath.addEllipse(
QtCore.QRectF(-1, -1, 2, 2))
self.setPath(self.painterpath)
self.setBrush(self.color)
self.setPen(QtGui.QPen(self.color, 3))
self.setZValue(1e5)
self.setPos(pos)
class Vertex(QtWidgets.QGraphicsPathItem):
def __init__(self, polygon, color, nohover_size=2):
super(Vertex, self).__init__()
self.polygon = polygon
self.color = color
self.color.setAlpha(255)
self.nohover_size = nohover_size
self.hover_size = self.nohover_size + 2
self.line_width = 0
self.nohover = QtGui.QPainterPath()
self.nohover.addEllipse(QtCore.QRectF(-self.nohover_size//2, -self.nohover_size//2, self.nohover_size, self.nohover_size))
self.hover = QtGui.QPainterPath()
self.hover.addRect(QtCore.QRectF(-self.nohover_size//2, -self.nohover_size//2, self.nohover_size, self.nohover_size))
self.setPath(self.nohover)
self.setBrush(self.color)
self.setPen(QtGui.QPen(self.color, self.line_width))
self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, True)
self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsMovable, True)
self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemSendsGeometryChanges, True)
self.setAcceptHoverEvents(True)
self.setZValue(1e5)
def setColor(self, color):
self.color = QtGui.QColor(color)
self.color.setAlpha(255)
self.setPen(QtGui.QPen(self.color, self.line_width))
self.setBrush(self.color)
def itemChange(self, change: 'QtWidgets.QGraphicsItem.GraphicsItemChange', value: typing.Any):
if change == QtWidgets.QGraphicsItem.GraphicsItemChange.ItemSelectedHasChanged:
self.scene().mainwindow.actionDelete.setEnabled(self.isSelected())
if self.isSelected():
selected_color = QtGui.QColor('#00A0FF')
self.setBrush(selected_color)
else:
self.setBrush(self.color)
if change == QtWidgets.QGraphicsItem.GraphicsItemChange.ItemPositionChange and self.isEnabled():
# 限制顶点移动到图外
if value.x() < 0:
value.setX(0)
if value.x() > self.scene().width()-1:
value.setX(self.scene().width()-1)
if value.y() < 0:
value.setY(0)
if value.y() > self.scene().height()-1:
value.setY(self.scene().height()-1)
index = self.polygon.vertexs.index(self)
self.polygon.movePoint(index, value)
return super(Vertex, self).itemChange(change, value)
def hoverEnterEvent(self, event: 'QGraphicsSceneHoverEvent'):
| # -*- coding: utf-8 -*-
# @Author : LG
class PromptPoint(QtWidgets.QGraphicsPathItem):
def __init__(self, pos, type=0):
super(PromptPoint, self).__init__()
self.color = QtGui.QColor('#0000FF') if type==0 else QtGui.QColor('#00FF00')
self.color.setAlpha(255)
self.painterpath = QtGui.QPainterPath()
self.painterpath.addEllipse(
QtCore.QRectF(-1, -1, 2, 2))
self.setPath(self.painterpath)
self.setBrush(self.color)
self.setPen(QtGui.QPen(self.color, 3))
self.setZValue(1e5)
self.setPos(pos)
class Vertex(QtWidgets.QGraphicsPathItem):
def __init__(self, polygon, color, nohover_size=2):
super(Vertex, self).__init__()
self.polygon = polygon
self.color = color
self.color.setAlpha(255)
self.nohover_size = nohover_size
self.hover_size = self.nohover_size + 2
self.line_width = 0
self.nohover = QtGui.QPainterPath()
self.nohover.addEllipse(QtCore.QRectF(-self.nohover_size//2, -self.nohover_size//2, self.nohover_size, self.nohover_size))
self.hover = QtGui.QPainterPath()
self.hover.addRect(QtCore.QRectF(-self.nohover_size//2, -self.nohover_size//2, self.nohover_size, self.nohover_size))
self.setPath(self.nohover)
self.setBrush(self.color)
self.setPen(QtGui.QPen(self.color, self.line_width))
self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, True)
self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsMovable, True)
self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemSendsGeometryChanges, True)
self.setAcceptHoverEvents(True)
self.setZValue(1e5)
def setColor(self, color):
self.color = QtGui.QColor(color)
self.color.setAlpha(255)
self.setPen(QtGui.QPen(self.color, self.line_width))
self.setBrush(self.color)
def itemChange(self, change: 'QtWidgets.QGraphicsItem.GraphicsItemChange', value: typing.Any):
if change == QtWidgets.QGraphicsItem.GraphicsItemChange.ItemSelectedHasChanged:
self.scene().mainwindow.actionDelete.setEnabled(self.isSelected())
if self.isSelected():
selected_color = QtGui.QColor('#00A0FF')
self.setBrush(selected_color)
else:
self.setBrush(self.color)
if change == QtWidgets.QGraphicsItem.GraphicsItemChange.ItemPositionChange and self.isEnabled():
# 限制顶点移动到图外
if value.x() < 0:
value.setX(0)
if value.x() > self.scene().width()-1:
value.setX(self.scene().width()-1)
if value.y() < 0:
value.setY(0)
if value.y() > self.scene().height()-1:
value.setY(self.scene().height()-1)
index = self.polygon.vertexs.index(self)
self.polygon.movePoint(index, value)
return super(Vertex, self).itemChange(change, value)
def hoverEnterEvent(self, event: 'QGraphicsSceneHoverEvent'): | if self.scene().mode == STATUSMode.CREATE: # CREATE | 1 | 2023-12-24 16:19:16+00:00 | 2k |
aoki-h-jp/crypto-listed-detector | crypto_listed_detector/detector.py | [
{
"identifier": "BinanceFetch",
"path": "crypto_listed_detector/fetchapi/binance.py",
"snippet": "class BinanceFetch:\n _BASE_URL = \"https://fapi.binance.com\"\n\n def __init__(self):\n pass\n\n def get_linear_ticker(self):\n url = self._BASE_URL + \"/fapi/v1/exchangeInfo\"\n ... | import json
from crypto_listed_detector.fetchapi.binance import BinanceFetch
from crypto_listed_detector.fetchapi.bitget import BitgetFetch
from crypto_listed_detector.fetchapi.bybit import BybitFetch
from crypto_listed_detector.fetchapi.gateio import GateioFetch
from crypto_listed_detector.fetchapi.kucoin import KucoinFetch
from crypto_listed_detector.fetchapi.mexc import MexcFetch
from crypto_listed_detector.fetchapi.okx import OkxFetch
from crypto_listed_detector.fetchapi.phemex import PhemexFetch
from crypto_listed_detector.fetchapi.pionex import PionexFetch
from crypto_listed_detector.fetchapi.xtcom import XtcomFetch | 1,437 | """
crypto-listed-detector
"""
class Detector:
def __init__(self):
"""
Init all fetchers
"""
| """
crypto-listed-detector
"""
class Detector:
def __init__(self):
"""
Init all fetchers
""" | self.bybit = BybitFetch() | 2 | 2023-12-27 10:39:18+00:00 | 2k |
harvestingmoon/StableVisionBot | bot.py | [
{
"identifier": "BackEnd",
"path": "backend.py",
"snippet": "class BackEnd:\n def __init__(self,model_id) -> None:\n self.model = None\n self.curr_picture = None \n self.final_img = None\n self.call = {1:False,2:False}\n self.model_id = (model_id if model_id else \"... | from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update,InlineKeyboardButton,InlineKeyboardMarkup
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
ConversationHandler,
MessageHandler,
CallbackQueryHandler,
filters,
CallbackContext,
)
from backend import BackEnd,post_process
from PIL import Image
import numpy as np
import json
import logging
import yaml
import emoji
import asyncio | 1,161 | # Simple telegram bot that takes uses stable diffusion
''' Importing YAML'''
with open("config .yaml", "r") as f:
config = yaml.safe_load(f)
model = config['model']
api_key = config['API_KEY']
''' States for bot'''
ONE,TWO,DOCUMENT,PHOTO = range(4)
START,T2IMG,T2IMG2,IMG2IMG,IMG2IMG2,OUTPUT= range(6)
''' User logging'''
logging.basicConfig(
format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s', level = logging.INFO
)
logger = logging.getLogger(__name__)
''' Important pipeline for stable diffusion'''
| # Simple telegram bot that takes uses stable diffusion
''' Importing YAML'''
with open("config .yaml", "r") as f:
config = yaml.safe_load(f)
model = config['model']
api_key = config['API_KEY']
''' States for bot'''
ONE,TWO,DOCUMENT,PHOTO = range(4)
START,T2IMG,T2IMG2,IMG2IMG,IMG2IMG2,OUTPUT= range(6)
''' User logging'''
logging.basicConfig(
format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s', level = logging.INFO
)
logger = logging.getLogger(__name__)
''' Important pipeline for stable diffusion''' | engine = BackEnd(model) | 0 | 2023-12-22 07:25:26+00:00 | 2k |
khabbazan/Mattermost-Subscriptions | apps/chat/gql/subscriptions.py | [
{
"identifier": "MessageQueryType",
"path": "apps/chat/gql/types.py",
"snippet": "class MessageQueryType(graphene.ObjectType):\n \"\"\"\n GraphQL type representing a message in a chat system.\n \"\"\"\n\n id = graphene.String(description=\"Unique identifier of the message.\")\n\n def reso... | import graphene
from apps.chat.gql.types import MessageQueryType
from helpers.channels_graphql_ws import subscription | 652 |
class OnNewChatMessage(subscription.Subscription):
"""
GraphQL Subscription for new chat messages.
This subscription allows clients to listen for new messages on a specified channel.
"""
channel_identifier = graphene.String()
|
class OnNewChatMessage(subscription.Subscription):
"""
GraphQL Subscription for new chat messages.
This subscription allows clients to listen for new messages on a specified channel.
"""
channel_identifier = graphene.String() | message = graphene.Field(MessageQueryType) | 0 | 2023-12-25 11:40:56+00:00 | 2k |
Hatins/DEOE | models/detection/yolox_extension/models/yolo_pafpn.py | [
{
"identifier": "BaseConv",
"path": "models/detection/yolox/models/network_blocks.py",
"snippet": "class BaseConv(nn.Module):\n \"\"\"A Conv2d -> Batchnorm -> silu/leaky relu block\"\"\"\n\n def __init__(\n self, in_channels, out_channels, ksize, stride, groups=1, bias=False, act=\"silu\"\n... | from typing import Dict, Optional, Tuple
from torch import compile as th_compile
from ...yolox.models.network_blocks import BaseConv, CSPLayer, DWConv
from data.utils.types import BackboneFeatures
import torch as th
import torch.nn as nn | 1,394 | """
Original Yolox PAFPN code with slight modifications
"""
try:
except ImportError:
th_compile = None
class YOLOPAFPN(nn.Module):
"""
Removed the direct dependency on the backbone.
"""
def __init__(
self,
depth: float = 1.0,
in_stages: Tuple[int, ...] = (2, 3, 4),
in_channels: Tuple[int, ...] = (256, 512, 1024),
depthwise: bool = False,
act: str = "silu",
compile_cfg: Optional[Dict] = None,
):
super().__init__()
assert len(in_stages) == len(in_channels)
assert len(in_channels) == 3, 'Current implementation only for 3 feature maps'
self.in_features = in_stages
self.in_channels = in_channels
Conv = DWConv if depthwise else BaseConv
###### Compile if requested ######
if compile_cfg is not None:
compile_mdl = compile_cfg['enable']
if compile_mdl and th_compile is not None:
self.forward = th_compile(self.forward, **compile_cfg['args'])
elif compile_mdl:
print('Could not compile PAFPN because torch.compile is not available')
##################################
self.upsample = lambda x: nn.functional.interpolate(x, scale_factor=2, mode='nearest-exact')
self.lateral_conv0 = BaseConv(
in_channels[2], in_channels[1], 1, 1, act=act
)
| """
Original Yolox PAFPN code with slight modifications
"""
try:
except ImportError:
th_compile = None
class YOLOPAFPN(nn.Module):
"""
Removed the direct dependency on the backbone.
"""
def __init__(
self,
depth: float = 1.0,
in_stages: Tuple[int, ...] = (2, 3, 4),
in_channels: Tuple[int, ...] = (256, 512, 1024),
depthwise: bool = False,
act: str = "silu",
compile_cfg: Optional[Dict] = None,
):
super().__init__()
assert len(in_stages) == len(in_channels)
assert len(in_channels) == 3, 'Current implementation only for 3 feature maps'
self.in_features = in_stages
self.in_channels = in_channels
Conv = DWConv if depthwise else BaseConv
###### Compile if requested ######
if compile_cfg is not None:
compile_mdl = compile_cfg['enable']
if compile_mdl and th_compile is not None:
self.forward = th_compile(self.forward, **compile_cfg['args'])
elif compile_mdl:
print('Could not compile PAFPN because torch.compile is not available')
##################################
self.upsample = lambda x: nn.functional.interpolate(x, scale_factor=2, mode='nearest-exact')
self.lateral_conv0 = BaseConv(
in_channels[2], in_channels[1], 1, 1, act=act
) | self.C3_p4 = CSPLayer( | 1 | 2023-12-29 04:04:34+00:00 | 2k |
yeyingdege/ctr-din-pytorch | din/model.py | [
{
"identifier": "EmbeddingLayer",
"path": "din/embedding.py",
"snippet": "class EmbeddingLayer(nn.Module):\n def __init__(self, num_emb, embedding_dim):\n super(EmbeddingLayer, self).__init__()\n\n self.embeddings = nn.Embedding(num_emb, embedding_dim)\n nn.init.xavier_uniform_(s... | import torch
import torch.nn as nn
from torch.nn import functional as F
from .embedding import EmbeddingLayer
from .fc import FCLayer
from .attention import DinAttentionLayer | 1,019 |
class DeepInterestNetwork(nn.Module):
def __init__(self, n_uid, n_mid, n_cat, EMBEDDING_DIM, HIDDEN_DIM=[162,200,80,2]):
super(DeepInterestNetwork, self).__init__()
self.embedding_dim = EMBEDDING_DIM
self.hid_dim = HIDDEN_DIM
# embeddings
self.uid_embeddings = EmbeddingLayer(n_uid, self.embedding_dim)
self.mid_embeddings = EmbeddingLayer(n_mid, self.embedding_dim)
self.cat_embeddings = EmbeddingLayer(n_cat, self.embedding_dim)
self.attn = DinAttentionLayer(embedding_dim=self.embedding_dim*2)
mlp_input_dim = self.embedding_dim * 9
self.mlp = nn.Sequential(
|
class DeepInterestNetwork(nn.Module):
def __init__(self, n_uid, n_mid, n_cat, EMBEDDING_DIM, HIDDEN_DIM=[162,200,80,2]):
super(DeepInterestNetwork, self).__init__()
self.embedding_dim = EMBEDDING_DIM
self.hid_dim = HIDDEN_DIM
# embeddings
self.uid_embeddings = EmbeddingLayer(n_uid, self.embedding_dim)
self.mid_embeddings = EmbeddingLayer(n_mid, self.embedding_dim)
self.cat_embeddings = EmbeddingLayer(n_cat, self.embedding_dim)
self.attn = DinAttentionLayer(embedding_dim=self.embedding_dim*2)
mlp_input_dim = self.embedding_dim * 9
self.mlp = nn.Sequential( | FCLayer(mlp_input_dim, hidden_size=self.hid_dim[1], bias=True, batch_norm=True, activation='dice'), | 1 | 2023-12-27 05:53:50+00:00 | 2k |
iamlooper/VIC-TG-Bot | app/core/client/filters.py | [
{
"identifier": "Config",
"path": "app/config.py",
"snippet": "class _Config:\n class CMD:\n def __init__(self, func, path, doc):\n def __init__(self):\n def __str__(self):"
},
{
"identifier": "Conversation",
"path": "app/core/client/conversation.py",
"snippet": "class Co... | from pyrogram import filters as _filters
from pyrogram.types import Message
from app import Config
from app.core.client.conversation import Conversation | 867 |
# Overall BOT filters
convo_filter = _filters.create(
lambda _, __, message: (message.chat.id in Conversation.CONVO_DICT.keys())
and (not message.reactions)
)
def cmd_check(message: Message, trigger: str) -> bool:
start_str = message.text.split(maxsplit=1)[0]
cmd = start_str.replace(trigger, "", 1)
|
# Overall BOT filters
convo_filter = _filters.create(
lambda _, __, message: (message.chat.id in Conversation.CONVO_DICT.keys())
and (not message.reactions)
)
def cmd_check(message: Message, trigger: str) -> bool:
start_str = message.text.split(maxsplit=1)[0]
cmd = start_str.replace(trigger, "", 1) | return bool(cmd in Config.CMD_DICT.keys()) | 0 | 2023-12-24 05:00:58+00:00 | 2k |
Enthusiasm23/primkit | src/primkit/utils/LoggerSetup.py | [
{
"identifier": "LOG_LEVEL",
"path": "src/primkit/config.py",
"snippet": "LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO') # 日志级别"
},
{
"identifier": "LOG_FILE",
"path": "src/primkit/config.py",
"snippet": "LOG_FILE = os.environ.get('LOG_FILE', None) # 日志文件路径"
},
{
"identifier":... | import logging
import logging.handlers
from ..config import LOG_LEVEL, LOG_FILE, LOG_FORMAT, \
LOG_FILE_MODE, MAX_LOG_SIZE, BACKUP_COUNT, LOG_STREAM | 741 |
def setup_logging(
level=None,
log_file=None,
format=None,
log_file_mode=None,
max_log_size=None,
backup_count=None,
stream=None
):
"""
Configure logging for the application.
:param level: The logging level, e.g., 'DEBUG', 'INFO', 'WARNING'. Defaults to value from config.py but can be overridden by user input.
:param log_file: Path to the log file. If specified, logs will be written to the file. Defaults to value from config.py but can be overridden by user input.
:param format: The format for the logging messages. Defaults to value from config.py but can be overridden by user input.
:param log_file_mode: The mode for writing to the log file, e.g., 'a' for append mode. Defaults to value from config.py but can be overridden by user input.
:param max_log_size: The maximum size of the log file in bytes. When exceeded, the log will rotate. Defaults to value from config.py but can be overridden by user input.
:param backup_count: The number of backup log files to keep. Defaults to value from config.py but can be overridden by user input.
:param stream: Whether to output logs to the console. Defaults to value from config.py but can be overridden by user input.
The function uses the default configuration or configuration provided by the user. Logging can be directed to a file, console, or both based on parameters.
"""
# Use the default configuration or user-provided configuration
if level is not None:
if isinstance(level, int):
log_level = level
else:
log_level = getattr(logging, level.upper(), logging.INFO)
else:
if isinstance(LOG_LEVEL, int):
log_level = LOG_LEVEL
else:
log_level = getattr(logging, LOG_LEVEL.upper(), logging.INFO)
log_file = log_file if log_file is not None else LOG_FILE
format = format if format is not None else LOG_FORMAT
|
def setup_logging(
level=None,
log_file=None,
format=None,
log_file_mode=None,
max_log_size=None,
backup_count=None,
stream=None
):
"""
Configure logging for the application.
:param level: The logging level, e.g., 'DEBUG', 'INFO', 'WARNING'. Defaults to value from config.py but can be overridden by user input.
:param log_file: Path to the log file. If specified, logs will be written to the file. Defaults to value from config.py but can be overridden by user input.
:param format: The format for the logging messages. Defaults to value from config.py but can be overridden by user input.
:param log_file_mode: The mode for writing to the log file, e.g., 'a' for append mode. Defaults to value from config.py but can be overridden by user input.
:param max_log_size: The maximum size of the log file in bytes. When exceeded, the log will rotate. Defaults to value from config.py but can be overridden by user input.
:param backup_count: The number of backup log files to keep. Defaults to value from config.py but can be overridden by user input.
:param stream: Whether to output logs to the console. Defaults to value from config.py but can be overridden by user input.
The function uses the default configuration or configuration provided by the user. Logging can be directed to a file, console, or both based on parameters.
"""
# Use the default configuration or user-provided configuration
if level is not None:
if isinstance(level, int):
log_level = level
else:
log_level = getattr(logging, level.upper(), logging.INFO)
else:
if isinstance(LOG_LEVEL, int):
log_level = LOG_LEVEL
else:
log_level = getattr(logging, LOG_LEVEL.upper(), logging.INFO)
log_file = log_file if log_file is not None else LOG_FILE
format = format if format is not None else LOG_FORMAT | log_file_mode = log_file_mode if log_file_mode is not None else LOG_FILE_MODE | 3 | 2023-12-25 14:12:46+00:00 | 2k |
Wangyuhao06/2022-adhoc | src/env.py | [
{
"identifier": "random_waypoint",
"path": "pymobility/models/mobility.py",
"snippet": "def random_waypoint(*args, **kwargs):\n return iter(RandomWaypoint(*args, **kwargs))"
},
{
"identifier": "Node",
"path": "src/node.py",
"snippet": "class Node(object):\n def __init__(self,id_nod... | import random
import numpy as np
from math import log2, log10
from queue import Queue
from pymobility.models.mobility import random_waypoint
from src.node import Node
from src.packet import Packet
from src.parameter import *
from src.transtask import Trans_task | 1,479 |
class Environment():
#初始化环境
def __init__(self):
#初始数据-最大节点数
self.node_max=NODE_MAX
self.node_space_size=NODE_MAX
self.node_moving_area=MOV_AREA
#初始化二维平面
|
class Environment():
#初始化环境
def __init__(self):
#初始数据-最大节点数
self.node_max=NODE_MAX
self.node_space_size=NODE_MAX
self.node_moving_area=MOV_AREA
#初始化二维平面 | self.geo_area = random_waypoint(self.node_max, dimensions=(MOV_AREA, MOV_AREA), velocity=(10, 15), wt_max=1.0) | 0 | 2023-12-30 09:35:30+00:00 | 2k |
karthicksivakumarp/gui_read_csv | main.py | [
{
"identifier": "read_csv_file",
"path": "read_from_csv/read_csv_file.py",
"snippet": "class read_csv_data:\r\n def __init__(self):\r\n def read_mult_csv_file(self):\r"
},
{
"identifier": "analyze_data",
"path": "data_analysis/analyze_data.py",
"snippet": "class analyze_csv_data:\n... | from read_from_csv import read_csv_file
from data_analysis import analyze_data
from report_generation import generate_report
from tkinter import Tk
from user_interface import gui
| 800 | # Import necessary modules
# Initialize CSV reader instance
read_csv = read_csv_file.read_csv_data()
# Obtain the function/method for reading multiple CSV files
# Note: "read_mult_csv_file" is a function or method defined in the "read_csv_file" module
main_read_csv = read_csv.read_mult_csv_file
# Initialize data analyzer instance
analyze_data = analyze_data.analyze_csv_data()
# Initialize report generator instance
report_gen = generate_report.generate_report()
# Create the main Tkinter window
root = Tk()
root.title('Csv DataAnalyzer') # Set the title of the Tkinter window
root.geometry("800x600") # Set the initial dimensions of the Tkinter window
# Create the user interface (GUI) using the UI class from the "user_interface" module
# Pass the necessary components (main_read_csv, analyze_data, report_gen) to the GUI
| # Import necessary modules
# Initialize CSV reader instance
read_csv = read_csv_file.read_csv_data()
# Obtain the function/method for reading multiple CSV files
# Note: "read_mult_csv_file" is a function or method defined in the "read_csv_file" module
main_read_csv = read_csv.read_mult_csv_file
# Initialize data analyzer instance
analyze_data = analyze_data.analyze_csv_data()
# Initialize report generator instance
report_gen = generate_report.generate_report()
# Create the main Tkinter window
root = Tk()
root.title('Csv DataAnalyzer') # Set the title of the Tkinter window
root.geometry("800x600") # Set the initial dimensions of the Tkinter window
# Create the user interface (GUI) using the UI class from the "user_interface" module
# Pass the necessary components (main_read_csv, analyze_data, report_gen) to the GUI
| gui.UI(root, main_read_csv, analyze_data, report_gen)
| 3 | 2023-12-25 18:49:42+00:00 | 2k |
Slenderman00/Ask-Surf | AskSurf/cli.py | [
{
"identifier": "load_settings",
"path": "AskSurf/settings.py",
"snippet": "def load_settings():\n # check if settings.toml exists\n if not settings_exist():\n create_settings()\n edit_settings()\n return load_settings()\n\n with open(own_dir / \"settings.toml\", \"r\") as ... | import os
import requests
import argparse
import tqdm
import time
import subprocess
import sys
from pathlib import Path
from halo import Halo
from .settings import load_settings, settings_exist, edit_settings | 795 |
settings = {}
own_dir = Path(__file__).parent.absolute()
question_pipe = own_dir / "question_pipe"
response_pipe = own_dir / "response_pipe"
def conditional_decorator(dec, condition):
def decorator(func):
if not condition:
# Return the function unchanged, not decorated.
return func
return dec(func)
return decorator
def parse_message(message):
# replace the tags with the correct color codes
message = message.replace("[RED]", "\033[31m")
message = message.replace("[YELLOW]", "\033[33m")
message = message.replace("[ORANGE]", "\033[33m")
message = message.replace("[GREEN]", "\033[32m")
message = message.replace("[PURPLE]", "\033[35m")
message = message.replace("[BLUE]", "\033[34m")
message = message.replace("[NORMAL]", "\033[0m")
# replace all end tags with the normal color code
message = message.replace("[/RED]", "\033[0m")
message = message.replace("[/YELLOW]", "\033[0m")
message = message.replace("[/ORANGE]", "\033[0m")
message = message.replace("[/GREEN]", "\033[0m")
message = message.replace("[/PURPLE]", "\033[0m")
message = message.replace("[/BLUE]", "\033[0m")
message = message.replace("[/NORMAL]", "\033[0m")
return message
def init():
if not model_exists():
print("Please select a model")
download_model(select_model())
if not settings_exist():
print("Please make sure the settings are correct")
settings = load_settings()
exit(1)
def main():
"""Main entry point for the application"""
init()
# parse the arguments
parser = argparse.ArgumentParser(description="AskSurf CLI")
parser.add_argument(
"question",
nargs=argparse.REMAINDER,
help="The question to ask Dolphin",
)
parser.add_argument(
"--model",
"-m",
action="store_true",
help="The model to use",
)
parser.add_argument(
"--delete",
"-d",
action="store_true",
help="Delete the model",
)
parser.add_argument(
"--kill",
"-k",
action="store_true",
help="Kill the Dolphin service",
)
parser.add_argument(
"--settings",
"-s",
action="store_true",
help="Edit the settings",
)
args = parser.parse_args()
if args.model:
download_model(select_model())
return
if args.delete:
delete_model()
return
if args.kill:
os.system("pkill -f dolphin_service.py")
return
if args.settings:
|
settings = {}
own_dir = Path(__file__).parent.absolute()
question_pipe = own_dir / "question_pipe"
response_pipe = own_dir / "response_pipe"
def conditional_decorator(dec, condition):
def decorator(func):
if not condition:
# Return the function unchanged, not decorated.
return func
return dec(func)
return decorator
def parse_message(message):
# replace the tags with the correct color codes
message = message.replace("[RED]", "\033[31m")
message = message.replace("[YELLOW]", "\033[33m")
message = message.replace("[ORANGE]", "\033[33m")
message = message.replace("[GREEN]", "\033[32m")
message = message.replace("[PURPLE]", "\033[35m")
message = message.replace("[BLUE]", "\033[34m")
message = message.replace("[NORMAL]", "\033[0m")
# replace all end tags with the normal color code
message = message.replace("[/RED]", "\033[0m")
message = message.replace("[/YELLOW]", "\033[0m")
message = message.replace("[/ORANGE]", "\033[0m")
message = message.replace("[/GREEN]", "\033[0m")
message = message.replace("[/PURPLE]", "\033[0m")
message = message.replace("[/BLUE]", "\033[0m")
message = message.replace("[/NORMAL]", "\033[0m")
return message
def init():
if not model_exists():
print("Please select a model")
download_model(select_model())
if not settings_exist():
print("Please make sure the settings are correct")
settings = load_settings()
exit(1)
def main():
"""Main entry point for the application"""
init()
# parse the arguments
parser = argparse.ArgumentParser(description="AskSurf CLI")
parser.add_argument(
"question",
nargs=argparse.REMAINDER,
help="The question to ask Dolphin",
)
parser.add_argument(
"--model",
"-m",
action="store_true",
help="The model to use",
)
parser.add_argument(
"--delete",
"-d",
action="store_true",
help="Delete the model",
)
parser.add_argument(
"--kill",
"-k",
action="store_true",
help="Kill the Dolphin service",
)
parser.add_argument(
"--settings",
"-s",
action="store_true",
help="Edit the settings",
)
args = parser.parse_args()
if args.model:
download_model(select_model())
return
if args.delete:
delete_model()
return
if args.kill:
os.system("pkill -f dolphin_service.py")
return
if args.settings: | edit_settings() | 2 | 2023-12-22 19:43:45+00:00 | 2k |
davidsvy/fractal_video | src/prepare_data/diving48.py | [
{
"identifier": "dataset_stats",
"path": "src/utils/data.py",
"snippet": "def dataset_stats(root, ext):\n n_train = len(find_files(dir=os.path.join(root, 'train'), ext=ext))\n n_val = len(find_files(dir=os.path.join(root, 'val'), ext=ext))\n n_test = len(find_files(dir=os.path.join(root, 'test'... | import json
import os
import shutil
from ..utils.data import dataset_stats
from ..utils.other import run_bash | 685 |
def move_files(path_split, dir_src, dir_tgt, ext):
with open(path_split, 'r') as file:
lut = json.load(file)
for item in lut:
filename = f'{item["vid_name"]}.{ext}'
path_src = os.path.join(dir_src, filename)
label = str(item['label'])
dir_label = os.path.join(dir_tgt, label)
path_tgt = os.path.join(dir_label, filename)
os.makedirs(dir_label, exist_ok=True)
shutil.move(path_src, path_tgt)
def diving48(root):
"""
train -> 15943 files
val -> 2096 files
"""
url_data = 'http://www.svcl.ucsd.edu/projects/resound/Diving48_rgb.tar.gz'
url_split_train = 'http://www.svcl.ucsd.edu/projects/resound/Diving48_train.json'
url_split_val = 'http://www.svcl.ucsd.edu/projects/resound/Diving48_test.json'
path_data = os.path.join(root, os.path.basename(url_data))
path_split_train = os.path.join(root, os.path.basename(url_split_train))
path_split_val = os.path.join(root, os.path.basename(url_split_val))
dir_src = os.path.join(root, 'rgb')
dir_train = os.path.join(root, 'train')
dir_val = os.path.join(root, 'val')
ext = 'mp4'
os.makedirs(dir_train, exist_ok=True)
os.makedirs(dir_val, exist_ok=True)
print('\nDownloading DIVING48...')
run_bash(f'wget {url_split_train} -P {root}')
run_bash(f'wget {url_split_val} -P {root}')
run_bash(f'wget {url_data} -P {root}')
print('Extracting DIVING48...')
run_bash(f'tar -xf {path_data} -C {root}')
os.remove(path_data)
move_files(
path_split=path_split_train, dir_src=dir_src,
dir_tgt=dir_train, ext=ext
)
move_files(
path_split=path_split_val, dir_src=dir_src,
dir_tgt=dir_val, ext=ext
)
shutil.rmtree(dir_src)
os.remove(path_split_train)
os.remove(path_split_val)
|
def move_files(path_split, dir_src, dir_tgt, ext):
with open(path_split, 'r') as file:
lut = json.load(file)
for item in lut:
filename = f'{item["vid_name"]}.{ext}'
path_src = os.path.join(dir_src, filename)
label = str(item['label'])
dir_label = os.path.join(dir_tgt, label)
path_tgt = os.path.join(dir_label, filename)
os.makedirs(dir_label, exist_ok=True)
shutil.move(path_src, path_tgt)
def diving48(root):
"""
train -> 15943 files
val -> 2096 files
"""
url_data = 'http://www.svcl.ucsd.edu/projects/resound/Diving48_rgb.tar.gz'
url_split_train = 'http://www.svcl.ucsd.edu/projects/resound/Diving48_train.json'
url_split_val = 'http://www.svcl.ucsd.edu/projects/resound/Diving48_test.json'
path_data = os.path.join(root, os.path.basename(url_data))
path_split_train = os.path.join(root, os.path.basename(url_split_train))
path_split_val = os.path.join(root, os.path.basename(url_split_val))
dir_src = os.path.join(root, 'rgb')
dir_train = os.path.join(root, 'train')
dir_val = os.path.join(root, 'val')
ext = 'mp4'
os.makedirs(dir_train, exist_ok=True)
os.makedirs(dir_val, exist_ok=True)
print('\nDownloading DIVING48...')
run_bash(f'wget {url_split_train} -P {root}')
run_bash(f'wget {url_split_val} -P {root}')
run_bash(f'wget {url_data} -P {root}')
print('Extracting DIVING48...')
run_bash(f'tar -xf {path_data} -C {root}')
os.remove(path_data)
move_files(
path_split=path_split_train, dir_src=dir_src,
dir_tgt=dir_train, ext=ext
)
move_files(
path_split=path_split_val, dir_src=dir_src,
dir_tgt=dir_val, ext=ext
)
shutil.rmtree(dir_src)
os.remove(path_split_train)
os.remove(path_split_val)
| dataset_stats(root=root, ext=ext) | 0 | 2023-12-27 19:43:45+00:00 | 2k |
OpenBrickProtocolFoundation/client | main.py | [
{
"identifier": "Event",
"path": "tetrion.py",
"snippet": "class Event(NamedTuple):\n key: Key\n type: EventType\n frame: int"
},
{
"identifier": "EventType",
"path": "tetrion.py",
"snippet": "class EventType(Enum):\n PRESSED = 0\n RELEASED = 1"
},
{
"identifier": ... | import pygame
from tetrion import Event
from tetrion import EventType
from tetrion import Key
from tetrion import Tetrion | 754 |
def main() -> None:
frame = 0
with Tetrion() as tetrion:
pygame.init()
RECT_SIZE = 30
size = (RECT_SIZE * tetrion.width, (RECT_SIZE + 2) * tetrion.height)
screen = pygame.display.set_mode(size)
COLORS = [(0, 0, 0),
(0, 240, 240),
(0, 0, 240),
(240, 160, 0),
(240, 240, 0),
(0, 240, 0),
(160, 0, 240),
(240, 0, 0)]
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
elif event.key == pygame.K_a:
|
def main() -> None:
frame = 0
with Tetrion() as tetrion:
pygame.init()
RECT_SIZE = 30
size = (RECT_SIZE * tetrion.width, (RECT_SIZE + 2) * tetrion.height)
screen = pygame.display.set_mode(size)
COLORS = [(0, 0, 0),
(0, 240, 240),
(0, 0, 240),
(240, 160, 0),
(240, 240, 0),
(0, 240, 0),
(160, 0, 240),
(240, 0, 0)]
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
elif event.key == pygame.K_a: | tetrion.enqueue_event(Event(key=Key.LEFT, type=EventType.PRESSED, frame=frame)) | 2 | 2023-12-30 15:25:05+00:00 | 2k |
Birch-san/natten-fwd-ad | script/demo.py | [
{
"identifier": "NattenBlock",
"path": "src/natten_block.py",
"snippet": "class NattenBlock(Module):\n def __init__(self, d_model: int, d_head: int, kernel_size: int):\n super().__init__()\n self.d_head = d_head\n self.n_heads = d_model // d_head\n self.kernel_size = kernel_size\n self.q... | import torch
import torch.autograd.forward_ad as fwAD
from torch import inference_mode, enable_grad
from torch.backends.cuda import sdp_kernel
from src.natten_block import NattenBlock
from src.hood_attn_block import NeighbourhoodAttnBlock | 775 |
device=torch.device('cuda')
dtype=torch.bfloat16
seed=42
d_model=128
d_head=64
kernel_size=13
torch.manual_seed(seed)
|
device=torch.device('cuda')
dtype=torch.bfloat16
seed=42
d_model=128
d_head=64
kernel_size=13
torch.manual_seed(seed) | natten_block = NattenBlock(d_model, d_head=d_head, kernel_size=kernel_size).to(device=device, dtype=dtype) | 0 | 2023-12-22 22:57:36+00:00 | 2k |
ysyBrenda/Transformer-For-Geochemical-Anomaly-Detection | anomaly_detection.py | [
{
"identifier": "Transformer",
"path": "transformer/Models.py",
"snippet": "class Transformer(nn.Module):\n ''' A sequence to sequence model with attention mechanism. '''\n\n def __init__(\n self, src_pad_idx, trg_pad_idx,\n d_word_vec=38, d_model=38, d_inner=2048,\n ... | import torch
import argparse
import dill as pickle
import numpy as np
import calculate_anomalyscore
import torch.utils.data as Data
import time
from tqdm import tqdm
from transformer.Models import Transformer
from transformer.Translator import Translator | 1,019 | '''
geochemical anomaly detection
1,reconstruct geochemical data with trained model.
2,then, identify geochemical anomaly
Author: ysyBrenda
'''
def load_model(opt, device):
checkpoint = torch.load(opt.model, map_location=device)
model_opt = checkpoint['settings']
| '''
geochemical anomaly detection
1,reconstruct geochemical data with trained model.
2,then, identify geochemical anomaly
Author: ysyBrenda
'''
def load_model(opt, device):
checkpoint = torch.load(opt.model, map_location=device)
model_opt = checkpoint['settings']
| model = Transformer( | 0 | 2023-12-22 13:22:58+00:00 | 2k |
camenduru/MotionCtrl-hf | lvdm/modules/attention.py | [
{
"identifier": "conv_nd",
"path": "lvdm/basics.py",
"snippet": "def conv_nd(dims, *args, **kwargs):\n \"\"\"\n Create a 1D, 2D, or 3D convolution module.\n \"\"\"\n if dims == 1:\n return nn.Conv1d(*args, **kwargs)\n elif dims == 2:\n return nn.Conv2d(*args, **kwargs)\n ... | import math
import torch
import torch.nn.functional as F
import xformers
import xformers.ops
from functools import partial
from inspect import isfunction
from einops import rearrange, repeat
from torch import einsum, nn
from lvdm.basics import conv_nd, normalization, zero_module
from lvdm.common import checkpoint, default, exists, init_, max_neg_value, uniq | 1,032 |
try:
XFORMERS_IS_AVAILBLE = True
except:
XFORMERS_IS_AVAILBLE = False
class RelativePosition(nn.Module):
""" https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
def __init__(self, num_units, max_relative_position):
super().__init__()
self.num_units = num_units
self.max_relative_position = max_relative_position
self.embeddings_table = nn.Parameter(torch.Tensor(max_relative_position * 2 + 1, num_units))
nn.init.xavier_uniform_(self.embeddings_table)
def forward(self, length_q, length_k):
device = self.embeddings_table.device
range_vec_q = torch.arange(length_q, device=device)
range_vec_k = torch.arange(length_k, device=device)
distance_mat = range_vec_k[None, :] - range_vec_q[:, None]
distance_mat_clipped = torch.clamp(distance_mat, -self.max_relative_position, self.max_relative_position)
final_mat = distance_mat_clipped + self.max_relative_position
# final_mat = th.LongTensor(final_mat).to(self.embeddings_table.device)
# final_mat = th.tensor(final_mat, device=self.embeddings_table.device, dtype=torch.long)
final_mat = final_mat.long()
embeddings = self.embeddings_table[final_mat]
return embeddings
class CrossAttention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.,
relative_position=False, temporal_length=None):
super().__init__()
inner_dim = dim_head * heads
|
try:
XFORMERS_IS_AVAILBLE = True
except:
XFORMERS_IS_AVAILBLE = False
class RelativePosition(nn.Module):
""" https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
def __init__(self, num_units, max_relative_position):
super().__init__()
self.num_units = num_units
self.max_relative_position = max_relative_position
self.embeddings_table = nn.Parameter(torch.Tensor(max_relative_position * 2 + 1, num_units))
nn.init.xavier_uniform_(self.embeddings_table)
def forward(self, length_q, length_k):
device = self.embeddings_table.device
range_vec_q = torch.arange(length_q, device=device)
range_vec_k = torch.arange(length_k, device=device)
distance_mat = range_vec_k[None, :] - range_vec_q[:, None]
distance_mat_clipped = torch.clamp(distance_mat, -self.max_relative_position, self.max_relative_position)
final_mat = distance_mat_clipped + self.max_relative_position
# final_mat = th.LongTensor(final_mat).to(self.embeddings_table.device)
# final_mat = th.tensor(final_mat, device=self.embeddings_table.device, dtype=torch.long)
final_mat = final_mat.long()
embeddings = self.embeddings_table[final_mat]
return embeddings
class CrossAttention(nn.Module):
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.,
relative_position=False, temporal_length=None):
super().__init__()
inner_dim = dim_head * heads | context_dim = default(context_dim, query_dim) | 4 | 2023-12-27 19:32:03+00:00 | 2k |
vita-epfl/social-transmotion | evaluate_jrdb.py | [
{
"identifier": "batch_process_coords",
"path": "dataset_jrdb.py",
"snippet": "def batch_process_coords(coords, masks, padding_mask, config, modality_selection='traj+2dbox', training=False, multiperson=True):\n joints = coords.to(config[\"DEVICE\"])\n masks = masks.to(config[\"DEVICE\"])\n in_F... | import argparse
import torch
import random
import numpy as np
from progress.bar import Bar
from torch.utils.data import DataLoader
from dataset_jrdb import batch_process_coords, create_dataset, collate_batch
from model_jrdb import create_model
from utils.utils import create_logger | 1,456 |
def inference(model, config, input_joints, padding_mask, out_len=14):
model.eval()
with torch.no_grad():
pred_joints = model(input_joints, padding_mask)
output_joints = pred_joints[:,-out_len:]
return output_joints
def evaluate_ade_fde(model, modality_selection, dataloader, bs, config, logger, return_all=False, bar_prefix="", per_joint=False, show_avg=False):
in_F, out_F = config['TRAIN']['input_track_size'], config['TRAIN']['output_track_size']
bar = Bar(f"EVAL ADE_FDE", fill="#", max=len(dataloader))
batch_size = bs
batch_id = 0
ade = 0
fde = 0
ade_batch = 0
fde_batch = 0
for i, batch in enumerate(dataloader):
joints, masks, padding_mask = batch
padding_mask = padding_mask.to(config["DEVICE"])
|
def inference(model, config, input_joints, padding_mask, out_len=14):
model.eval()
with torch.no_grad():
pred_joints = model(input_joints, padding_mask)
output_joints = pred_joints[:,-out_len:]
return output_joints
def evaluate_ade_fde(model, modality_selection, dataloader, bs, config, logger, return_all=False, bar_prefix="", per_joint=False, show_avg=False):
in_F, out_F = config['TRAIN']['input_track_size'], config['TRAIN']['output_track_size']
bar = Bar(f"EVAL ADE_FDE", fill="#", max=len(dataloader))
batch_size = bs
batch_id = 0
ade = 0
fde = 0
ade_batch = 0
fde_batch = 0
for i, batch in enumerate(dataloader):
joints, masks, padding_mask = batch
padding_mask = padding_mask.to(config["DEVICE"])
| in_joints, in_masks, out_joints, out_masks, padding_mask = batch_process_coords(joints, masks, padding_mask, config, modality_selection) | 0 | 2023-12-25 15:12:40+00:00 | 2k |
facebookresearch/ca_body | ca_body/nn/shadow.py | [
{
"identifier": "tile2d",
"path": "ca_body/nn/blocks.py",
"snippet": "def tile2d(x, size: int):\n \"\"\"Tile a given set of features into a convolutional map.\n\n Args:\n x: float tensor of shape [N, F]\n size: int or a tuple\n\n Returns:\n a feature map [N, F, size[0], siz... | import logging
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import ca_body.nn.layers as la
from typing import Optional, Dict
from ca_body.nn.blocks import tile2d, weights_initializer | 1,068 | # 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.
# TODO: use shared utils here?
logger = logging.getLogger(__name__)
class ShadowUNet(nn.Module):
def __init__(
self,
uv_size,
ao_mean,
shadow_size,
lrelu_slope=0.2,
beta=1.0,
n_dims=64,
interp_mode="bilinear",
biases=True,
trainable_mean=False,
):
super().__init__()
# this is the size of the output
self.uv_size = uv_size
self.shadow_size = shadow_size
ao_mean = F.interpolate(
th.as_tensor(ao_mean)[np.newaxis],
size=(self.shadow_size, self.shadow_size),
)[0]
if not trainable_mean:
# TODO:
self.register_buffer("ao_mean", ao_mean)
else:
self.register_parameter("ao_mean", th.nn.Parameter(ao_mean))
self.depth = 3
self.lrelu_slope = lrelu_slope
self.interp_mode = interp_mode
self.align_corners = None
if interp_mode == "bilinear":
self.align_corners = False
# the base number of dimensions for the shadow maps
n_dims = n_dims
# TODO: generate this?
self.n_enc_dims = [
(1, n_dims),
(n_dims, n_dims),
(n_dims, n_dims),
(n_dims, n_dims),
]
self.sizes = [shadow_size // (2**i) for i in range(len(self.n_enc_dims))]
logger.debug(f"sizes: {self.sizes}")
self.enc_layers = nn.ModuleList()
for i, size in enumerate(self.sizes):
n_in, n_out = self.n_enc_dims[i]
logger.debug(f"EncoderLayers({i}): {n_in}, {n_out}, {size}")
self.enc_layers.append(
nn.Sequential(
la.Conv2dWNUB(
n_in,
n_out,
kernel_size=3,
height=size,
width=size,
stride=1,
padding=1,
),
nn.LeakyReLU(self.lrelu_slope, inplace=True),
)
)
self.n_dec_dims = [
(n_dims, n_dims),
(n_dims * 2, n_dims),
(n_dims * 2, n_dims),
(n_dims * 2, n_dims),
]
self.dec_layers = nn.ModuleList()
for i in range(len(self.sizes)):
size = self.sizes[-i - 1]
n_in, n_out = self.n_dec_dims[i]
logger.debug(f"DecoderLayer({i}): {n_in}, {n_out}, {size}")
self.dec_layers.append(
nn.Sequential(
la.Conv2dWNUB(
n_in,
n_out,
kernel_size=3,
height=size,
width=size,
stride=1,
padding=1,
),
nn.LeakyReLU(self.lrelu_slope, inplace=True),
)
)
| # 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.
# TODO: use shared utils here?
logger = logging.getLogger(__name__)
class ShadowUNet(nn.Module):
def __init__(
self,
uv_size,
ao_mean,
shadow_size,
lrelu_slope=0.2,
beta=1.0,
n_dims=64,
interp_mode="bilinear",
biases=True,
trainable_mean=False,
):
super().__init__()
# this is the size of the output
self.uv_size = uv_size
self.shadow_size = shadow_size
ao_mean = F.interpolate(
th.as_tensor(ao_mean)[np.newaxis],
size=(self.shadow_size, self.shadow_size),
)[0]
if not trainable_mean:
# TODO:
self.register_buffer("ao_mean", ao_mean)
else:
self.register_parameter("ao_mean", th.nn.Parameter(ao_mean))
self.depth = 3
self.lrelu_slope = lrelu_slope
self.interp_mode = interp_mode
self.align_corners = None
if interp_mode == "bilinear":
self.align_corners = False
# the base number of dimensions for the shadow maps
n_dims = n_dims
# TODO: generate this?
self.n_enc_dims = [
(1, n_dims),
(n_dims, n_dims),
(n_dims, n_dims),
(n_dims, n_dims),
]
self.sizes = [shadow_size // (2**i) for i in range(len(self.n_enc_dims))]
logger.debug(f"sizes: {self.sizes}")
self.enc_layers = nn.ModuleList()
for i, size in enumerate(self.sizes):
n_in, n_out = self.n_enc_dims[i]
logger.debug(f"EncoderLayers({i}): {n_in}, {n_out}, {size}")
self.enc_layers.append(
nn.Sequential(
la.Conv2dWNUB(
n_in,
n_out,
kernel_size=3,
height=size,
width=size,
stride=1,
padding=1,
),
nn.LeakyReLU(self.lrelu_slope, inplace=True),
)
)
self.n_dec_dims = [
(n_dims, n_dims),
(n_dims * 2, n_dims),
(n_dims * 2, n_dims),
(n_dims * 2, n_dims),
]
self.dec_layers = nn.ModuleList()
for i in range(len(self.sizes)):
size = self.sizes[-i - 1]
n_in, n_out = self.n_dec_dims[i]
logger.debug(f"DecoderLayer({i}): {n_in}, {n_out}, {size}")
self.dec_layers.append(
nn.Sequential(
la.Conv2dWNUB(
n_in,
n_out,
kernel_size=3,
height=size,
width=size,
stride=1,
padding=1,
),
nn.LeakyReLU(self.lrelu_slope, inplace=True),
)
)
| self.apply(weights_initializer(self.lrelu_slope)) | 1 | 2023-12-27 15:31:35+00:00 | 2k |
0x00wolf/hkrsAI | src/logger.py | [
{
"identifier": "PathFinder",
"path": "src/pathfinder.py",
"snippet": "class PathFinder:\n \"\"\"Class that returns an object with necessary paths for runtime operations\"\"\"\n def __init__(self, cwd: str):\n self.cwd = cwd\n self.config = f'{self.cwd}/config.json'\n self.log... | import os
import re
import json
from typing import Type
from src.pathfinder import PathFinder
from src.conversation import Conversation | 1,302 |
class Logger:
def __init__(self, paths: PathFinder, log_level: int, log_format: str):
"""Logs conversations and saves data at the user's request"""
self.level: int = log_level
self.format: str = log_format
self.paths: Paths = paths
self.number: int = 0
self.file: str = ''
self.savefile: str = ''
self.save_number: int = 0
self.new_log()
@property
def level(self):
return self._level
@level.setter
def level(self, new_value: int):
if 1 != new_value != 2:
raise TypeError
else:
self._level = new_value
@property
def format(self):
return self._format
@format.setter
def format(self, new_value: str):
if new_value == 'txt' or new_value == 'json':
self._format = new_value
else:
self._format = new_value
def new_log(self):
self.number = self._next_number()
self.file = self._new_file()
def _next_number(self):
"""Fetch the next log number from config.json and updates it"""
config_data = self._load(self.paths.config)
self.number = log_num = config_data['log_number']
config_data['log_number'] = self.number + 1
self._dump(config_data, self.paths.config)
return self.number
def _new_file(self):
"""Generates a new logfile relative the current log number"""
while True: # to prevent inadvertently overwriting logs if the value is changed in config.json
self.file = f'{self.paths.logs}/log{self.number}.{self.format}'
try:
with open(self.file, 'x'):
print(f'[*] logfile generated ~ {self.file}')
return self.file
except FileExistsError:
self.number += 1
|
class Logger:
def __init__(self, paths: PathFinder, log_level: int, log_format: str):
"""Logs conversations and saves data at the user's request"""
self.level: int = log_level
self.format: str = log_format
self.paths: Paths = paths
self.number: int = 0
self.file: str = ''
self.savefile: str = ''
self.save_number: int = 0
self.new_log()
@property
def level(self):
return self._level
@level.setter
def level(self, new_value: int):
if 1 != new_value != 2:
raise TypeError
else:
self._level = new_value
@property
def format(self):
return self._format
@format.setter
def format(self, new_value: str):
if new_value == 'txt' or new_value == 'json':
self._format = new_value
else:
self._format = new_value
def new_log(self):
self.number = self._next_number()
self.file = self._new_file()
def _next_number(self):
"""Fetch the next log number from config.json and updates it"""
config_data = self._load(self.paths.config)
self.number = log_num = config_data['log_number']
config_data['log_number'] = self.number + 1
self._dump(config_data, self.paths.config)
return self.number
def _new_file(self):
"""Generates a new logfile relative the current log number"""
while True: # to prevent inadvertently overwriting logs if the value is changed in config.json
self.file = f'{self.paths.logs}/log{self.number}.{self.format}'
try:
with open(self.file, 'x'):
print(f'[*] logfile generated ~ {self.file}')
return self.file
except FileExistsError:
self.number += 1
| def log(self, conversation: Conversation): | 1 | 2023-12-22 07:04:47+00:00 | 2k |
ccurme/chesster | chesster/app/board_manager.py | [
{
"identifier": "display_board",
"path": "chesster/app/utils.py",
"snippet": "def display_board(board, player_side: chess.Color) -> None:\n \"\"\"Display board.\"\"\"\n board_size = 360\n if player_side == chess.WHITE:\n flipped = False\n else:\n flipped = True\n if board.mo... | import os
import urllib
import chess
from typing import Iterator
from fastapi import WebSocket, WebSocketDisconnect
from langserve import RemoteRunnable
from chesster.app.utils import (
display_board,
get_engine_score,
serialize_board_state_with_last_move,
) | 974 |
LANGSERVE_HOST = os.getenv("LANGSERVE_HOST", "localhost")
LANGSERVE_SECRET = os.getenv("LANGSERVE_SECRET", "secret")
CHAT_HISTORY_LENGTH = 50 # Number of most recent (human, ai) exchanges to retain.
class BoardManager:
def __init__(self):
self.active_websockets: list[WebSocket] = []
self.last_updated_image = None
self.board = chess.Board()
self.player_side = chess.WHITE
self.interesting_move_iterator = None
self.chat_history = []
self.remote_runnable = RemoteRunnable(
f"http://{LANGSERVE_HOST}:8001/chesster", headers={"x-token": LANGSERVE_SECRET}
)
async def set_board(self, board: chess.Board) -> None:
"""Set board."""
self.board = board
await self.update_board(self.board)
async def set_player_side(self, player_side: chess.Color) -> None:
"""Set player side."""
self.player_side = player_side
await self.update_board(self.board)
async def set_interesting_move_iterator(self) -> None:
"""Calculate interesting moves in board's move stack."""
self.interesting_move_iterator = self._interesting_move_iterator()
async def make_move(self, move: chess.Move) -> None:
"""Parse move and update board."""
self.board.push(move)
await self.update_board(self.board)
async def _interesting_move_iterator(
self, centipawn_threshold: int = 100
) -> Iterator[chess.Board]:
"""Make iterator over interesting moves according to Chess engine."""
new_board = chess.Board()
centipawns = 0
for move in self.board.move_stack:
new_board.push(move)
new_centipawns = get_engine_score(new_board, self.player_side)
if new_centipawns is None:
continue
delta = new_centipawns - centipawns
if new_board.turn != self.player_side: # player just moved
if abs(delta) > centipawn_threshold:
await self.update_board(new_board)
yield {
|
LANGSERVE_HOST = os.getenv("LANGSERVE_HOST", "localhost")
LANGSERVE_SECRET = os.getenv("LANGSERVE_SECRET", "secret")
CHAT_HISTORY_LENGTH = 50 # Number of most recent (human, ai) exchanges to retain.
class BoardManager:
def __init__(self):
self.active_websockets: list[WebSocket] = []
self.last_updated_image = None
self.board = chess.Board()
self.player_side = chess.WHITE
self.interesting_move_iterator = None
self.chat_history = []
self.remote_runnable = RemoteRunnable(
f"http://{LANGSERVE_HOST}:8001/chesster", headers={"x-token": LANGSERVE_SECRET}
)
async def set_board(self, board: chess.Board) -> None:
"""Set board."""
self.board = board
await self.update_board(self.board)
async def set_player_side(self, player_side: chess.Color) -> None:
"""Set player side."""
self.player_side = player_side
await self.update_board(self.board)
async def set_interesting_move_iterator(self) -> None:
"""Calculate interesting moves in board's move stack."""
self.interesting_move_iterator = self._interesting_move_iterator()
async def make_move(self, move: chess.Move) -> None:
"""Parse move and update board."""
self.board.push(move)
await self.update_board(self.board)
async def _interesting_move_iterator(
self, centipawn_threshold: int = 100
) -> Iterator[chess.Board]:
"""Make iterator over interesting moves according to Chess engine."""
new_board = chess.Board()
centipawns = 0
for move in self.board.move_stack:
new_board.push(move)
new_centipawns = get_engine_score(new_board, self.player_side)
if new_centipawns is None:
continue
delta = new_centipawns - centipawns
if new_board.turn != self.player_side: # player just moved
if abs(delta) > centipawn_threshold:
await self.update_board(new_board)
yield { | "board": serialize_board_state_with_last_move( | 2 | 2023-12-24 19:19:31+00:00 | 2k |
zkarpinski/codeinsight-sdk-python | tests/test_client.py | [
{
"identifier": "CodeInsightClient",
"path": "codeinsight_sdk/client.py",
"snippet": "class CodeInsightClient:\n def __init__(self,\n base_url: str,\n api_token: str,\n timeout: int = 60,\n verify_ssl: bool = True\n ):\n ... | import pytest
import logging
import requests_mock
from codeinsight_sdk import CodeInsightClient
from codeinsight_sdk.exceptions import CodeInsightError | 1,265 |
logger = logging.getLogger(__name__)
## CHANGE ME ##
TEST_URL = "https://api.revenera.com"
TEST_API_TOKEN = "your_api_token"
class TestCodeInsightClient:
@pytest.fixture
def client(self):
return CodeInsightClient(TEST_URL, TEST_API_TOKEN)
def test_client(self, client):
assert client.base_url == TEST_URL
def test_endpoint_not_found(self, client):
with requests_mock.Mocker() as m:
m.get(f"{TEST_URL}/codeinsight/api/projects", status_code=404)
with pytest.raises(Exception):
client.projects.all()
class TestProjectEndpoints:
@pytest.fixture
def client(self):
return CodeInsightClient(TEST_URL, TEST_API_TOKEN)
def test_create_project(self, client):
project_name = "Test"
with requests_mock.Mocker() as m:
m.post(f"{TEST_URL}/codeinsight/api/projects", text='{"data": {"id":1}}')
project_id = client.projects.create(project_name)
assert project_id == 1
def test_get_all_projects(self, client):
with requests_mock.Mocker() as m:
m.get(f"{TEST_URL}/codeinsight/api/projects", text='{"data": [{"id":1, "name":"Test"}, {"id":2, "name":"Test 2"}]}')
projects = client.projects.all()
assert len(projects) > 0
def test_get_project_id(self, client):
project_name = "Test"
with requests_mock.Mocker() as m:
m.get(f"{TEST_URL}/codeinsight/api/project/id", text='{ "Content: ": 1 }') # Yes, the key is called 'Content: ' ...
project_id = client.projects.get_id(project_name)
assert project_id == 1
def test_get_project_id_invalid(self,client):
project_name = "Invalid_Project"
fake_response_json = """{ "Arguments: " : ["",""],
"Key: ": " InvalidProjectNameParm",
"Error: ": "The project name entered was not found" }
"""
with requests_mock.Mocker() as m:
# Note, the key names end with a colon and space '...: '
m.get(f"{TEST_URL}/codeinsight/api/project/id", text=fake_response_json, status_code=400)
|
logger = logging.getLogger(__name__)
## CHANGE ME ##
TEST_URL = "https://api.revenera.com"
TEST_API_TOKEN = "your_api_token"
class TestCodeInsightClient:
@pytest.fixture
def client(self):
return CodeInsightClient(TEST_URL, TEST_API_TOKEN)
def test_client(self, client):
assert client.base_url == TEST_URL
def test_endpoint_not_found(self, client):
with requests_mock.Mocker() as m:
m.get(f"{TEST_URL}/codeinsight/api/projects", status_code=404)
with pytest.raises(Exception):
client.projects.all()
class TestProjectEndpoints:
@pytest.fixture
def client(self):
return CodeInsightClient(TEST_URL, TEST_API_TOKEN)
def test_create_project(self, client):
project_name = "Test"
with requests_mock.Mocker() as m:
m.post(f"{TEST_URL}/codeinsight/api/projects", text='{"data": {"id":1}}')
project_id = client.projects.create(project_name)
assert project_id == 1
def test_get_all_projects(self, client):
with requests_mock.Mocker() as m:
m.get(f"{TEST_URL}/codeinsight/api/projects", text='{"data": [{"id":1, "name":"Test"}, {"id":2, "name":"Test 2"}]}')
projects = client.projects.all()
assert len(projects) > 0
def test_get_project_id(self, client):
project_name = "Test"
with requests_mock.Mocker() as m:
m.get(f"{TEST_URL}/codeinsight/api/project/id", text='{ "Content: ": 1 }') # Yes, the key is called 'Content: ' ...
project_id = client.projects.get_id(project_name)
assert project_id == 1
def test_get_project_id_invalid(self,client):
project_name = "Invalid_Project"
fake_response_json = """{ "Arguments: " : ["",""],
"Key: ": " InvalidProjectNameParm",
"Error: ": "The project name entered was not found" }
"""
with requests_mock.Mocker() as m:
# Note, the key names end with a colon and space '...: '
m.get(f"{TEST_URL}/codeinsight/api/project/id", text=fake_response_json, status_code=400) | with pytest.raises(CodeInsightError): | 1 | 2023-12-29 00:49:12+00:00 | 2k |
chebupelka8/Engine | scripts/loop.py | [
{
"identifier": "Vec2",
"path": "scripts/math.py",
"snippet": "class Vec2:\r\n def __init__(self, x: int | float, y: int | float) -> None:\r\n self.__verify(x, y)\r\n\r\n self.__x = x\r\n self.__y = y\r\n \r\n @staticmethod\r\n def __verify(x, y) -> None:\r\n matc... | import pygame, sys
from pygame.locals import *
from .math import Vec2
from .image import Image
| 951 |
class WindowLoop:
def __init__(self, __size: Vec2, fps: int = 144) -> None:
pygame.init()
self.__display = pygame.display.set_mode((__size.x, __size.y))
pygame.display.set_caption("Engine: v0.1")
|
class WindowLoop:
def __init__(self, __size: Vec2, fps: int = 144) -> None:
pygame.init()
self.__display = pygame.display.set_mode((__size.x, __size.y))
pygame.display.set_caption("Engine: v0.1")
| pygame.display.set_icon(Image("Engine/assets/icon.png").image)
| 1 | 2023-12-25 07:53:49+00:00 | 2k |
lxbme/TSPLifesaver | TSPLifesaver/tools.py | [
{
"identifier": "AbstractPoint",
"path": "TSPLifesaver/abc/abc.py",
"snippet": "class AbstractPoint(ABC, MutableSequence):\n def __delitem__(self, key): ...\n\n def insert(self, index, value): ...\n\n @abstractmethod\n def __init__(self,pos):\n \"\"\"\n Init the Point\n ... | from typing import Iterable, MutableSequence, Type
from random import shuffle
from copy import deepcopy
from TSPLifesaver.abc import AbstractRoute, AbstractPoint
from TSPLifesaver.structure import BasicRoute, PointWithEuclideanDistance
from TSPLifesaver.optimizer import SimulatedAnnealing | 1,502 |
def route_from_sequence(sequence: Iterable[MutableSequence], route: AbstractRoute = BasicRoute([]),
point_class: Type[AbstractPoint] = PointWithEuclideanDistance,
name_offset: int = 1, ) -> AbstractRoute:
"""
:param route: Instances of the AbstractRoute class or its subclasses, defaults to empty instance of BasicRoute
:param name_offset: Index of the name
:param sequence: Sequence containing coordinates
:param point_class: AbstractPoint or its subclasses ,defaults to PointWithEuclideanDistance
:return: a new route
"""
index = name_offset
for pos in sequence:
try:
point = point_class(pos, name=f"{index}")
except:
point = point_class(pos)
route.append(point)
index += 1
return route
def simulated_annealing(route: AbstractRoute, epoch: int = 100, temperature: float = 10000,
cooling_rate: float = 0.03, min_temperature: float = 1,
log: bool = False) -> AbstractRoute:
"""
:param route: Instances of the AbstractRoute class or its subclasses
:param epoch: Number of epochs to simulate, defaults to 100
:param temperature: Temperature of the annealing, defaults to 10000
:param cooling_rate: Cooling rate of the annealing, defaults to 0.03
:param min_temperature: Minimum temperature of the annealing, defaults to 1
:param log: Whether to print the log of the annealing, defaults to False
:return: optimized route
"""
if len(route):
best_route = deepcopy(route)
for i in range(epoch):
if log:
print(f"Running epoch {i} of {epoch}")
shuffle(route)
|
def route_from_sequence(sequence: Iterable[MutableSequence], route: AbstractRoute = BasicRoute([]),
point_class: Type[AbstractPoint] = PointWithEuclideanDistance,
name_offset: int = 1, ) -> AbstractRoute:
"""
:param route: Instances of the AbstractRoute class or its subclasses, defaults to empty instance of BasicRoute
:param name_offset: Index of the name
:param sequence: Sequence containing coordinates
:param point_class: AbstractPoint or its subclasses ,defaults to PointWithEuclideanDistance
:return: a new route
"""
index = name_offset
for pos in sequence:
try:
point = point_class(pos, name=f"{index}")
except:
point = point_class(pos)
route.append(point)
index += 1
return route
def simulated_annealing(route: AbstractRoute, epoch: int = 100, temperature: float = 10000,
cooling_rate: float = 0.03, min_temperature: float = 1,
log: bool = False) -> AbstractRoute:
"""
:param route: Instances of the AbstractRoute class or its subclasses
:param epoch: Number of epochs to simulate, defaults to 100
:param temperature: Temperature of the annealing, defaults to 10000
:param cooling_rate: Cooling rate of the annealing, defaults to 0.03
:param min_temperature: Minimum temperature of the annealing, defaults to 1
:param log: Whether to print the log of the annealing, defaults to False
:return: optimized route
"""
if len(route):
best_route = deepcopy(route)
for i in range(epoch):
if log:
print(f"Running epoch {i} of {epoch}")
shuffle(route) | opt = SimulatedAnnealing(route, temperature=temperature, | 4 | 2023-12-26 10:08:09+00:00 | 2k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.