code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_plugin_twitter_dm_attachments_invalid_attachment( mocker, twitter_url, good_message_response): """ Test case with an invalid attachment. """ mock_post: Mock = mocker.patch("requests.post") mock_post.side_effect = [good_media_response, good_message_response] # Create applicatio...
Test case with an invalid attachment.
test_plugin_twitter_dm_attachments_invalid_attachment
python
caronc/apprise
test/test_plugin_twitter.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_twitter.py
BSD-2-Clause
def test_plugin_twitter_tweet_attachments_more_logging( mock_post, twitter_url, good_media_response): """ NotifyTwitter() Tweet Attachment Checks - More logging TODO: The "more logging" aspect is not verified yet? """ good_tweet_response = good_response({ 'screen_name': TWITTER_SCR...
NotifyTwitter() Tweet Attachment Checks - More logging TODO: The "more logging" aspect is not verified yet?
test_plugin_twitter_tweet_attachments_more_logging
python
caronc/apprise
test/test_plugin_twitter.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_twitter.py
BSD-2-Clause
def test_plugin_whatsapp_auth(mock_post): """ NotifyWhatsApp() Auth - account-wide auth token - API key and its own auth token """ response = mock.Mock() response.content = '' response.status_code = requests.codes.ok # Prepare Mock mock_post.return_value = response # ...
NotifyWhatsApp() Auth - account-wide auth token - API key and its own auth token
test_plugin_whatsapp_auth
python
caronc/apprise
test/test_plugin_whatsapp.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_whatsapp.py
BSD-2-Clause
def test_plugin_windows_mocked(): """ NotifyWindows() General Checks (via non-Windows platform) """ # We need to fake our windows environment for testing purposes win32api_name = 'win32api' win32api = types.ModuleType(win32api_name) sys.modules[win32api_name] = win32api win32api.GetMod...
NotifyWindows() General Checks (via non-Windows platform)
test_plugin_windows_mocked
python
caronc/apprise
test/test_plugin_windows.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_windows.py
BSD-2-Clause
def test_plugin_windows_native(mock_loadimage, mock_notify, mock_update_window): """ NotifyWindows() General Checks (via Windows platform) """ # Create our instance obj = apprise.Apprise.instantiate('windows://', suppress_exceptions=Fal...
NotifyWindows() General Checks (via Windows platform)
test_plugin_windows_native
python
caronc/apprise
test/test_plugin_windows.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_windows.py
BSD-2-Clause
def test_plugin_workflows_templating_basic_success( request_mock, workflows_url, tmpdir): """ NotifyWorkflows() Templating - success. Test cases where URL and JSON is valid. """ template = tmpdir.join("simple.json") template.write(cleandoc(""" { "@type": "MessageCard", "...
NotifyWorkflows() Templating - success. Test cases where URL and JSON is valid.
test_plugin_workflows_templating_basic_success
python
caronc/apprise
test/test_plugin_workflows.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_workflows.py
BSD-2-Clause
def test_plugin_workflows_templating_load_json_failure( request_mock, workflows_url, tmpdir): """ NotifyWorkflows() Templating - template loading failure. Test a case where we can not access the file. """ template = tmpdir.join("empty.json") template.write("") obj = Apprise.instant...
NotifyWorkflows() Templating - template loading failure. Test a case where we can not access the file.
test_plugin_workflows_templating_load_json_failure
python
caronc/apprise
test/test_plugin_workflows.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_workflows.py
BSD-2-Clause
def test_plugin_workflows_templating_target_success( request_mock, workflows_url, tmpdir): """ NotifyWorkflows() Templating - success with target. A more complicated example; uses a target. """ template = tmpdir.join("more_complicated_example.json") template.write(cleandoc(""" { ...
NotifyWorkflows() Templating - success with target. A more complicated example; uses a target.
test_plugin_workflows_templating_target_success
python
caronc/apprise
test/test_plugin_workflows.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_workflows.py
BSD-2-Clause
def test_workflows_yaml_config_missing_template_filename( request_mock, workflows_url, simple_template, tmpdir): """ NotifyWorkflows() YAML Configuration Entries - Missing template reference. """ config = tmpdir.join("workflow01.yml") config.write(cleandoc(""" urls: - {url}: ...
NotifyWorkflows() YAML Configuration Entries - Missing template reference.
test_workflows_yaml_config_missing_template_filename
python
caronc/apprise
test/test_plugin_workflows.py
https://github.com/caronc/apprise/blob/master/test/test_plugin_workflows.py
BSD-2-Clause
def test_notify_overflow_truncate_with_amalgamation(): """ API: Overflow With Amalgamation Truncate Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with body_len = 1024 title_...
API: Overflow With Amalgamation Truncate Functionality Testing
test_notify_overflow_truncate_with_amalgamation
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def test_notify_overflow_truncate_no_amalgamation(): """ API: Overflow No Amalgamation Truncate Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with body_len = 1024 title_len ...
API: Overflow No Amalgamation Truncate Functionality Testing
test_notify_overflow_truncate_no_amalgamation
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def test_notify_overflow_split_with_amalgamation(): """ API: Overflow With Amalgamation Splits Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with body_len = 1024 title_len ...
API: Overflow With Amalgamation Splits Functionality Testing
test_notify_overflow_split_with_amalgamation
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def test_notify_overflow_split_with_amalgamation_force_title_always(): """ API: Overflow With Amalgamation (title alaways Split Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with ...
API: Overflow With Amalgamation (title alaways Split Functionality Testing
test_notify_overflow_split_with_amalgamation_force_title_always
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def test_notify_overflow_split_with_amalgamation_force_title_once(): """ API: Overflow With Amalgamation (title once) Split Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with b...
API: Overflow With Amalgamation (title once) Split Functionality Testing
test_notify_overflow_split_with_amalgamation_force_title_once
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def test_notify_overflow_split_no_amalgamation(): """ API: Overflow No Amalgamation Splits Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with body_len = 1024 title_len = 10...
API: Overflow No Amalgamation Splits Functionality Testing
test_notify_overflow_split_no_amalgamation
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def test_notify_overflow_split_no_amalgamation_force_title_always(): """ API: Overflow No Amalgamation (title always) Split Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with b...
API: Overflow No Amalgamation (title always) Split Functionality Testing
test_notify_overflow_split_no_amalgamation_force_title_always
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def test_notify_overflow_split_no_amalgamation_force_title_once(): """ API: Overflow No Amalgamation (title once) Split Functionality Testing """ # # A little preparation # # Number of characters per line row = 24 # Some variables we use to control the data we work with body_...
API: Overflow No Amalgamation (title once) Split Functionality Testing
test_notify_overflow_split_no_amalgamation_force_title_once
python
caronc/apprise
test/test_rest_plugins.py
https://github.com/caronc/apprise/blob/master/test/test_rest_plugins.py
BSD-2-Clause
def environ(*remove, **update): """ Temporarily updates the ``os.environ`` dictionary in-place. The ``os.environ`` dictionary is updated in-place so that the modification is sure to work in all situations. :param remove: Environment variable(s) to remove. :param update: Dictionary of environme...
Temporarily updates the ``os.environ`` dictionary in-place. The ``os.environ`` dictionary is updated in-place so that the modification is sure to work in all situations. :param remove: Environment variable(s) to remove. :param update: Dictionary of environment variables and values to ...
environ
python
caronc/apprise
test/helpers/environment.py
https://github.com/caronc/apprise/blob/master/test/helpers/environment.py
BSD-2-Clause
def reload_plugin(name): """ Reload built-in plugin module, e.g. `NotifyGnome`. Reloading plugin modules is needed when testing module-level code of notification plugins. See also https://stackoverflow.com/questions/31363311. """ A_MGR.unload_modules() reload(sys.modules['apprise.app...
Reload built-in plugin module, e.g. `NotifyGnome`. Reloading plugin modules is needed when testing module-level code of notification plugins. See also https://stackoverflow.com/questions/31363311.
reload_plugin
python
caronc/apprise
test/helpers/module.py
https://github.com/caronc/apprise/blob/master/test/helpers/module.py
BSD-2-Clause
def add(self, url, meta): """ Adds a test suite to our object """ self.__tests.append({ 'url': url, 'meta': meta, })
Adds a test suite to our object
add
python
caronc/apprise
test/helpers/rest.py
https://github.com/caronc/apprise/blob/master/test/helpers/rest.py
BSD-2-Clause
def __notify( self, url, obj, meta, asset, mock_request, mock_patch, mock_del, mock_put, mock_head, mock_post, mock_get ): """ Perform notification testing against object specified """ # ...
Perform notification testing against object specified
__notify
python
caronc/apprise
test/helpers/rest.py
https://github.com/caronc/apprise/blob/master/test/helpers/rest.py
BSD-2-Clause
def extract_anthropic_prompt(prompt_and_response): """Extract the anthropic prompt from a prompt and response pair.""" search_term = '\n\nAssistant:' search_term_idx = prompt_and_response.rfind(search_term) assert search_term_idx != -1, f"Prompt and response does not contain '{search_term}'" return ...
Extract the anthropic prompt from a prompt and response pair.
extract_anthropic_prompt
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def strip_html_tags(html_string): """Strip HTML tags from a string, except for <code> tags (which contain real code in the StackExchange answers).""" # Create a BeautifulSoup object soup = BeautifulSoup(html_string, 'html.parser') # Initialize an empty list to store the text text = [] for eleme...
Strip HTML tags from a string, except for <code> tags (which contain real code in the StackExchange answers).
strip_html_tags
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def get_se(split, silent=False, cache_dir: str = None) -> Dict[str, Dict[str, Union[List[Tuple[int, int]], List[str], str]]]: """Load the StackExchange dataset from Huggingface, and return a dict of prompts and responses. See get_hh for the format. We strip the HTML tags from the responses (except for <...
Load the StackExchange dataset from Huggingface, and return a dict of prompts and responses. See get_hh for the format. We strip the HTML tags from the responses (except for <code> tags), and we add necessary newlines.
get_se
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def get_shp(split: str, silent: bool = False, cache_dir: str = None) -> Dict[str, Dict[str, Union[List[Tuple[int, int]], List[str], str]]]: """Load the Stanford Human Preferences dataset from Huggingface and convert it to the necessary format. See hh for the format. We filter preference pairs to only keep p...
Load the Stanford Human Preferences dataset from Huggingface and convert it to the necessary format. See hh for the format. We filter preference pairs to only keep pairs where the score ratio is at least 2. For this dataset, the sft_target is the response with the highest score.
get_shp
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def get_hh(split: str, silent: bool = False, cache_dir: str = None) -> Dict[str, Dict[str, Union[List[Tuple[int, int]], List[str], str]]]: """Load the Anthropic Helpful-Harmless dataset from Huggingface and convert it to the necessary format. The dataset is converted to a dictionary with the following s...
Load the Anthropic Helpful-Harmless dataset from Huggingface and convert it to the necessary format. The dataset is converted to a dictionary with the following structure: { 'prompt1': { 'responses': List[str], 'pairs': List[Tuple[int, int]], 's...
get_hh
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def get_dataset(name: str, split: str, silent: bool = False, cache_dir: str = None): """Load the given dataset by name. Supported by default are 'shp', 'hh', and 'se'.""" if name == 'shp': data = get_shp(split, silent=silent, cache_dir=cache_dir) elif name == 'hh': data = get_hh(split, silen...
Load the given dataset by name. Supported by default are 'shp', 'hh', and 'se'.
get_dataset
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def get_collate_fn(tokenizer) -> Callable[[List[Dict]], Dict[str, Union[List, torch.Tensor]]]: """Returns a collate function for the given tokenizer. The collate function takes a list of examples (dicts, where values are lists of ints [tokens] or strings [the original texts]) and returns a batc...
Returns a collate function for the given tokenizer. The collate function takes a list of examples (dicts, where values are lists of ints [tokens] or strings [the original texts]) and returns a batch of examples, PyTorch tensors padded to the maximum length. Strings are passed through.
get_collate_fn
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def tokenize_batch_element(prompt: str, chosen: str, rejected: str, truncation_mode: str, tokenizer, max_length: int, max_prompt_length: int) -> Dict: """Tokenize a single batch element. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + c...
Tokenize a single batch element. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the chosen/rejected. ...
tokenize_batch_element
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def get_batch_iterator(names: List[str], tokenizer, split: str = 'train', batch_size: int = 1, shuffle: bool = True, max_length: int = 512, max_prompt_length: int = 128, ...
Get an iterator over batches of data. Stops after n_epochs or n_examples, whichever comes first. Args: names: Names of datasets to use. tokenizer: Tokenizer to use. split: Which split to use. batch_size: Batch size. shuffle: Whether to shuffle the data after each epoch. ...
get_batch_iterator
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def strings_match_up_to_spaces(str_a: str, str_b: str) -> bool: """Returns True if str_a and str_b match up to spaces, False otherwise.""" for idx in range(min(len(str_a), len(str_b)) - 2): if str_a[idx] != str_b[idx]: if str_a[idx] != ' ' and str_b[idx] != ' ': return False ...
Returns True if str_a and str_b match up to spaces, False otherwise.
strings_match_up_to_spaces
python
eric-mitchell/direct-preference-optimization
preference_datasets.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/preference_datasets.py
Apache-2.0
def worker_main(rank: int, world_size: int, config: DictConfig, policy: nn.Module, reference_model: Optional[nn.Module] = None): """Main function for each worker process (may be only 1 for BasicTrainer/TensorParallelTrainer).""" if 'FSDP' in config.trainer: init_distributed(rank, world_size, port=config...
Main function for each worker process (may be only 1 for BasicTrainer/TensorParallelTrainer).
worker_main
python
eric-mitchell/direct-preference-optimization
train.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/train.py
Apache-2.0
def main(config: DictConfig): """Main entry point for training. Validates config, creates/initializes model(s), and kicks off worker process(es).""" # Resolve hydra references, e.g. so we don't re-compute the run directory OmegaConf.resolve(config) missing_keys: Set[str] = OmegaConf.missing_keys(confi...
Main entry point for training. Validates config, creates/initializes model(s), and kicks off worker process(es).
main
python
eric-mitchell/direct-preference-optimization
train.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/train.py
Apache-2.0
def preference_loss(policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor, beta: float, label_smoothing: ...
Compute the DPO loss for a batch of policy and reference model log probabilities. Args: policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_si...
preference_loss
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def concatenated_inputs(batch: Dict[str, Union[List, torch.LongTensor]]) -> Dict[str, torch.LongTensor]: """Concatenate the chosen and rejected inputs into a single tensor. Args: batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (b...
Concatenate the chosen and rejected inputs into a single tensor. Args: batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length). Returns: A dictionary containing the concatenated inputs under...
concatenated_inputs
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def __init__(self, policy: nn.Module, config: DictConfig, seed: int, run_dir: str, reference_model: Optional[nn.Module] = None, rank: int = 0, world_size: int = 1): """A trainer for a language model, supporting either SFT or DPO training. If multiple GPUs are present, naively splits the m...
A trainer for a language model, supporting either SFT or DPO training. If multiple GPUs are present, naively splits the model across them, effectively offering N times available memory, but without any parallel computation.
__init__
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def get_batch_samples(self, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: """Generate samples from the policy (and reference model, if doing DPO training) for the given batch of inputs.""" # FSDP generation according to https://github.com/pytorch/pytorch/issues/100069 ctx = lambda: (F...
Generate samples from the policy (and reference model, if doing DPO training) for the given batch of inputs.
get_batch_samples
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def concatenated_forward(self, model: nn.Module, batch: Dict[str, Union[List, torch.LongTensor]]) -> Tuple[torch.FloatTensor, torch.FloatTensor]: """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. We do this to avoid doing two forward ...
Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. We do this to avoid doing two forward passes, because it's faster for FSDP.
concatenated_forward
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def get_batch_metrics(self, batch: Dict[str, Union[List, torch.LongTensor]], loss_config: DictConfig, train=True): """Compute the SFT or DPO loss and other metrics for the given batch of inputs.""" metrics = {} train_test = 'train' if train else 'eval' if loss_config.name in {'dpo', 'i...
Compute the SFT or DPO loss and other metrics for the given batch of inputs.
get_batch_metrics
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def train(self): """Begin either SFT or DPO training, with periodic evaluation.""" rank0_print(f'Using {self.config.optimizer} optimizer') self.optimizer = getattr(torch.optim, self.config.optimizer)(self.policy.parameters(), lr=self.config.lr) self.scheduler = torch.optim.lr_scheduler....
Begin either SFT or DPO training, with periodic evaluation.
train
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def save(self, output_dir: Optional[str] = None, metrics: Optional[Dict] = None): """Save policy, optimizer, and scheduler state to disk.""" policy_state_dict = self.policy.state_dict() self.write_state_dict(self.example_counter, policy_state_dict, metrics, 'policy.pt', output_dir) del ...
Save policy, optimizer, and scheduler state to disk.
save
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def __init__(self, policy: nn.Module, config: DictConfig, seed: int, run_dir: str, reference_model: Optional[nn.Module] = None, rank: int = 0, world_size: int = 1): """A trainer subclass that uses PyTorch FSDP to shard the model across multiple GPUs. This trainer will shard both the policy a...
A trainer subclass that uses PyTorch FSDP to shard the model across multiple GPUs. This trainer will shard both the policy and reference model across all available GPUs. Models are sharded at the block level, where the block class name is provided in the config.
__init__
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def save(self, output_dir=None, metrics=None): """Save policy, optimizer, and scheduler state to disk, gathering from all processes and saving only on the rank 0 process.""" save_policy = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) with FSDP.state_dict_type(self.policy, StateDictTy...
Save policy, optimizer, and scheduler state to disk, gathering from all processes and saving only on the rank 0 process.
save
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def __init__(self, policy, config, seed, run_dir, reference_model=None, rank=0, world_size=1): """A trainer subclass that uses TensorParallel to shard the model across multiple GPUs. Based on https://github.com/BlackSamorez/tensor_parallel. Note sampling is extremely slow, see https://...
A trainer subclass that uses TensorParallel to shard the model across multiple GPUs. Based on https://github.com/BlackSamorez/tensor_parallel. Note sampling is extremely slow, see https://github.com/BlackSamorez/tensor_parallel/issues/66.
__init__
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def save(self, output_dir=None, metrics=None): """Save (unsharded) policy state to disk.""" with tp.save_tensor_parallel(self.policy): policy_state_dict = self.policy.state_dict() self.write_state_dict(self.example_counter, policy_state_dict, metrics, 'policy.pt', output_dir) ...
Save (unsharded) policy state to disk.
save
python
eric-mitchell/direct-preference-optimization
trainers.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/trainers.py
Apache-2.0
def get_local_dir(prefixes_to_resolve: List[str]) -> str: """Return the path to the cache directory for this user.""" for prefix in prefixes_to_resolve: if os.path.exists(prefix): return f"{prefix}/{getpass.getuser()}" os.makedirs(prefix) return f"{prefix}/{getpass.getuser()}"
Return the path to the cache directory for this user.
get_local_dir
python
eric-mitchell/direct-preference-optimization
utils.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/utils.py
Apache-2.0
def get_local_run_dir(exp_name: str, local_dirs: List[str]) -> str: """Create a local directory to store outputs for this run, and return its path.""" now = datetime.now() timestamp = now.strftime("%Y-%m-%d_%H-%M-%S_%f") run_dir = f"{get_local_dir(local_dirs)}/{exp_name}_{timestamp}" os.makedirs(run...
Create a local directory to store outputs for this run, and return its path.
get_local_run_dir
python
eric-mitchell/direct-preference-optimization
utils.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/utils.py
Apache-2.0
def slice_and_move_batch_for_device(batch: Dict, rank: int, world_size: int, device: str) -> Dict: """Slice a batch into chunks, and move each chunk to the specified device.""" chunk_size = len(list(batch.values())[0]) // world_size start = chunk_size * rank end = chunk_size * (rank + 1) sliced = {k...
Slice a batch into chunks, and move each chunk to the specified device.
slice_and_move_batch_for_device
python
eric-mitchell/direct-preference-optimization
utils.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/utils.py
Apache-2.0
def all_gather_if_needed(values: torch.Tensor, rank: int, world_size: int) -> torch.Tensor: """Gather and stack/cat values from all processes, if there are multiple processes.""" if world_size == 1: return values all_values = [torch.empty_like(values).to(rank) for _ in range(world_size)] dist.a...
Gather and stack/cat values from all processes, if there are multiple processes.
all_gather_if_needed
python
eric-mitchell/direct-preference-optimization
utils.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/utils.py
Apache-2.0
def print_gpu_memory(rank: int = None, message: str = ''): """Print the amount of GPU memory currently allocated for each GPU.""" if torch.cuda.is_available(): device_count = torch.cuda.device_count() for i in range(device_count): device = torch.device(f'cuda:{i}') alloca...
Print the amount of GPU memory currently allocated for each GPU.
print_gpu_memory
python
eric-mitchell/direct-preference-optimization
utils.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/utils.py
Apache-2.0
def get_block_class_from_model(model: torch.nn.Module, block_class_name: str) -> torch.nn.Module: """Get the class of a block from a model, using the block's class name.""" for module in model.modules(): if module.__class__.__name__ == block_class_name: return module.__class__ raise Valu...
Get the class of a block from a model, using the block's class name.
get_block_class_from_model
python
eric-mitchell/direct-preference-optimization
utils.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/utils.py
Apache-2.0
def __init__(self, seed): """Temporarily set the random seed, and then restore it when exiting the context.""" self.seed = seed self.stored_state = None self.stored_np_state = None
Temporarily set the random seed, and then restore it when exiting the context.
__init__
python
eric-mitchell/direct-preference-optimization
utils.py
https://github.com/eric-mitchell/direct-preference-optimization/blob/master/utils.py
Apache-2.0
def __init__(self, node: Node, text_buf: bytes, override_nodes: list["DTNode"] | None = None): """ Initialize a node from its name (which may be in the form of `label:name`) and `parse` which contains the node itself. """ self.node = node self.text_buf = text_buf ...
Initialize a node from its name (which may be in the form of `label:name`) and `parse` which contains the node itself.
__init__
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def get_string(self, property_re: str) -> str | None: """Extract last defined value for a `string` type property matching the `property_re` regex.""" if (nodes := self._get_property(property_re)) is None: return None return self._get_content(nodes[0]).strip('"')
Extract last defined value for a `string` type property matching the `property_re` regex.
get_string
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def get_array(self, property_re: str) -> list[str] | None: """Extract last defined values for a `array` type property matching the `property_re` regex.""" if (nodes := self._get_property(property_re)) is None: return None return list( chain.from_iterable( ...
Extract last defined values for a `array` type property matching the `property_re` regex.
get_array
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def get_phandle_array(self, property_re: str) -> list[str] | None: """Extract last defined values for a `phandle-array` type property matching the `property_re` regex.""" if array_vals := self.get_array(property_re): return [ f"&{stripped}" for binding in " "....
Extract last defined values for a `phandle-array` type property matching the `property_re` regex.
get_phandle_array
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def get_path(self, property_re: str) -> str | None: """ Extract last defined value for a `path` type property matching the `property_re` regex. Only supports phandle paths `&p` rather than path types `"/a/b"` right now. """ if (nodes := self._get_property(property_re)) is None: ...
Extract last defined value for a `path` type property matching the `property_re` regex. Only supports phandle paths `&p` rather than path types `"/a/b"` right now.
get_path
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def __init__( self, in_str: str, file_name: str | None = None, preprocess: bool = True, preamble: str | None = None, additional_includes: list[str] | None = None, ): """ Given an input DTS string `in_str` and `file_name` it is read from, parse it to be...
Given an input DTS string `in_str` and `file_name` it is read from, parse it to be able to get `compatible` and `chosen` nodes. For performance reasons, the whole tree isn't parsed into DTNode's. If `preamble` is set to a non-empty string, prepend it to the read buffer.
__init__
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def get_compatible_nodes(self, compatible_value: str) -> list[DTNode]: """Return a list of nodes that have the given compatible value.""" query = TS_LANG.query( rf""" (node (property name: (identifier) @prop value: (string_literal) @propval) (#eq? @pro...
Return a list of nodes that have the given compatible value.
get_compatible_nodes
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def get_chosen_property(self, property_name: str) -> str | None: """Return phandle for a given property in the /chosen node.""" phandle = None for node in self.chosen_nodes: if (val := node.get_path(re.escape(property_name))) is not None: phandle = val return ...
Return phandle for a given property in the /chosen node.
get_chosen_property
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def preprocess_extra_data(self, data: str) -> str: """ Given a string containing data, preprocess it in the same context as the original input buffer by appending the data to it and extracting the result afterwards. TODO(perf): Figure out a good interface to achieve this without...
Given a string containing data, preprocess it in the same context as the original input buffer by appending the data to it and extracting the result afterwards. TODO(perf): Figure out a good interface to achieve this without running preprocessing twice.
preprocess_extra_data
python
caksoylar/keymap-drawer
keymap_drawer/dts.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/dts.py
MIT
def from_key_spec(cls, key_spec: dict | str | int | None) -> "LayoutKey": """Derive full params from a string/int (for tap), a full spec or null (empty key).""" match key_spec: case dict(): return cls(**key_spec) case str(): return cls(tap=key_spec...
Derive full params from a string/int (for tap), a full spec or null (empty key).
from_key_spec
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def serialize_model(self) -> str | dict[str, str]: """Custom serializer to output string-only for simple legends.""" if self.hold or self.shifted or self.left or self.right or self.type: return { k: v for k, v in ( ("t", self.tap), ...
Custom serializer to output string-only for simple legends.
serialize_model
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def apply_formatter(self, formatter: Callable[[str], str]) -> None: """Add a formatter function (str -> str) to all non-empty fields.""" if self.tap: self.tap = formatter(self.tap) if self.hold: self.hold = formatter(self.hold) if self.shifted: self.sh...
Add a formatter function (str -> str) to all non-empty fields.
apply_formatter
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def normalize_fields(cls, spec_dict: dict) -> dict: """Normalize spec_dict so that each field uses its alias and key is parsed to LayoutKey.""" for name, field in cls.model_fields.items(): if name in spec_dict: spec_dict[field.alias or name] = spec_dict.pop(name) if k...
Normalize spec_dict so that each field uses its alias and key is parsed to LayoutKey.
normalize_fields
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def validate_trigger_spec(self): """Make sure either positions or trigger keys are specified.""" assert (not self.key_positions and self.trigger_keys) or ( self.key_positions and not self.trigger_keys ), "Need to specify exactly one of `key_positions` or `trigger_keys` for combo" ...
Make sure either positions or trigger keys are specified.
validate_trigger_spec
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def get_combos_per_layer(self, layers: Iterable[str] | None = None) -> dict[str, list[ComboSpec]]: """Return a mapping of layer names to combos that are present on that layer, if they aren't drawn separately.""" assert self.config is not None if layers is None: layers = self.layers ...
Return a mapping of layer names to combos that are present on that layer, if they aren't drawn separately.
get_combos_per_layer
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def get_separate_combos(self) -> list[ComboSpec]: """Return a list of combos that are meant to be drawn separately.""" assert self.config is not None return [ combo for combo in self.combos if combo.draw_separate or (combo.draw_separate is None and self.config...
Return a list of combos that are meant to be drawn separately.
get_separate_combos
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def dump(self, num_cols: int = 0) -> dict: """Returns a dict-valued dump of the keymap representation.""" dump = self.model_dump(exclude_defaults=True, exclude_unset=True, by_alias=True) if num_cols > 0: dump["layers"] = { name: [layer_keys[i : i + num_cols] for i in ...
Returns a dict-valued dump of the keymap representation.
dump
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def rebase(self, base: "KeymapData") -> None: """ Rebase a keymap on a "base" one: This mostly preserves the fields with the fields from the keymap, however for layers and combos it inherits fields from base that are not specified in the new keymap. For example this can be used to take a...
Rebase a keymap on a "base" one: This mostly preserves the fields with the fields from the keymap, however for layers and combos it inherits fields from base that are not specified in the new keymap. For example this can be used to take an old keymap and update with a new parse output, ...
rebase
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def parse_layers(cls, val) -> dict[str, list[LayoutKey]]: """Parse each key on layer from its key spec, flattening the spec if it contains sublists.""" return { layer_name: [ val if isinstance(val, LayoutKey) else LayoutKey.from_key_spec(val) for val in chain....
Parse each key on layer from its key spec, flattening the spec if it contains sublists.
parse_layers
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def create_layout(cls, vals): """Create layout with type given by layout param.""" if vals["layout"] is None: # ignore for no-layout mode return vals if isinstance(vals["layout"], PhysicalLayout): # already provided a valid object return vals vals["layout"] = Ph...
Create layout with type given by layout param.
create_layout
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def check_combos(self): """Resolve trigger keys if specified then validate combo positions are legitimate ones we can draw.""" for combo in self.combos: if combo.trigger_keys: self._resolve_key_positions_from_trigger_keys(combo) assert self.layout is None or all(...
Resolve trigger keys if specified then validate combo positions are legitimate ones we can draw.
check_combos
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def check_dimensions(self): """Validate that physical layout and layers have the same number of keys.""" if self.layout is None: # only check self-consistency for no-layout mode if len(set(len(layer) for layer in self.layers.values())) > 1: counts = {layer_name: len(layer) f...
Validate that physical layout and layers have the same number of keys.
check_dimensions
python
caksoylar/keymap-drawer
keymap_drawer/keymap.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/keymap.py
MIT
def from_qmk_spec( cls, scale: float, pos: Point, width: float, height: float, rotation: float, rotation_pos: Point ) -> "PhysicalKey": """ Create a PhysicalKey from QMK-format key definition. `pos` is the top left corner coordinates, `rotation_pos` is the coordinates around which th...
Create a PhysicalKey from QMK-format key definition. `pos` is the top left corner coordinates, `rotation_pos` is the coordinates around which the rectangle is rotated. `scale` maps from `1u` dimensions to pixel dimensions. During construction of PhysicalKey, uses `rotation_pos` to re-ad...
from_qmk_spec
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def normalize(self) -> "PhysicalLayout": """Normalize the layout so that the keys are all in (0, 0) to (width, height) coordinates.""" min_pt = Point( min(k.pos.x - k.bounding_width / 2 for k in self.keys), min(k.pos.y - k.bounding_height / 2 for k in self.keys), ) ...
Normalize the layout so that the keys are all in (0, 0) to (width, height) coordinates.
normalize
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def handle_file_overrides(self): """Allow certain spec combinations where one overrides the other.""" if self.qmk_info_json and self.qmk_keyboard: logger.warning("qmk_info_json is overriding qmk_keyboard specification") self.qmk_keyboard = None if self.dts_layout and self...
Allow certain spec combinations where one overrides the other.
handle_file_overrides
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def check_specs(self): """Check that exactly one layout type is specified.""" if ( sum( spec is not None for spec in ( self.qmk_keyboard, self.zmk_keyboard, self.zmk_shared_layout, ...
Check that exactly one layout type is specified.
check_specs
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def handle_qmk_layout(self): """Check and set the layout name to account for deprecated qmk_layout field.""" if self.qmk_layout is not None: logger.warning('"qmk_layout" is deprecated, please use "layout_name" instead') assert self.layout_name is None, '"qmk_layout" cannot be use...
Check and set the layout name to account for deprecated qmk_layout field.
handle_qmk_layout
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def generate(self) -> PhysicalLayout: """Generate a physical layout given config and layout specs.""" draw_cfg, parse_cfg = self.config.draw_config, self.config.parse_config if self.qmk_keyboard or self.qmk_info_json: if self.qmk_keyboard: qmk_info = _get_qmk_info(se...
Generate a physical layout given config and layout specs.
generate
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def check_thumbs(self): """Check that the number of thumb keys is specified correctly.""" if self.thumbs: if isinstance(self.thumbs, int): assert self.thumbs <= self.columns, "Number of thumbs should not be greater than columns" assert self.split, "Cannot proc...
Check that the number of thumb keys is specified correctly.
check_thumbs
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def check_drops(self): """Check that drop_pinky or drop_index are only used with split layouts.""" if self.drop_pinky or self.drop_inner: assert self.split, '"drop_*" properties can only be used with split layouts' return self
Check that drop_pinky or drop_index are only used with split layouts.
check_drops
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def generate(self, key_w: float, key_h: float, split_gap: float) -> PhysicalLayout: """Generate a list of PhysicalKeys from given ortho specifications.""" logger.debug("generating OrthoLayout-based physical layout for spec %s", self.model_dump()) nrows = self.rows if not isinstance(self...
Generate a list of PhysicalKeys from given ortho specifications.
generate
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def spec_validator(cls, val: str) -> str: """Split spec string by spaces or underscores then validate each part.""" assert all( cls.part_pattern.match(part) for part in cls._split_spec(val) ), "Cols+thumbs `spec` value does not match the expected syntax, please double check" ...
Split spec string by spaces or underscores then validate each part.
spec_validator
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def generate(self, key_w: float, key_h: float, split_gap: float) -> PhysicalLayout: """Generate a list of PhysicalKeys from given CPT specification.""" logger.debug("generating CPT-based physical layout for spec %s", self.spec) parts = [match.groupdict() for part in self._split_spec(self.spec) ...
Generate a list of PhysicalKeys from given CPT specification.
generate
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def generate(self, layout_name: str | None, key_size: float) -> PhysicalLayout: """Generate a sequence of PhysicalKeys from QmkKeys.""" logger.debug("generating QMK-based physical layout for layout name %s", layout_name) assert self.layouts, "QmkLayout.layouts cannot be empty" if layout_...
Generate a sequence of PhysicalKeys from QmkKeys.
generate
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def _get_qmk_info(qmk_keyboard: str, use_local_cache: bool = False) -> dict: """ Get a QMK info.json file from either self-maintained folder of layouts, local file cache if enabled, or from QMK keyboards metadata API. """ qmk_keyboard = _map_qmk_keyboard(qmk_keyboard) local_path = QMK_LAYOUTS_PA...
Get a QMK info.json file from either self-maintained folder of layouts, local file cache if enabled, or from QMK keyboards metadata API.
_get_qmk_info
python
caksoylar/keymap-drawer
keymap_drawer/physical_layout.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/physical_layout.py
MIT
def draw(args: Namespace, config: Config) -> None: """Draw the keymap in SVG format to stdout.""" yaml_data: dict[str, dict] = {} for yaml_arg in args.keymap_yaml: yaml_data = _merge_keymaps(yaml_data, yaml.safe_load(yaml_arg)) cli_layout = { k: v for k, v in ( ("qmk...
Draw the keymap in SVG format to stdout.
draw
python
caksoylar/keymap-drawer
keymap_drawer/__main__.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/__main__.py
MIT
def parse(args: Namespace, config: Config) -> None: """Call the appropriate parser for given args and dump YAML keymap representation to stdout.""" if args.base_keymap: yaml_data = yaml.safe_load(args.base_keymap) base = KeymapData( layers=yaml_data.get("layers", {}), combos=yaml_dat...
Call the appropriate parser for given args and dump YAML keymap representation to stdout.
parse
python
caksoylar/keymap-drawer
keymap_drawer/__main__.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/__main__.py
MIT
def dump_config(args: Namespace, config: Config) -> None: """Dump the currently active config, either default or parsed from args.""" def cfg_str_representer(dumper, in_str): if "\n" in in_str: # use '|' style for multiline strings return dumper.represent_scalar("tag:yaml.org,2002:str", in...
Dump the currently active config, either default or parsed from args.
dump_config
python
caksoylar/keymap-drawer
keymap_drawer/__main__.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/__main__.py
MIT
def main() -> None: """Parse the configuration and print SVG using KeymapDrawer.""" parser = ArgumentParser(description=__doc__) parser.add_argument("-v", "--version", action="version", version=version("keymap-drawer")) parser.add_argument("-d", "--debug", action="store_true") parser.add_argument( ...
Parse the configuration and print SVG using KeymapDrawer.
main
python
caksoylar/keymap-drawer
keymap_drawer/__main__.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/__main__.py
MIT
def print_combo(self, combo: ComboSpec, combo_ind: int) -> tuple[Point, Point]: # pylint: disable=too-many-locals """ Print SVG code for a rectangle with text representing a combo specification, which contains the key positions that trigger it and what it does when triggered. The position of th...
Print SVG code for a rectangle with text representing a combo specification, which contains the key positions that trigger it and what it does when triggered. The position of the rectangle depends on the alignment specified, along with whether dendrons are drawn going to each key position from ...
print_combo
python
caksoylar/keymap-drawer
keymap_drawer/draw/combo.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/combo.py
MIT
def print_combos_for_layer(self, combos: Sequence[ComboSpec]) -> tuple[float | None, float | None]: """ Print SVG for all given combos, relative to that point. Return min and max y-coordinates of combo boxes, for bounding box calculations. """ combo_pts = [self.print_combo(combo,...
Print SVG for all given combos, relative to that point. Return min and max y-coordinates of combo boxes, for bounding box calculations.
print_combos_for_layer
python
caksoylar/keymap-drawer
keymap_drawer/draw/combo.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/combo.py
MIT
def create_combo_diagrams( self, scale_factor: int, ghost_keys: Sequence[int] | None = None ) -> tuple[PhysicalLayout | None, dict[str, list[LayoutKey]]]: """ Create and return both a shrunk down physical layout and layers representing combo locations with held key highlighting. ...
Create and return both a shrunk down physical layout and layers representing combo locations with held key highlighting.
create_combo_diagrams
python
caksoylar/keymap-drawer
keymap_drawer/draw/combo.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/combo.py
MIT
def print_layer_header(self, p: Point, header: str) -> None: """Print a layer header that precedes the layer visualization.""" text = header + ":" if self.cfg.append_colon_to_layer_header else header self.out.write( f'<text x="{round(p.x)}" y="{round(p.y)}" class="label" id="{self._s...
Print a layer header that precedes the layer visualization.
print_layer_header
python
caksoylar/keymap-drawer
keymap_drawer/draw/draw.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/draw.py
MIT
def print_footer(self, p: Point) -> None: """Print a footer with text given by cfg.footer_text, with CSS class `footer` for bottom-right alignment.""" self.output_stream.write( f'<text x="{p.x - self.cfg.outer_pad_w}" y="{p.y - self.cfg.outer_pad_h / 2}" class="footer">' f"{self....
Print a footer with text given by cfg.footer_text, with CSS class `footer` for bottom-right alignment.
print_footer
python
caksoylar/keymap-drawer
keymap_drawer/draw/draw.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/draw.py
MIT
def print_key(self, p_key: PhysicalKey, l_key: LayoutKey, key_ind: int) -> None: """ Print SVG code for a rectangle with text representing the key, which is described by its physical representation (p_key) and what it does in the given layer (l_key). """ p, w, h, r = ( ...
Print SVG code for a rectangle with text representing the key, which is described by its physical representation (p_key) and what it does in the given layer (l_key).
print_key
python
caksoylar/keymap-drawer
keymap_drawer/draw/draw.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/draw.py
MIT
def print_layers( # pylint: disable=too-many-locals self, p: Point, layout: PhysicalLayout, layers: Mapping[str, Sequence[LayoutKey]], combos_per_layer: Mapping[str, Sequence[ComboSpec]], n_cols: int = 1, draw_header: bool = True, pad_divisor: int = 1, ...
Print SVG code for keys for all layers (including combos on them) starting at coordinate p, into n_cols columns and return the bottom right coordinate.
print_layers
python
caksoylar/keymap-drawer
keymap_drawer/draw/draw.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/draw.py
MIT
def print_board( # pylint: disable=too-many-locals self, draw_layers: Sequence[str] | None = None, keys_only: bool = False, combos_only: bool = False, ghost_keys: Sequence[int] | None = None, ) -> None: """Print SVG code representing the keymap.""" # get fina...
Print SVG code representing the keymap.
print_board
python
caksoylar/keymap-drawer
keymap_drawer/draw/draw.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/draw.py
MIT
def init_glyphs(self) -> None: """Preprocess all glyphs in the keymap to get their name to SVG mapping.""" def find_key_glyph_names(key: LayoutKey) -> set[str]: return { glyph for field in (key.tap, key.hold, key.shifted, key.left, key.right) ...
Preprocess all glyphs in the keymap to get their name to SVG mapping.
init_glyphs
python
caksoylar/keymap-drawer
keymap_drawer/draw/glyph.py
https://github.com/caksoylar/keymap-drawer/blob/master/keymap_drawer/draw/glyph.py
MIT