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 get_infix_pretty (self, prog_idx = 0, do_simplify = True): """ Returns a printable ASCII sympy.pretty representation of a program. Parameters ---------- prog_idx : int Index of program in VectPrograms. do_simplify : bool If True performs a symb...
Returns a printable ASCII sympy.pretty representation of a program. Parameters ---------- prog_idx : int Index of program in VectPrograms. do_simplify : bool If True performs a symbolic simplification of program. Returns ------- pr...
get_infix_pretty
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def get_infix_latex (self, prog_idx = 0, replace_dummy_symbol = True, new_dummy_symbol = "?", do_simplify = True): """ Returns an str latex representation of a program. Parameters ---------- prog_idx : int Index of program in VectPrograms. replace_dummy_symbol...
Returns an str latex representation of a program. Parameters ---------- prog_idx : int Index of program in VectPrograms. replace_dummy_symbol : bool If True, dummy symbol is replaced by new_dummy_symbol. new_dummy_symbol : str or None ...
get_infix_latex
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def get_infix_fig (self, prog_idx = 0, replace_dummy_symbol = True, new_dummy_symbol = "?", do_simplify = True, show_superparent_at_beginning = True, text_size = 16, ...
Returns pyplot (figure, axis) containing analytic symbolic function program. Parameters ---------- prog_idx : int Index of program in VectPrograms. replace_dummy_symbol : bool If True, dummy symbol is replaced by new_dummy_symbol. new_dummy_symbol...
get_infix_fig
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def get_infix_image(self, prog_idx = 0, replace_dummy_symbol = True, new_dummy_symbol = "?", do_simplify = True, text_size = 16, text_pos = (0.0, 0.5), ...
Returns image containing analytic symbolic function program. Parameters ---------- prog_idx : int Index of program in VectPrograms. replace_dummy_symbol : bool If True, dummy symbol is replaced by new_dummy_symbol. new_dummy_symbol : str or None ...
get_infix_image
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def show_infix(self, prog_idx=0, replace_dummy_symbol = True, new_dummy_symbol = "?", do_simplify = True, text_size=16, text_pos=(0.0, 0.5), figsize=(10, 2), ): ...
Shows pyplot (figure, axis) containing analytic symbolic function program. Parameters ---------- prog_idx : int Index of program in VectPrograms. replace_dummy_symbol : bool If True, dummy symbol is replaced by new_dummy_symbol. new_dummy_symbol :...
show_infix
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def get_tree_graph (self, prog_idx = 0, n_dim_units = 3, shape = "circle", constraint_color = AGRAPH_BLUE, vanilla_color = AGRAPH_BLACK, dummy_color = AGRAPH_RED, special_color = AGRAPH_RED, special_color_pos = None, edge_c...
Returns a graph representation of a program tree encoding parent, children relationships, physical units and position. Parameters ---------- prog_idx : int Index of program in VectPrograms. shape : str Shape of nodes in graph (passed to pygraphvi...
get_tree_graph
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def get_tree_latex (self, prog_idx = 0, fpath = None, **args_get_tree_graph): """ Returns a latex code of the tree program. Parameters ---------- prog_idx : int Index of program in VectPrograms. fpath : str or None Path where to save latex code. B...
Returns a latex code of the tree program. Parameters ---------- prog_idx : int Index of program in VectPrograms. fpath : str or None Path where to save latex code. By default = None, nothing is saved. args_get_tree_graph : dict Additi...
get_tree_latex
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def get_tree_image (self, prog_idx = 0, fpath = None, **args_get_tree_graph): """ Returns an image of the tree program (less pretty than get_tree_image_via_tex). Parameters ---------- prog_idx : int Index of program in VectPrograms. fpath : str or None ...
Returns an image of the tree program (less pretty than get_tree_image_via_tex). Parameters ---------- prog_idx : int Index of program in VectPrograms. fpath : str or None Path where to save image. By default, = None, nothing is saved. args_get_tr...
get_tree_image
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def get_tree_image_via_tex (self, prog_idx = 0, fname = None, dpi = 300, **args_get_tree_graph): """ Returns an image of the tree program going through latex (prettier than get_tree_image by leveraging features of latex that are not available in AGraph.draw). Exports AGraph -> .tex (via ...
Returns an image of the tree program going through latex (prettier than get_tree_image by leveraging features of latex that are not available in AGraph.draw). Exports AGraph -> .tex (via dot2tex) -> .pdf (via PDFLaTeX) -> image (via pdf2image) Parameters ---------- prog_...
get_tree_image_via_tex
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def show_tree (self, prog_idx = 0, via_tex = False, figsize = (30,30), dpi = 300, **args_get_tree_graph): """ Shows pyplot (figure, axis) containing tree of program. Parameters ---------- prog_idx : int Index of program in VectPrograms. via_tex : bool ...
Shows pyplot (figure, axis) containing tree of program. Parameters ---------- prog_idx : int Index of program in VectPrograms. via_tex : bool If True uses get_tree_image_via_tex (prettier), else uses get_tree_image. figsize : tuple of int ...
show_tree
python
WassimTenachi/PhySO
physo/physym/vect_programs.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/physym/vect_programs.py
MIT
def check_args_and_build_run_config(multi_X, multi_y, multi_y_weights, # X X_names, X_units, # y y_name , y_units, # Fixed constants fixed_consts, fixed_consts_units, # Class free constants ...
Checks arguments of SR and ClassSR functions and builds run_config for physo.task.fit.
check_args_and_build_run_config
python
WassimTenachi/PhySO
physo/task/args_handler.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/task/args_handler.py
MIT
def dummy_epoch_ClassSR (multi_X, multi_y, run_config, multi_y_weights=1.): """ Dummy epoch for class SR task. Plots reward distribution and programs lengths distribution. Parameters ---------- multi_X : list of len (n_realizations,) of np.array of shape (n_dim, ?,) of float List of X (...
Dummy epoch for class SR task. Plots reward distribution and programs lengths distribution. Parameters ---------- multi_X : list of len (n_realizations,) of np.array of shape (n_dim, ?,) of float List of X (one per realization). With X being values of the input variables of the problem wit...
dummy_epoch_ClassSR
python
WassimTenachi/PhySO
physo/task/checks.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py
MIT
def dummy_epoch_SR (X, y, run_config, y_weights = 1.): """ Dummy epoch for SR task. Plots reward distribution and programs lengths distribution. Parameters ---------- X : numpy.array of shape (n_dim, ?,) of float Values of the input variables of the problem with n_dim = nb of input varia...
Dummy epoch for SR task. Plots reward distribution and programs lengths distribution. Parameters ---------- X : numpy.array of shape (n_dim, ?,) of float Values of the input variables of the problem with n_dim = nb of input variables. y : numpy.array of shape (?,) of float Value...
dummy_epoch_SR
python
WassimTenachi/PhySO
physo/task/checks.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py
MIT
def sanity_check_ClassSR (multi_X, multi_y, run_config, multi_y_weights = 1., candidate_wrapper = None, target_program_str = None, expected_ideal_reward = 1.): """ Checks if finding the target program would give the expected ideal reward. Parameters ---------- multi_X : list of len (n_realizations,)...
Checks if finding the target program would give the expected ideal reward. Parameters ---------- multi_X : list of len (n_realizations,) of np.array of shape (n_dim, ?,) of float List of X (one per realization). With X being values of the input variables of the problem with n_dim = nb o...
sanity_check_ClassSR
python
WassimTenachi/PhySO
physo/task/checks.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py
MIT
def sanity_check_SR (X, y, run_config, y_weights = 1., candidate_wrapper = None, target_program_str = None, expected_ideal_reward = 1.): """ Checks if finding the target program would give the expected ideal reward. Parameters ---------- X : numpy.array of shape (n_dim, ?,) of float Values o...
Checks if finding the target program would give the expected ideal reward. Parameters ---------- X : numpy.array of shape (n_dim, ?,) of float Values of the input variables of the problem with n_dim = nb of input variables. y : numpy.array of shape (?,) of float Values of the target...
sanity_check_SR
python
WassimTenachi/PhySO
physo/task/checks.py
https://github.com/WassimTenachi/PhySO/blob/master/physo/task/checks.py
MIT
def on_train_begin(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): r""" Event called at the beginning of training. """ if state.is_local_process_zero: self.in_training = True self.start_time = time.time() s...
Event called at the beginning of training.
on_train_begin
python
WangRongsheng/CareGPT
src/llmtuner/extras/callbacks.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py
MIT
def on_train_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): r""" Event called at the end of training. """ if state.is_local_process_zero: self.in_training = False self.cur_steps = 0 self.max_steps = 0
Event called at the end of training.
on_train_end
python
WangRongsheng/CareGPT
src/llmtuner/extras/callbacks.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py
MIT
def on_substep_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): r""" Event called at the end of an substep during gradient accumulation. """ if state.is_local_process_zero and self.runner is not None and self.runner.aborted: co...
Event called at the end of an substep during gradient accumulation.
on_substep_end
python
WangRongsheng/CareGPT
src/llmtuner/extras/callbacks.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py
MIT
def on_step_end(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): r""" Event called at the end of a training step. """ if state.is_local_process_zero: self.cur_steps = state.global_step self.timing() if self....
Event called at the end of a training step.
on_step_end
python
WangRongsheng/CareGPT
src/llmtuner/extras/callbacks.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py
MIT
def on_evaluate(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): r""" Event called after an evaluation phase. """ if state.is_local_process_zero and not self.in_training: self.cur_steps = 0 self.max_steps = 0
Event called after an evaluation phase.
on_evaluate
python
WangRongsheng/CareGPT
src/llmtuner/extras/callbacks.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py
MIT
def on_log(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs) -> None: r""" Event called after logging the last logs. """ if not state.is_local_process_zero: return logs = dict( current_steps=self.cur_steps, ...
Event called after logging the last logs.
on_log
python
WangRongsheng/CareGPT
src/llmtuner/extras/callbacks.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/callbacks.py
MIT
def reset_logging(): r""" Removes basic config of root logger """ root = logging.getLogger() list(map(root.removeHandler, root.handlers)) list(map(root.removeFilter, root.filters))
Removes basic config of root logger
reset_logging
python
WangRongsheng/CareGPT
src/llmtuner/extras/logging.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/logging.py
MIT
def count_parameters(model: torch.nn.Module) -> Tuple[int, int]: r""" Returns the number of trainable parameters and number of all parameters in the model. """ trainable_params, all_param = 0, 0 for param in model.parameters(): num_params = param.numel() # if using DS Zero 3 and the ...
Returns the number of trainable parameters and number of all parameters in the model.
count_parameters
python
WangRongsheng/CareGPT
src/llmtuner/extras/misc.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/misc.py
MIT
def dispatch_model(model: "PreTrainedModel") -> "PreTrainedModel": r""" Dispatches a pre-trained model to GPUs with balanced memory. Borrowed from: https://github.com/huggingface/transformers/blob/v4.31.0/src/transformers/modeling_utils.py#L2803 """ if getattr(model, "is_loaded_in_8bit", False) or g...
Dispatches a pre-trained model to GPUs with balanced memory. Borrowed from: https://github.com/huggingface/transformers/blob/v4.31.0/src/transformers/modeling_utils.py#L2803
dispatch_model
python
WangRongsheng/CareGPT
src/llmtuner/extras/misc.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/misc.py
MIT
def encode_oneturn( self, tokenizer: "PreTrainedTokenizer", query: str, resp: str, history: Optional[List[Tuple[str, str]]] = None, system: Optional[str] = None ) -> Tuple[List[int], List[int]]: r""" Returns a single pair of token ids representing prom...
Returns a single pair of token ids representing prompt and response respectively.
encode_oneturn
python
WangRongsheng/CareGPT
src/llmtuner/extras/template.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py
MIT
def encode_multiturn( self, tokenizer: "PreTrainedTokenizer", query: str, resp: str, history: Optional[List[Tuple[str, str]]] = None, system: Optional[str] = None ) -> List[Tuple[List[int], List[int]]]: r""" Returns multiple pairs of token ids represen...
Returns multiple pairs of token ids representing prompts and responses respectively.
encode_multiturn
python
WangRongsheng/CareGPT
src/llmtuner/extras/template.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py
MIT
def _format( self, query: str, resp: str, history: Optional[List[Tuple[str, str]]] = None, system: Optional[str] = None ) -> Tuple[str, List[Tuple[str, str]]]: r""" Aligns inputs to the standard format. """ system = system or self.system # use ...
Aligns inputs to the standard format.
_format
python
WangRongsheng/CareGPT
src/llmtuner/extras/template.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py
MIT
def _encode( self, tokenizer: "PreTrainedTokenizer", system: str, history: List[Tuple[str, str]] ) -> List[Tuple[List[int], List[int]]]: r""" Encodes formatted inputs to pairs of token ids. Turn 0: bos + prefix + sep + query resp + eos Turn t: sep +...
Encodes formatted inputs to pairs of token ids. Turn 0: bos + prefix + sep + query resp + eos Turn t: sep + bos + query resp + eos
_encode
python
WangRongsheng/CareGPT
src/llmtuner/extras/template.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py
MIT
def _encode( self, tokenizer: "PreTrainedTokenizer", system: str, history: List[Tuple[str, str]] ) -> List[Tuple[List[int], List[int]]]: r""" Encodes formatted inputs to pairs of token ids. Turn 0: bos + prefix + query resp + eos Turn t: bos + query...
Encodes formatted inputs to pairs of token ids. Turn 0: bos + prefix + query resp + eos Turn t: bos + query resp + eos
_encode
python
WangRongsheng/CareGPT
src/llmtuner/extras/template.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/extras/template.py
MIT
def save_to_json(self, json_path: str): r"""Saves the content of this instance in JSON format inside `json_path`.""" json_string = json.dumps(asdict(self), indent=2, sort_keys=True) + "\n" with open(json_path, "w", encoding="utf-8") as f: f.write(json_string)
Saves the content of this instance in JSON format inside `json_path`.
save_to_json
python
WangRongsheng/CareGPT
src/llmtuner/hparams/finetuning_args.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/hparams/finetuning_args.py
MIT
def load_from_json(cls, json_path: str): r"""Creates an instance from the content of `json_path`.""" with open(json_path, "r", encoding="utf-8") as f: text = f.read() return cls(**json.loads(text))
Creates an instance from the content of `json_path`.
load_from_json
python
WangRongsheng/CareGPT
src/llmtuner/hparams/finetuning_args.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/hparams/finetuning_args.py
MIT
def init_adapter( model: "PreTrainedModel", model_args: "ModelArguments", finetuning_args: "FinetuningArguments", is_trainable: bool, is_mergeable: bool ) -> "PreTrainedModel": r""" Initializes the adapters. Support full-parameter, freeze and LoRA training. Note that the trainable ...
Initializes the adapters. Support full-parameter, freeze and LoRA training. Note that the trainable parameters must be cast to float32.
init_adapter
python
WangRongsheng/CareGPT
src/llmtuner/tuner/core/adapter.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/adapter.py
MIT
def load_model_and_tokenizer( model_args: "ModelArguments", finetuning_args: "FinetuningArguments", is_trainable: Optional[bool] = False, stage: Optional[Literal["pt", "sft", "rm", "ppo"]] = "sft" ) -> Tuple[PreTrainedModel, "PreTrainedTokenizer"]: r""" Loads pretrained model and tokenizer. ...
Loads pretrained model and tokenizer. Support both training and inference.
load_model_and_tokenizer
python
WangRongsheng/CareGPT
src/llmtuner/tuner/core/loader.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/loader.py
MIT
def _save(self, output_dir: Optional[str] = None, state_dict: Optional[Dict[str, torch.Tensor]] = None) -> None: r""" Saves trainable parameters as model checkpoint. This function will only be executed at the process zero. Subclass and override to inject custom behavior. It should not ...
Saves trainable parameters as model checkpoint. This function will only be executed at the process zero. Subclass and override to inject custom behavior. It should not be directly used by external scripts.
_save
python
WangRongsheng/CareGPT
src/llmtuner/tuner/core/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/trainer.py
MIT
def _load_best_model(self): r""" Loads trainable parameters from model checkpoint. Subclass and override to inject custom behavior. It should not be directly used by external scripts. """ logger.info(f"Loading best model from {self.state.best_model_checkpoint} (score: {self.stat...
Loads trainable parameters from model checkpoint. Subclass and override to inject custom behavior. It should not be directly used by external scripts.
_load_best_model
python
WangRongsheng/CareGPT
src/llmtuner/tuner/core/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/core/trainer.py
MIT
def __call__(self, features: Sequence[Dict[str, Any]]) -> Dict[str, torch.Tensor]: r""" Pads batched data to the longest sequence in the batch. We generate 2 * n examples where the first n examples represent chosen examples and the last n examples represent rejected examples. ""...
Pads batched data to the longest sequence in the batch. We generate 2 * n examples where the first n examples represent chosen examples and the last n examples represent rejected examples.
__call__
python
WangRongsheng/CareGPT
src/llmtuner/tuner/dpo/collator.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/dpo/collator.py
MIT
def ppo_train(self, max_target_length: int) -> None: r""" Implements training loop for the PPO stage, like _inner_training_loop() in Huggingface's Trainer. """ total_train_batch_size = ( self.args.per_device_train_batch_size * self.args.gradient_accumulation_steps * self.args...
Implements training loop for the PPO stage, like _inner_training_loop() in Huggingface's Trainer.
ppo_train
python
WangRongsheng/CareGPT
src/llmtuner/tuner/ppo/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/ppo/trainer.py
MIT
def get_rewards( self, queries: List[torch.Tensor], responses: List[torch.Tensor], unwrapped_model: "AutoModelForCausalLMWithValueHead" ) -> List[torch.Tensor]: r""" Computes scores using given reward model. """ replace_model(unwrapped_model, target="r...
Computes scores using given reward model.
get_rewards
python
WangRongsheng/CareGPT
src/llmtuner/tuner/ppo/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/ppo/trainer.py
MIT
def batched_forward_pass( self, model: "AutoModelForCausalLMWithValueHead", queries: torch.Tensor, responses: torch.Tensor, model_inputs: dict, return_logits: Optional[bool] = False ): r""" Calculates model outputs in multiple batches. Subclas...
Calculates model outputs in multiple batches. Subclass and override to inject custom behavior.
batched_forward_pass
python
WangRongsheng/CareGPT
src/llmtuner/tuner/ppo/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/ppo/trainer.py
MIT
def compute_loss( self, model: "PreTrainedModel", inputs: Dict[str, torch.Tensor], return_outputs: Optional[bool] = False ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]: r""" Computes pairwise loss. The first n examples are chosen and the last n exa...
Computes pairwise loss. The first n examples are chosen and the last n examples are rejected. We use score on the EOS token to represent reward of the whole sentence. Subclass and override to inject custom behavior. It should not be directly used by external scripts. Note that the fi...
compute_loss
python
WangRongsheng/CareGPT
src/llmtuner/tuner/rm/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/rm/trainer.py
MIT
def save_predictions( self, predict_results: "PredictionOutput" ) -> None: r""" Saves model predictions to `output_dir`. A custom behavior that not contained in Seq2SeqTrainer. """ if not self.is_world_process_zero(): return output_predic...
Saves model predictions to `output_dir`. A custom behavior that not contained in Seq2SeqTrainer.
save_predictions
python
WangRongsheng/CareGPT
src/llmtuner/tuner/rm/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/rm/trainer.py
MIT
def __call__(self, eval_preds: Sequence[Union[np.ndarray, Tuple[np.ndarray]]]) -> Dict[str, float]: r""" Uses the model predictions to compute metrics. """ preds, labels = eval_preds score_dict = {"rouge-1": [], "rouge-2": [], "rouge-l": [], "bleu-4": []} preds = np.wher...
Uses the model predictions to compute metrics.
__call__
python
WangRongsheng/CareGPT
src/llmtuner/tuner/sft/metric.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/sft/metric.py
MIT
def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: r""" Removes the prompt ...
Removes the prompt part in the generated tokens. Subclass and override to inject custom behavior.
prediction_step
python
WangRongsheng/CareGPT
src/llmtuner/tuner/sft/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/sft/trainer.py
MIT
def _pad_tensors_to_target_len( self, src_tensor: torch.Tensor, tgt_tensor: torch.Tensor, pad_token_id: Optional[int] = None ) -> torch.Tensor: r""" Pads the tensor to the same length as the target tensor. Should only be called when predict_with_generate=True...
Pads the tensor to the same length as the target tensor. Should only be called when predict_with_generate=True.
_pad_tensors_to_target_len
python
WangRongsheng/CareGPT
src/llmtuner/tuner/sft/trainer.py
https://github.com/WangRongsheng/CareGPT/blob/master/src/llmtuner/tuner/sft/trainer.py
MIT
def __init__(self, enum_obj: t.Any) -> None: """Initialize attributes for informative output. :param enum_obj: Enum object. """ if enum_obj: self.name = enum_obj self.items = ", ".join(map(str, enum_obj)) else: self.items = ""
Initialize attributes for informative output. :param enum_obj: Enum object.
__init__
python
lk-geimfari/mimesis
mimesis/exceptions.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/exceptions.py
MIT
def romanize(locale: Locale) -> Callable[[str], str]: """Create a closure function to romanize a given string in the specified locale. Supported locales are: - Locale.RU (Russian) - Locale.UK (Ukrainian) - Locale.KK (Kazakh) :param locale: Locale. :return: A closure that takes a string an...
Create a closure function to romanize a given string in the specified locale. Supported locales are: - Locale.RU (Russian) - Locale.UK (Ukrainian) - Locale.KK (Kazakh) :param locale: Locale. :return: A closure that takes a string and returns a romanized string.
romanize
python
lk-geimfari/mimesis
mimesis/keys.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/keys.py
MIT
def maybe(value: Any, probability: float = 0.5) -> Callable[[Any, Random], Any]: """Return a closure (a key function). The returned closure itself returns either **value** or the first argument passed to closure with a certain probability (0.5 by default). :param value: The value that may be returned....
Return a closure (a key function). The returned closure itself returns either **value** or the first argument passed to closure with a certain probability (0.5 by default). :param value: The value that may be returned. :param probability: The probability of returning **value**. :return: A closure ...
maybe
python
lk-geimfari/mimesis
mimesis/keys.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/keys.py
MIT
def randints(self, n: int = 3, a: int = 1, b: int = 100) -> list[int]: """Generate a list of random integers. :param n: Number of elements. :param a: Minimum value of range. :param b: Maximum value of range. :return: List of random integers. :raises ValueError: if the nu...
Generate a list of random integers. :param n: Number of elements. :param a: Minimum value of range. :param b: Maximum value of range. :return: List of random integers. :raises ValueError: if the number is less or equal to zero.
randints
python
lk-geimfari/mimesis
mimesis/random.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/random.py
MIT
def generate_string_by_mask( self, mask: str = "@###", char: str = "@", digit: str = "#", ) -> str: """Generate custom code using ascii uppercase and random integers. :param mask: Mask of code. :param char: Placeholder for characters. :param digit: Pl...
Generate custom code using ascii uppercase and random integers. :param mask: Mask of code. :param char: Placeholder for characters. :param digit: Placeholder for digits. :return: Custom code.
generate_string_by_mask
python
lk-geimfari/mimesis
mimesis/random.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/random.py
MIT
def weighted_choice(self, choices: dict[t.Any, float]) -> t.Any: """Returns a random element according to the specified weights. :param choices: A dictionary where keys are choices and values are weights. :raises ValueError: If choices are empty. :return: Random key from dictionary. ...
Returns a random element according to the specified weights. :param choices: A dictionary where keys are choices and values are weights. :raises ValueError: If choices are empty. :return: Random key from dictionary.
weighted_choice
python
lk-geimfari/mimesis
mimesis/random.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/random.py
MIT
def __init__( self, locale: Locale = Locale.DEFAULT, seed: Seed = MissingSeed, ) -> None: """Base class for fields. This class is used as a base class for :class:`Field` and :class:`Fieldset`. :attr: aliases: A dictionary of aliases for standard fields. :par...
Base class for fields. This class is used as a base class for :class:`Field` and :class:`Fieldset`. :attr: aliases: A dictionary of aliases for standard fields. :param locale: Locale. :param seed: Seed for random.
__init__
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def _explicit_lookup(self, name: str) -> Any: """An explicit method lookup. This method is called when the field defined explicitly, like this: ``provider.method`` :param name: The field name. :return: Callable object. :raise FieldError: When field is invalid. "...
An explicit method lookup. This method is called when the field defined explicitly, like this: ``provider.method`` :param name: The field name. :return: Callable object. :raise FieldError: When field is invalid.
_explicit_lookup
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def _fuzzy_lookup(self, name: str) -> Any: """A fuzzy method lookup. This method is called when the field definition is fuzzy, like this: ``method`` :param name: The field name. :return: Callable object. :raise FieldError: When field is invalid. """ for ...
A fuzzy method lookup. This method is called when the field definition is fuzzy, like this: ``method`` :param name: The field name. :return: Callable object. :raise FieldError: When field is invalid.
_fuzzy_lookup
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def _lookup_method(self, name: str) -> Any: """Lookup method by the field name. :param name: The field name. :return: Callable object. :raise FieldError: When field is invalid. """ # Check if the field is defined in aliases name = self.aliases.get(name, name) ...
Lookup method by the field name. :param name: The field name. :return: Callable object. :raise FieldError: When field is invalid.
_lookup_method
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def register_handler(self, field_name: str, field_handler: FieldHandler) -> None: """Register a new field handler. :param field_name: Name of the field. :param field_handler: Callable object. """ if not isinstance(field_name, str): raise TypeError("Field name must b...
Register a new field handler. :param field_name: Name of the field. :param field_handler: Callable object.
register_handler
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def handle( self, field_name: str | None = None ) -> Callable[[FieldHandler], FieldHandler]: """Decorator for registering a custom field handler. You can use this decorator only for functions, not for any other callables. .. versionadded:: 12.0.0 :param field_name:...
Decorator for registering a custom field handler. You can use this decorator only for functions, not for any other callables. .. versionadded:: 12.0.0 :param field_name: Name of the field. If not specified, the name of the function is used. :return: Decorator. ...
handle
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def __init__(self, *args: Any, **kwargs: Any) -> None: """Initialize fieldset. Accepts additional keyword argument **i** which is used to specify the number of iterations. The name of the keyword argument can be changed by overriding **fieldset_iterations_kwarg** attribute of t...
Initialize fieldset. Accepts additional keyword argument **i** which is used to specify the number of iterations. The name of the keyword argument can be changed by overriding **fieldset_iterations_kwarg** attribute of this class.
__init__
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def __call__(self, *args: Any, **kwargs: Any) -> list[Any]: """Perform fieldset. :param args: Arguments for field. :param kwargs: Keyword arguments for field. :raises FieldsetError: If parameter **i** is less than 1. :return: List of values. """ min_iterations = ...
Perform fieldset. :param args: Arguments for field. :param kwargs: Keyword arguments for field. :raises FieldsetError: If parameter **i** is less than 1. :return: List of values.
__call__
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def __init__(self, schema: CallableSchema, iterations: int = 10) -> None: """Initialize schema. :param iterations: Number of iterations. This parameter is keyword-only. The default value is 10. :param schema: A schema (must be a callable object). """ if iterations < ...
Initialize schema. :param iterations: Number of iterations. This parameter is keyword-only. The default value is 10. :param schema: A schema (must be a callable object).
__init__
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def to_csv(self, file_path: str, **kwargs: Any) -> None: """Export a schema as a CSV file. :param file_path: The file path. :param kwargs: The keyword arguments for :py:class:`csv.DictWriter` class. """ data = self.create() with open(file_path, "w", encoding="utf-8", new...
Export a schema as a CSV file. :param file_path: The file path. :param kwargs: The keyword arguments for :py:class:`csv.DictWriter` class.
to_csv
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def to_json(self, file_path: str, **kwargs: Any) -> None: """Export a schema as a JSON file. :param file_path: File a path. :param kwargs: Extra keyword arguments for :py:func:`json.dump` class. """ with open(file_path, "w", encoding="utf-8") as fp: json.dump(self.cr...
Export a schema as a JSON file. :param file_path: File a path. :param kwargs: Extra keyword arguments for :py:func:`json.dump` class.
to_json
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def to_pickle(self, file_path: str, **kwargs: Any) -> None: """Export a schema as the pickled representation of the object to the file. :param file_path: The file path. :param kwargs: Extra keyword arguments for :py:func:`pickle.dump` class. """ with open(file_path, "wb") as fp:...
Export a schema as the pickled representation of the object to the file. :param file_path: The file path. :param kwargs: Extra keyword arguments for :py:func:`pickle.dump` class.
to_pickle
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def __next__(self) -> JSON: """Return the next item from the iterator.""" if self.__counter < self.iterations: self.__counter += 1 return self.__schema() raise StopIteration
Return the next item from the iterator.
__next__
python
lk-geimfari/mimesis
mimesis/schema.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/schema.py
MIT
def luhn_checksum(num: str) -> str: """Calculate a checksum for num using the Luhn algorithm. Used to validate credit card numbers, IMEI numbers, and other identification numbers. :param num: The number to calculate a checksum for as a string. :return: Checksum for number. """ check = 0 ...
Calculate a checksum for num using the Luhn algorithm. Used to validate credit card numbers, IMEI numbers, and other identification numbers. :param num: The number to calculate a checksum for as a string. :return: Checksum for number.
luhn_checksum
python
lk-geimfari/mimesis
mimesis/shortcuts.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/shortcuts.py
MIT
def _calculate_checksum(self, cpr_nr_no_checksum: str) -> int: """Calculate the CPR number checksum. The CPR checksum can be checked by: 1. Multiplying each digit in the CPR number with a corresponding fixed factor (self._checksum_factors) to produce a list of products. 2. Su...
Calculate the CPR number checksum. The CPR checksum can be checked by: 1. Multiplying each digit in the CPR number with a corresponding fixed factor (self._checksum_factors) to produce a list of products. 2. Summing up all the products, including the checksum, and checking ...
_calculate_checksum
python
lk-geimfari/mimesis
mimesis/builtins/da.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/da.py
MIT
def _generate_serial_checksum(self, cpr_century: str) -> tuple[str, int]: """Generate a serial number and checksum from cpr_century.""" serial_number = f"{self.random.randint(0, 99):02d}" cpr_nr_no_checksum = f"{cpr_century}{serial_number}" checksum = self._calculate_checksum(cpr_nr_no_...
Generate a serial number and checksum from cpr_century.
_generate_serial_checksum
python
lk-geimfari/mimesis
mimesis/builtins/da.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/da.py
MIT
def cpr(self) -> str: """Generate a random CPR number (Central Person Registry). :return: CPR number. :Example: 0405420694 """ date = self._datetime.date(start=1858, end=2021) cpr_date = f"{date:%d%m%y}" century_selector = self._calculate_century_sel...
Generate a random CPR number (Central Person Registry). :return: CPR number. :Example: 0405420694
cpr
python
lk-geimfari/mimesis
mimesis/builtins/da.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/da.py
MIT
def tracking_number(self, service: str = "usps") -> str: """Generate random tracking number. Supported services: USPS, FedEx and UPS. :param str service: Post service. :return: Tracking number. """ service = service.lower() if service not in ("usps", "fedex", "...
Generate random tracking number. Supported services: USPS, FedEx and UPS. :param str service: Post service. :return: Tracking number.
tracking_number
python
lk-geimfari/mimesis
mimesis/builtins/en.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/en.py
MIT
def ssn(self) -> str: """Generate a random, but valid SSN. :returns: SSN. :Example: 569-66-5801 """ area = self.random.randint(1, 899) if area == 666: area = 665 return "{:03}-{:02}-{:04}".format( area, self.rando...
Generate a random, but valid SSN. :returns: SSN. :Example: 569-66-5801
ssn
python
lk-geimfari/mimesis
mimesis/builtins/en.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/en.py
MIT
def fiscal_code(self, gender: Gender | None = None) -> str: """Return a random fiscal code. :param gender: Gender's enum object. :return: Fiscal code. Example: RSSMRA66R05D612U """ code = "".join(self.random.choices(string.ascii_uppercase, k=6)) cod...
Return a random fiscal code. :param gender: Gender's enum object. :return: Fiscal code. Example: RSSMRA66R05D612U
fiscal_code
python
lk-geimfari/mimesis
mimesis/builtins/it.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/it.py
MIT
def bsn(self) -> str: """Generate a random, but valid ``Burgerservicenummer``. :returns: Random BSN. :Example: 255159705 """ def _is_valid_bsn(number: str) -> bool: total = 0 multiplier = 9 for char in number: mu...
Generate a random, but valid ``Burgerservicenummer``. :returns: Random BSN. :Example: 255159705
bsn
python
lk-geimfari/mimesis
mimesis/builtins/nl.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/nl.py
MIT
def nip(self) -> str: """Generate random valid 10-digit NIP. :return: Valid 10-digit NIP """ nip_digits = [int(d) for d in str(self.random.randint(101, 998))] nip_digits += [self.random.randint(0, 9) for _ in range(6)] nip_coefficients = (6, 5, 7, 2, 3, 4, 5, 6, 7) ...
Generate random valid 10-digit NIP. :return: Valid 10-digit NIP
nip
python
lk-geimfari/mimesis
mimesis/builtins/pl.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/pl.py
MIT
def pesel( self, birth_date: DateTime | None = None, gender: Gender | None = None, ) -> str: """Generate random 11-digit PESEL. :param birth_date: Initial birthdate (optional) :param gender: Gender of the person. :return: Valid 11-digit PESEL """ ...
Generate random 11-digit PESEL. :param birth_date: Initial birthdate (optional) :param gender: Gender of the person. :return: Valid 11-digit PESEL
pesel
python
lk-geimfari/mimesis
mimesis/builtins/pl.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/pl.py
MIT
def regon(self) -> str: """Generate random valid 9-digit REGON. :return: Valid 9-digit REGON """ regon_coeffs = (8, 9, 2, 3, 4, 5, 6, 7) regon_digits = [self.random.randint(0, 9) for _ in range(8)] sum_v = sum(nc * nd for nc, nd in zip(regon_coeffs, regon_digits)) ...
Generate random valid 9-digit REGON. :return: Valid 9-digit REGON
regon
python
lk-geimfari/mimesis
mimesis/builtins/pl.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/pl.py
MIT
def __get_verifying_digit_cpf(cpf: list[int], weight: int) -> int: """Calculate the verifying digit for the CPF. :param cpf: List of integers with the CPF. :param weight: Integer with the weight for the modulo 11 calculate. :returns: The verifying digit for the CPF. """ ...
Calculate the verifying digit for the CPF. :param cpf: List of integers with the CPF. :param weight: Integer with the weight for the modulo 11 calculate. :returns: The verifying digit for the CPF.
__get_verifying_digit_cpf
python
lk-geimfari/mimesis
mimesis/builtins/pt_br.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/pt_br.py
MIT
def cpf(self, with_mask: bool = True) -> str: """Get a random CPF. :param with_mask: Use CPF mask (###.###.###-##). :returns: Random CPF. :Example: 001.137.297-40 """ cpf_without_dv = [self.random.randint(0, 9) for _ in range(9)] first_dv = self.__g...
Get a random CPF. :param with_mask: Use CPF mask (###.###.###-##). :returns: Random CPF. :Example: 001.137.297-40
cpf
python
lk-geimfari/mimesis
mimesis/builtins/pt_br.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/pt_br.py
MIT
def __get_verifying_digit_cnpj(cnpj: list[int], weight: int) -> int: """Calculate the verifying digit for the CNPJ. :param cnpj: List of integers with the CNPJ. :param weight: Integer with the weight for the modulo 11 calculate. :returns: The verifying digit for the CNPJ. """ ...
Calculate the verifying digit for the CNPJ. :param cnpj: List of integers with the CNPJ. :param weight: Integer with the weight for the modulo 11 calculate. :returns: The verifying digit for the CNPJ.
__get_verifying_digit_cnpj
python
lk-geimfari/mimesis
mimesis/builtins/pt_br.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/pt_br.py
MIT
def cnpj(self, with_mask: bool = True) -> str: """Get a random CNPJ. :param with_mask: Use cnpj mask (###.###.###-##) :returns: Random cnpj. :Example: 77.732.230/0001-70 """ cnpj_without_dv = [self.random.randint(0, 9) for _ in range(12)] first_dv ...
Get a random CNPJ. :param with_mask: Use cnpj mask (###.###.###-##) :returns: Random cnpj. :Example: 77.732.230/0001-70
cnpj
python
lk-geimfari/mimesis
mimesis/builtins/pt_br.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/pt_br.py
MIT
def generate_sentence(self) -> str: """Generate sentence from the parts. :return: Sentence. """ sentences = self._extract(["sentence"]) sentence = [ self.random.choice(sentences[k]) for k in ("head", "p1", "p2", "tail") ] return " ".join(sentence)
Generate sentence from the parts. :return: Sentence.
generate_sentence
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def passport_series(self, year: int | None = None) -> str: """Generate random series of passport. :param year: Year of manufacture. :type year: int or None :return: Series. :Example: 02 15. """ if not year: year = self.random.randint(10, ...
Generate random series of passport. :param year: Year of manufacture. :type year: int or None :return: Series. :Example: 02 15.
passport_series
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def series_and_number(self) -> str: """Generate a random passport number and series. :return: Series and number. :Example: 57 16 805199. """ series = self.passport_series() number = self.passport_number() return f"{series} {number}"
Generate a random passport number and series. :return: Series and number. :Example: 57 16 805199.
series_and_number
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def snils(self) -> str: """Generate snils with a special algorithm. :return: SNILS. :Example: 41917492600. """ numbers = [] control_codes = [] for i in range(0, 9): numbers.append(self.random.randint(0, 9)) for i in range(9, 0, ...
Generate snils with a special algorithm. :return: SNILS. :Example: 41917492600.
snils
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def inn(self) -> str: """Generate random, but valid ``INN``. :return: INN. """ def control_sum(nums: list[int], t: str) -> int: digits_dict = { "n2": [7, 2, 4, 10, 3, 5, 9, 4, 6, 8], "n1": [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8], } ...
Generate random, but valid ``INN``. :return: INN.
inn
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def ogrn(self) -> str: """Generate random valid ``OGRN``. :return: OGRN. :Example: 4715113303725. """ numbers = [] for _ in range(0, 12): numbers.append(self.random.randint(1 if _ == 0 else 0, 9)) _ogrn = "".join(str(i) for i in numbers)...
Generate random valid ``OGRN``. :return: OGRN. :Example: 4715113303725.
ogrn
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def bic(self) -> str: """Generate random ``BIC`` (Bank ID Code). :return: BIC. :Example: 044025575. """ country_code = "04" code = f"{self.random.randint(1, 10):02}" bank_number = f"{self.random.randint(0, 99):02}" bank_office = f"{self.rando...
Generate random ``BIC`` (Bank ID Code). :return: BIC. :Example: 044025575.
bic
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def kpp(self) -> str: """Generate random ``KPP``. :return: 'KPP'. :Example: 560058652. """ tax_codes: list[str] = self._extract(["tax_codes"]) tax_code = tax_codes[self.random.randint(0, len(tax_codes) - 1)] reg_code = f"{self.random.randint(1, 99):0...
Generate random ``KPP``. :return: 'KPP'. :Example: 560058652.
kpp
python
lk-geimfari/mimesis
mimesis/builtins/ru.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/ru.py
MIT
def patronymic(self, gender: Gender | None = None) -> str: """Generate random patronymic name. :param gender: Gender of person. :type gender: str or int :return: Patronymic name. """ gender = self.validate_enum(gender, Gender) patronymics: list[str] = self._extra...
Generate random patronymic name. :param gender: Gender of person. :type gender: str or int :return: Patronymic name.
patronymic
python
lk-geimfari/mimesis
mimesis/builtins/uk.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/builtins/uk.py
MIT
def __init__( self, field: str, locale: Locale | None = None, **kwargs: Any, ) -> None: """ Creates a field instance. The created field is lazy. It also receives build time parameters. These parameters are not applied yet. :param field: name ...
Creates a field instance. The created field is lazy. It also receives build time parameters. These parameters are not applied yet. :param field: name to be passed to :class:`~mimesis.schema.Field`. :param locale: locale to use. This parameter has the highest priority. ...
__init__
python
lk-geimfari/mimesis
mimesis/plugins/factory.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/plugins/factory.py
MIT
def evaluate( self, instance: Resolver, step: BuildStep, extra: dict[str, Any] | None = None, ) -> Any: """Evaluates the lazy field. :param instance: (factory.builder.Resolver): The object holding currently computed attributes. :param step: (factory.builder.B...
Evaluates the lazy field. :param instance: (factory.builder.Resolver): The object holding currently computed attributes. :param step: (factory.builder.BuildStep): The object holding the current build step. :param extra: Extra call-time added kwargs that would be passed to ``Field``.
evaluate
python
lk-geimfari/mimesis
mimesis/plugins/factory.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/plugins/factory.py
MIT
def override_locale(cls, locale: Locale) -> Iterator[None]: """ Overrides unspecified locales. Remember that implicit locales would not be overridden. """ old_locale = cls._default_locale cls._default_locale = locale yield cls._default_locale = old_locale
Overrides unspecified locales. Remember that implicit locales would not be overridden.
override_locale
python
lk-geimfari/mimesis
mimesis/plugins/factory.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/plugins/factory.py
MIT
def _get_cached_instance( cls, locale: Locale | None = None, field_handlers: RegisterableFieldHandlers | None = None, ) -> Field: """Returns cached instance. :param locale: locale to use. :param field_handlers: custom field handlers. :return: cached instance ...
Returns cached instance. :param locale: locale to use. :param field_handlers: custom field handlers. :return: cached instance of Field.
_get_cached_instance
python
lk-geimfari/mimesis
mimesis/plugins/factory.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/plugins/factory.py
MIT
def address(self) -> str: """Generates a random full address. :return: Full address. """ fmt: str = self._extract(["address_fmt"]) st_num = self.street_number() st_name = self.street_name() if self.locale in SHORTENED_ADDRESS_FMT: return fmt.format(...
Generates a random full address. :return: Full address.
address
python
lk-geimfari/mimesis
mimesis/providers/address.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/address.py
MIT
def state(self, abbr: bool = False) -> str: """Generates a random administrative district of the country. :param abbr: Return ISO 3166-2 code. :return: Administrative district. """ key = "abbr" if abbr else "name" states: list[str] = self._extract(["state", key]) ...
Generates a random administrative district of the country. :param abbr: Return ISO 3166-2 code. :return: Administrative district.
state
python
lk-geimfari/mimesis
mimesis/providers/address.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/address.py
MIT
def _get_fs(self, key: str, dms: bool = False) -> str | float: """Get float number. :param key: Key (`lt` or `lg`). :param dms: DMS format. :return: Float number """ # The default range is a range of longitudes. rng = (-90, 90) if key == "lt" else (-180, 180) ...
Get float number. :param key: Key (`lt` or `lg`). :param dms: DMS format. :return: Float number
_get_fs
python
lk-geimfari/mimesis
mimesis/providers/address.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/address.py
MIT
def coordinates(self, dms: bool = False) -> dict[str, str | float]: """Generates random geo coordinates. :param dms: DMS format. :return: Dict with coordinates. """ return { "longitude": self._get_fs("lg", dms), "latitude": self._get_fs("lt", dms), ...
Generates random geo coordinates. :param dms: DMS format. :return: Dict with coordinates.
coordinates
python
lk-geimfari/mimesis
mimesis/providers/address.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/address.py
MIT
def continent(self, code: bool = False) -> str: """Returns a random continent name or continent code. :param code: Return code of a continent. :return: Continent name. """ codes: list[str] = self._extract(["continent"]) if code: codes = CONTINENT_CODES ...
Returns a random continent name or continent code. :param code: Return code of a continent. :return: Continent name.
continent
python
lk-geimfari/mimesis
mimesis/providers/address.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/address.py
MIT
def __init__( self, *, seed: Seed = MissingSeed, random: _random.Random | None = None, ) -> None: """Initialize attributes. Keep in mind that locale-independent data providers will work only with keyword-only arguments. :param seed: Seed for random. ...
Initialize attributes. Keep in mind that locale-independent data providers will work only with keyword-only arguments. :param seed: Seed for random. When set to `None` the current system time is used. :param random: Custom random. See https://github.com/lk-geimf...
__init__
python
lk-geimfari/mimesis
mimesis/providers/base.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py
MIT
def reseed(self, seed: Seed = MissingSeed) -> None: """Reseeds the internal random generator. In case we use the default seed, we need to create a per instance random generator. In this case, two providers with the same seed will always return the same values. :param seed: Seed...
Reseeds the internal random generator. In case we use the default seed, we need to create a per instance random generator. In this case, two providers with the same seed will always return the same values. :param seed: Seed for random. When set to `None` the current system ...
reseed
python
lk-geimfari/mimesis
mimesis/providers/base.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py
MIT
def validate_enum(self, item: t.Any, enum: t.Any) -> t.Any: """Validates various enum objects that are used as arguments for methods. :param item: Item of an enum object. :param enum: Enum object. :return: Value of item. :raises NonEnumerableError: If enums has not such an item....
Validates various enum objects that are used as arguments for methods. :param item: Item of an enum object. :param enum: Enum object. :return: Value of item. :raises NonEnumerableError: If enums has not such an item.
validate_enum
python
lk-geimfari/mimesis
mimesis/providers/base.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py
MIT
def _read_global_file(self, file_name: str) -> t.Any: """Reads JSON file and return dict. Reads JSON file from mimesis/data/global/ directory. :param file_name: Path to file. :raises FileNotFoundError: If the file was not found. :return: JSON data. """ with open...
Reads JSON file and return dict. Reads JSON file from mimesis/data/global/ directory. :param file_name: Path to file. :raises FileNotFoundError: If the file was not found. :return: JSON data.
_read_global_file
python
lk-geimfari/mimesis
mimesis/providers/base.py
https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/base.py
MIT