id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
100
import importlib import re from absl import app from absl import flags import gin import seqio import tensorflow.compat.v1 as tf The provided code snippet includes necessary dependencies for implementing the `sequence_length` function. Write a Python function `def sequence_length(value=512)` to solve the following pro...
Sequence length used when tokenizing. Args: value: an integer or dictionary Returns: a dictionary
101
import importlib import re from absl import app from absl import flags import gin import seqio import tensorflow.compat.v1 as tf FLAGS = flags.FLAGS The provided code snippet includes necessary dependencies for implementing the `pretty` function. Write a Python function `def pretty(value)` to solve the following probl...
Optional pretty printing helper for detokenized inputs. Makes any text delimiter regex specified in `--delimiters` bold in textual output. Args: value: string representing the detokenized output Returns: a string with appropriate styling applied
102
import importlib import re from absl import app from absl import flags import gin import seqio import tensorflow.compat.v1 as tf def import_modules(modules): for module in modules: importlib.import_module(module)
null
103
import functools import os import re from typing import Any, Callable, Iterable, Mapping, MutableSequence, Optional, Sequence, Tuple, Union from absl import logging import gin import numpy as np import seqio import t5.data import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds import typing_extensions _MO...
Filters example features, keeping only valid model features.
104
import functools import os import re from typing import Any, Callable, Iterable, Mapping, MutableSequence, Optional, Sequence, Tuple, Union from absl import logging import gin import numpy as np import seqio import t5.data import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds import typing_extensions def...
Get checkpoints from model directory. **Note**: This only works for models checkpoints saved using Tensorflow. Args: checkpoint_steps: list, int or str. If checkpoint_step is an int, find the checkpoint with the closest global step and return a singleton list. If checkpoint_step is a list of ints, replace each int with...
105
import functools import os import re from typing import Any, Callable, Iterable, Mapping, MutableSequence, Optional, Sequence, Tuple, Union from absl import logging import gin import numpy as np import seqio import t5.data import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds import typing_extensions def...
Run evaluation on the given mixture or task. Args: mixture_or_task_name: str, the name of the Mixture or Task to evaluate on. Must be pre-registered in the global `TaskRegistry` or `MixtureRegistry.` predict_or_score_fn: function, This function takes in the sequence length, checkpoint step, tasks to evaluate, an eval_d...
106
import importlib import os import sys from absl import app from absl import flags from absl import logging import gin from mesh_tensorflow.transformer import utils import pkg_resources import t5 from t5.models import mesh_transformer from t5.models import mtf_model import tensorflow.compat.v1 as tf def main(_): if FL...
null
107
import functools import os import gin import gin.tf import mesh_tensorflow as mtf from mesh_tensorflow import optimize from mesh_tensorflow.transformer import dataset as transformer_dataset from mesh_tensorflow.transformer import learning_rate_schedules from mesh_tensorflow.transformer import utils as mtf_utils from t5...
null
108
import functools from absl import logging import gin import mesh_tensorflow.transformer.dataset as transformer_dataset import seqio from t5.models import utils as model_utils import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds The provided code snippet includes necessary dependencies for implementing ...
Returns the tf.data.Dataset for training on a given mixture. This uses the format required for utils.run's `train_dataset_fn` argument in the Mesh TF transformer standalone. Args: mixture_or_task_name: string, an identifier for a Mixture or Task in the appropriate registry. Must be specified via gin. sequence_length: d...
109
import functools from absl import logging import gin import mesh_tensorflow.transformer.dataset as transformer_dataset import seqio from t5.models import utils as model_utils import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds The provided code snippet includes necessary dependencies for implementing ...
Returns all tf.data.Datasets for LM inference on a given mixture. For Tasks without inputs (such as language modeling), the first `priming_sequence_length` tokens in the target are used as the "inputs" for inference. Args: mixture_or_task_name: string, an identifier for a Mixture or Task in the appropriate registry. Mu...
110
import functools from absl import logging import gin import mesh_tensorflow.transformer.dataset as transformer_dataset import seqio from t5.models import utils as model_utils import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds The provided code snippet includes necessary dependencies for implementing ...
Returns all tf.data.Datasets for evaluation on a given mixture. This uses the format required for utils.run's `eval_dataset_fn` argument in the Mesh TF transformer standalone. Args: mixture_or_task_name: string, an identifier for a Mixture or Task in the appropriate registry. Must be specified via gin. sequence_length:...
111
import functools from absl import logging import gin import mesh_tensorflow.transformer.dataset as transformer_dataset import seqio from t5.models import utils as model_utils import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds The provided code snippet includes necessary dependencies for implementing ...
r"""Returns a dataset based on a TSV file formatted as `<input>\t<target>`.
112
import functools from absl import logging import gin import mesh_tensorflow.transformer.dataset as transformer_dataset import seqio from t5.models import utils as model_utils import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds The provided code snippet includes necessary dependencies for implementing ...
Get the appropriate value for the utils.run.vocabulary argument. Args: mixture_or_task_name: string, an identifier for a Mixture or Task in the appropriate registry. Must be specified via gin. Returns: Either a single seqio.vocabularies.Vocabulary or a tuple of seqio.vocabularies.Vocabulary for inputs and targets.
113
import functools import itertools import os import re import time from absl import logging import mesh_tensorflow.transformer.dataset as transformer_dataset import seqio import t5.data from t5.models import utils from t5.models.t5_model import T5Model import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds...
Convert a dataset of token sequences to batches of padded/masked examples. Args: dataset: tf.data.Dataset containing examples with token sequences. sequence_length: dict of int, a dict mapping feature name to length. batch_size: int, the number of padded sequences in each batch. output_features: list of str, features t...
114
import functools import itertools import os import re import time from absl import logging import mesh_tensorflow.transformer.dataset as transformer_dataset import seqio import t5.data from t5.models import utils from t5.models.t5_model import T5Model import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds...
Get a tf.data.Dataset for a given Task or Mixture. Args: mixture_or_task_or_name: Task or Mixture or str, the name of the Mixture or Task to train on or the Tasks or Mixture object itself. Must be pre-registered in the global `t5.data.TaskRegistry` or `t5.data.MixtureRegistry.` sequence_length: dict of int, a dict mapp...
115
import argparse, os, shutil, time import cv2 import torch from torch import nn from torch.utils.data import DataLoader from torchvision.transforms import Compose, ToTensor, Resize from torchvision.transforms.functional import to_pil_image from threading import Thread, Lock from tqdm import tqdm from PIL import Image fr...
null
116
import argparse import kornia import torch import os import random from torch import nn from torch import distributed as dist from torch import multiprocessing as mp from torch.nn import functional as F from torch.cuda.amp import autocast, GradScaler from torch.utils.tensorboard import SummaryWriter from torch.utils.da...
null
117
import argparse import torch import os import shutil from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import transforms as T from torchvision.transforms.functional import to_pil_image from threading import Thread from tqdm import tqdm from dataset import...
null
118
import os import re from setuptools import setup from setuptools import find_packages with open("README.md", "r") as fh: long_description = fh.read() with open("requirements.txt", encoding="utf8") as f: requirements = f.readlines() def find_version(*filepath): here = os.path.abspath(os.path.dirname(__file_...
null
119
import warnings import os import numpy as np from gradient_free_optimizers import ( HillClimbingOptimizer, StochasticHillClimbingOptimizer, RepulsingHillClimbingOptimizer, SimulatedAnnealingOptimizer, DownhillSimplexOptimizer, RandomSearchOptimizer, GridSearchOptimizer, RandomRestartHill...
null
120
import warnings import os import gc import glob import numpy as np import pandas as pd from tqdm import tqdm import matplotlib as mpl import matplotlib.pyplot as plt from gradient_free_optimizers.optimizers.core_optimizer.converter import Converter def warn(*args, **kwargs): pass
null
121
import warnings import os import gc import glob import numpy as np import pandas as pd from tqdm import tqdm import matplotlib as mpl import matplotlib.pyplot as plt from gradient_free_optimizers.optimizers.core_optimizer.converter import Converter def plot_search_paths( path, optimizer, opt_para, n_ite...
null
122
import numpy as np from gradient_free_optimizers import HillClimbingOptimizer def convex_function(pos_new): score = -(pos_new["x1"] * pos_new["x1"] + pos_new["x2"] * pos_new["x2"]) return score
null
123
import numpy as np from gradient_free_optimizers import GridSearchOptimizer def convex_function(pos_new): score = -(pos_new["x1"] * pos_new["x1"] + pos_new["x2"] * pos_new["x2"]) return score
null
124
import numpy as np from gradient_free_optimizers import RandomSearchOptimizer def ackley_function(pos_new): x = pos_new["x1"] y = pos_new["x2"] a1 = -20 * np.exp(-0.2 * np.sqrt(0.5 * (x * x + y * y))) a2 = -np.exp(0.5 * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y))) score = a1 + a2 + 20 retu...
null
125
import numpy as np from gradient_free_optimizers import RandomSearchOptimizer def convex_function(pos_new): score = -(pos_new["x1"] * pos_new["x1"] + pos_new["x2"] * pos_new["x2"]) return score
null
126
import numpy as np from gradient_free_optimizers import RandomSearchOptimizer def constraint_1(para): # only values in 'x1' higher than -5 are valid return para["x1"] > -5
null
127
from keras.models import Sequential from keras.layers import ( Dense, Conv2D, MaxPooling2D, Flatten, Dropout, Activation, ) from keras.datasets import cifar10 from keras.utils import to_categorical from gradient_free_optimizers import BayesianOptimizer import numpy as np (X_train, y_train), (X_t...
null
128
import numpy as np import matplotlib.pyplot as plt from gradient_free_optimizers import HillClimbingOptimizer def gaussian_function(x, A, B, C): return A * np.exp(-(x-B)**2/(2*C**2)) x_range = np.arange(min_x, max_x, step_x) y_gauss_hist = plt.hist(gauss_np1, density=True, bins=bins)[0] def fit_gaussian(para): ...
null
129
import numpy as np from sklearn.model_selection import cross_val_score from sklearn.ensemble import GradientBoostingClassifier from sklearn.datasets import load_wine from gradient_free_optimizers import HillClimbingOptimizer X, y = data.data, data.target def model(para): gbc = GradientBoostingClassifier( n...
null
130
import numpy as np from gradient_free_optimizers import LipschitzOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
131
import numpy as np from gradient_free_optimizers import EvolutionStrategyOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
132
import numpy as np from gradient_free_optimizers import SimulatedAnnealingOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
133
import numpy as np from gradient_free_optimizers import GridSearchOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
134
import numpy as np from gradient_free_optimizers import PatternSearch def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
135
import numpy as np from gradient_free_optimizers import PowellsMethod def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
136
import numpy as np from gradient_free_optimizers import SpiralOptimization def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
137
import numpy as np from gradient_free_optimizers import HillClimbingOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
138
import numpy as np from gradient_free_optimizers import DownhillSimplexOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
139
import numpy as np from gradient_free_optimizers import ParallelTemperingOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
140
import numpy as np from gradient_free_optimizers import StochasticHillClimbingOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
141
import numpy as np from gradient_free_optimizers import BayesianOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
142
import numpy as np from gradient_free_optimizers import DirectAlgorithm def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
143
import numpy as np from gradient_free_optimizers import RepulsingHillClimbingOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
144
import numpy as np from gradient_free_optimizers import TreeStructuredParzenEstimators def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
145
import numpy as np from gradient_free_optimizers import ParticleSwarmOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
146
import numpy as np from gradient_free_optimizers import RandomSearchOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
147
import numpy as np from gradient_free_optimizers import RandomRestartHillClimbingOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
148
import numpy as np from gradient_free_optimizers import RandomAnnealingOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
149
import numpy as np from gradient_free_optimizers import ForestOptimizer def sphere_function(para): x = para["x"] y = para["y"] return -(x * x + y * y)
null
150
import numpy as np from sklearn.model_selection import cross_val_score from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_wine from gradient_free_optimizers import HillClimbingOptimizer X, y = data.data, data.target def model(para): gbc = DecisionTreeClassifier( min_samples_s...
null
151
import random import numpy as np The provided code snippet includes necessary dependencies for implementing the `set_random_seed` function. Write a Python function `def set_random_seed(nth_process, random_state)` to solve the following problem: Sets the random seed separately for each thread (to avoid getting the same...
Sets the random seed separately for each thread (to avoid getting the same results in each thread)
152
import random import numpy as np def move_random(ss_positions): position = [] for search_space_pos in ss_positions: pos_ = random.choice(search_space_pos) position.append(pos_) return np.array(position)
null
153
import numpy as np from scipy.stats import norm from ..smb_opt.smbo import SMBO from ..smb_opt.surrogate_models import EnsembleRegressor from ..smb_opt.acquisition_function import ExpectedImprovement from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.svm i...
null
154
import random import numpy as np from ..local_opt import HillClimbingOptimizer def max_list_idx(list_): max_item = max(list_) max_item_idx = [i for i, j in enumerate(list_) if j == max_item] return max_item_idx[-1:][0]
null
155
import numpy as np from collections import OrderedDict from ..local_opt import HillClimbingOptimizer def sort_list_idx(list_): list_np = np.array(list_) idx_sorted = list(list_np.argsort()[::-1]) return idx_sorted
null
156
import numpy as np from ..local_opt import HillClimbingOptimizer def roation(n_dim, vector): if n_dim == 1: return -1 # not sure about that I = np.identity(n_dim - 1) R = np.pad(I, ((1, 0), (0, 1)), constant_values=(0, 0)) R[0, n_dim - 1] = -1 return np.matmul(R, vector)
null
157
import numpy as np from .base_population_optimizer import BasePopulationOptimizer from ._spiral import Spiral def centeroid(array_list): centeroid = [] for idx in range(array_list[0].shape[0]): center_dim_pos = [] for array in array_list: center_dim_pos.append(array[idx]) c...
null
158
import math import numpy as np from ..core_optimizer import CoreOptimizer def split(positions_l, population): div_int = math.ceil(len(positions_l) / population) dist_init_positions = [] for nth_indiv in range(population): indiv_pos = [] for nth_indiv_pos in range(div_int): idx ...
null
159
import numpy as np from sklearn.linear_model import BayesianRidge from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import Matern, WhiteKernel, RBF from sklearn.ensemble import ExtraTreesRegressor as _ExtraTreesRegressor_ from sklearn.ensemble import RandomForestRegress...
used from: https://github.com/scikit-optimize/scikit-optimize/blob/master/skopt/learning/forest.py
160
import numpy as np from scipy.stats import norm def normalize(array): num = array - array.min() den = array.max() - array.min() if den == 0: return np.random.random_sample(array.shape) else: return ((num / den) + 0) / 1
null
161
import numpy as np from scipy.stats import norm from .smbo import SMBO from .surrogate_models import ( GPR_linear, GPR, ) from .acquisition_function import ExpectedImprovement def normalize(array): num = array - array.min() den = array.max() - array.min() if den == 0: return np.random.rand...
null
162
import numpy as np from scipy.stats import norm from .smbo import SMBO from .surrogate_models import ( RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor, ) from .acquisition_function import ExpectedImprovement def normalize(array): num = array - array.min() den = array.max() - a...
null
163
import random import numpy as np from .hill_climbing_optimizer import HillClimbingOptimizer def sort_list_idx(list_): list_np = np.array(list_) idx_sorted = list(list_np.argsort()[::-1]) return idx_sorted
null
164
import random import numpy as np from .hill_climbing_optimizer import HillClimbingOptimizer def centeroid(array_list): centeroid = [] for idx in range(array_list[0].shape[0]): center_dim_pos = [] for array in array_list: center_dim_pos.append(array[idx]) center_dim_mean = ...
null
165
import numpy as np from ..base_optimizer import BaseOptimizer from numpy.random import normal, laplace, logistic, gumbel def max_list_idx(list_): max_item = max(list_) max_item_idx = [i for i, j in enumerate(list_) if j == max_item] return max_item_idx[-1:][0]
null
166
import numpy as np def _print_times(eval_time, iter_time, n_iter): opt_time = iter_time - eval_time iterPerSec = n_iter / iter_time print( indent, "Evaluation time :", eval_time, "sec", indent, "[{} %]".format(round(eval_time / iter_time * 100, 2)), ) ...
null
167
import time import numpy as np def time_exceeded(start_time, max_time): run_time = time.time() - start_time return max_time and run_time > max_time
null
168
import time import numpy as np def score_exceeded(score_best, max_score): return max_score and score_best >= max_score
null
169
import time import numpy as np def no_change(score_new_list, early_stopping): if "n_iter_no_change" not in early_stopping: print( "Warning n_iter_no_change-parameter must be set in order for early stopping to work" ) return False n_iter_no_change = early_stopping["n_iter_no...
null
170
import traceback from dataclasses import dataclass from pathlib import Path from typing import Dict, List from readmeai.config.settings import ConfigLoader from readmeai.core.logger import Logger _logger = Logger(__name__) class QuickStart: """Information about using, running, and testing a repository.""" insta...
Generates the 'Quick Start' section of the README file.
171
import re from typing import List EMOJI_PATTERN = re.compile( pattern="[" "\U0001f600-\U0001f64f" # emoticons "\U0001f300-\U0001f5ff" # symbols & pictographs "\U0001f680-\U0001f6ff" # transport & map symbols "\U0001f700-\U0001f77f" # alchemical symbols "\U0001f780-\U0001f7ff" # Geometric Sh...
Removes emojis from the content list.
172
import re from typing import List The provided code snippet includes necessary dependencies for implementing the `split_markdown_headings` function. Write a Python function `def split_markdown_headings(markdown_text: str) -> dict` to solve the following problem: Splits a markdown document by level 2 headings into sepa...
Splits a markdown document by level 2 headings into separate sections.
173
import re from typing import List The provided code snippet includes necessary dependencies for implementing the `update_heading_names` function. Write a Python function `def update_heading_names(md_contents: dict) -> dict` to solve the following problem: Updates dict keys by removing leading emojis, underscores, and ...
Updates dict keys by removing leading emojis, underscores, and spaces.
174
from pathlib import Path from typing import List, Tuple from readmeai.services.git import fetch_git_file_url def is_valid_tuple_summary(summary: Tuple[str, str]) -> bool: """Checks if a summary is a valid tuple format.""" return isinstance(summary, tuple) and len(summary) == 2 The provided code snippet include...
Converts the given code summaries into a formatted list.
175
from pathlib import Path from typing import List, Tuple from readmeai.services.git import fetch_git_file_url def construct_markdown_table( data: List[Tuple[str, str]], repo_url: str, full_name: str ) -> str: """Builds a Markdown table from the provided data.""" headers = ["File", "Summary"] table_rows =...
Produces Markdown tables for each project sub-directory.
176
from typing import Tuple from readmeai.cli.options import BadgeOptions from readmeai.config.settings import ConfigLoader from readmeai.services.git import GitHost from readmeai.utils.file_handler import FileHandler from readmeai.utils.file_resources import get_resource_path _package = "readmeai.generators" _submodule =...
Generates badges for the README using skill icons, from the repository - https://github.com/tandpfun/skill-icons.
177
from typing import Dict, Type from readmeai.core.parsers import BaseFileParser from readmeai.parsers.configuration.docker import ( DockerComposeParser, DockerfileParser, ) from readmeai.parsers.configuration.properties import PropertiesParser from readmeai.parsers.language.cpp import ( CMakeParser, Conf...
Returns a dictionary of callable file parser methods.
178
import asyncio import tempfile import traceback from pathlib import Path from typing import Optional from readmeai._exceptions import ReadmeGeneratorError from readmeai.cli.options import ImageOptions, ModelOptions from readmeai.config.settings import ConfigLoader, GitSettings from readmeai.core.logger import Logger fr...
Configures and runs the README file generator agent.
179
from __future__ import annotations from enum import Enum from typing import Optional import click class ImageOptions(str, Enum): """ Enum for CLI options for README file header images. """ # Custom image options CUSTOM = "custom" LLM = "llm" # Default image options BLACK = "https://img.i...
Prompt the user for a custom image URL.
180
import os import platform import shutil from enum import Enum from pathlib import Path from typing import Optional import git from readmeai._exceptions import GitCloneError from readmeai.core.logger import Logger The provided code snippet includes necessary dependencies for implementing the `find_git_executable` funct...
Find the path to the git executable, if available.
181
import os import platform import shutil from enum import Enum from pathlib import Path from typing import Optional import git from readmeai._exceptions import GitCloneError from readmeai.core.logger import Logger The provided code snippet includes necessary dependencies for implementing the `validate_file_permissions`...
Validates file permissions of the cloned repository.
182
import os import platform import shutil from enum import Enum from pathlib import Path from typing import Optional import git from readmeai._exceptions import GitCloneError from readmeai.core.logger import Logger The provided code snippet includes necessary dependencies for implementing the `validate_git_executable` f...
Validate the path to the git executable.
183
from dataclasses import dataclass from typing import Any, Dict, List, Optional import aiohttp from readmeai.core.logger import Logger from readmeai.services.git import fetch_git_api_url _logger = Logger(__name__) class RepositoryMetadata: """Dataclass to store GitHub repository metadata.""" name: str full_n...
Retrieves GitHub repository metadata and returns a dataclass.
184
from typing import Dict, List, Union import readmeai.config.settings as Settings from readmeai.core.logger import Logger _logger = Logger(__name__) def get_prompt_template(prompts: dict, prompt_type: str) -> str: """Retrieves the template for the given prompt type.""" prompt_templates = { "features": pr...
Generates a prompt for the LLM API.
185
from typing import Dict, List, Union import readmeai.config.settings as Settings from readmeai.core.logger import Logger The provided code snippet includes necessary dependencies for implementing the `set_additional_contexts` function. Write a Python function `async def set_additional_contexts( config: Settings, ...
Generates additional prompts (features, overview, slogan) for LLM.
186
from typing import Dict, List, Union import readmeai.config.settings as Settings from readmeai.core.logger import Logger The provided code snippet includes necessary dependencies for implementing the `set_summary_context` function. Write a Python function `async def set_summary_context( config: Settings, depen...
Generates the summary prompts to be used by the LLM API.
187
from tiktoken import get_encoding from readmeai.config.settings import Settings from readmeai.core.logger import Logger _logger = Logger(__name__) def count_tokens(text: str, encoder: str) -> int: """Return the number of tokens in a text string.""" try: encoding = _set_encoding_cache(encoder) to...
Handle token count for the prompt.
188
from tiktoken import get_encoding from readmeai.config.settings import Settings from readmeai.core.logger import Logger The provided code snippet includes necessary dependencies for implementing the `update_max_tokens` function. Write a Python function `def update_max_tokens( max_tokens: int, prompt: str, target: ...
Adjust the maximum number of tokens based on the specific prompt.
189
import re def clean_text(text: str) -> str: """Format and clean generated text from the LLM.""" # Dynamically remove all text before and including the first colon if any exist text = re.sub(r"^[^:]*:\s*", "", text) # Remove any text before and including "**:" text = re.sub(r"\*\*:\s*", "", text, fla...
Post-processes the response from the LLM.
190
import re The provided code snippet includes necessary dependencies for implementing the `fix_md_table_rows` function. Write a Python function `def fix_md_table_rows(md_table: str) -> str` to solve the following problem: Format a Markdown table with feature and description columns. Here is the function: def fix_md_t...
Format a Markdown table with feature and description columns.
191
import nox def install(session, groups, root=True): """Install the package in the current session.""" if root: groups = ["main", *groups] session.run_always( "poetry", "install", "--no-root", "--sync", f"--only={','.join(groups)}", external=True, )...
Run the test suite across Python versions
192
from typing import List, Optional from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute The provided code snippet includes necessary dependencies for implementing the `summary` function. Write a Python function `def summary(text: str, minlength: Optional[int] = None, maxle...
Runs a summarization model against a block of text. Args: text: text to summarize minlength: minimum length for summary maxlength: maximum length for summary Returns: summary text
193
from typing import List, Optional from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute The provided code snippet includes necessary dependencies for implementing the `batchsummary` function. Write a Python function `def batchsummary(texts: List[str] = Body(...), minlength...
Runs a summarization model against a block of text. Args: texts: list of text to summarize minlength: minimum length for summary maxlength: maximum length for summary Returns: list of summary text
194
from typing import List from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute The provided code snippet includes necessary dependencies for implementing the `tabular` function. Write a Python function `def tabular(file: str)` to solve the following problem: Splits tabular ...
Splits tabular data into rows and columns. Args: file: file to process Returns: list of (id, text, tag) elements
195
from typing import List from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute The provided code snippet includes necessary dependencies for implementing the `batchtabular` function. Write a Python function `def batchtabular(files: List[str] = Body(...))` to solve the follo...
Splits tabular data into rows and columns. Args: files: list of files to process Returns: list of (id, text, tag) elements
196
from typing import List, Optional from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute The provided code snippet includes necessary dependencies for implementing the `translate` function. Write a Python function `def translate(text: str, target: Optional[str] = "en", sour...
Translates text from source language into target language. Args: text: text to translate target: target language code, defaults to "en" source: source language code, detects language if not provided Returns: translated text
197
from typing import List, Optional from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute The provided code snippet includes necessary dependencies for implementing the `batchtranslate` function. Write a Python function `def batchtranslate(texts: List[str] = Body(...), targe...
Translates text from source language into target language. Args: texts: list of text to translate target: target language code, defaults to "en" source: source language code, detects language if not provided Returns: list of translated text
198
from typing import List, Optional from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute The provided code snippet includes necessary dependencies for implementing the `extract` function. Write a Python function `def extract(queue: List[dict] = Body(...), texts: Optional[Li...
Extracts answers to input questions. Args: queue: list of {name: value, query: value, question: value, snippet: value} texts: optional list of text Returns: list of {name: value, answer: value}
199
from typing import List from fastapi import APIRouter, Body from .. import application from ..route import EncodingAPIRoute def label(text: str = Body(...), labels: List[str] = Body(...)): """ Applies a zero shot classifier to text using a list of labels. Returns a list of {id: value, score: value} sorted b...
Applies a zero shot classifier to list of text using a list of labels. Returns a list of {id: value, score: value} sorted by highest score, where id is the index in labels per text element. Args: texts: list of text labels: list of labels Returns: list of {id: value score: value} per text element