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 __getstate__(self): """Control how the object is pickled""" state = self.__dict__.copy() # Remove unpicklable attributes if 'client' in state: del state['client'] # Remove Label Studio client if 'project' in state: del state['project'] # Remove proje...
Control how the object is pickled
__getstate__
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/annotation_mapper.py
Apache-2.0
def __setstate__(self, state): """Control how the object is unpickled""" self.__dict__.update(state) # Reconnect to Label Studio if needed if hasattr(self, 'api_url') and hasattr(self, 'api_key'): try: self.client = label_studio_sdk.Client(url=self.api_url, ...
Control how the object is unpickled
__setstate__
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/annotation_mapper.py
Apache-2.0
def _get_project_url(self): """Get URL to the Label Studio project Returns: str: URL to the Label Studio project, or None if not available """ if not hasattr(self, 'api_url') or not self.api_url or not self.project_id: return None ...
Get URL to the Label Studio project Returns: str: URL to the Label Studio project, or None if not available
_get_project_url
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/annotation_mapper.py
Apache-2.0
def _get_task_url(self, task_id): """Get URL to a specific Label Studio task Args: task_id: ID of the task Returns: str: URL to the task in Label Studio, or None if not available """ if not hasattr(self, 'api_url') or not self.api_...
Get URL to a specific Label Studio task Args: task_id: ID of the task Returns: str: URL to the task in Label Studio, or None if not available
_get_task_url
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/annotation_mapper.py
Apache-2.0
def __init__(self, label_config_file: str = None, answer1_key: str = 'answer1', answer2_key: str = 'answer2', prompt_key: str = 'prompt', chosen_key: str = 'chosen', rejected_key: str = 'rejected', **k...
Initialize the human preference annotation operator.
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
Apache-2.0
def _format_task(self, samples: List[Dict]) -> Dict: """Format samples as a Label Studio task for human preference. Args: samples: List of samples to include in the task Returns: Dict: Formatted task data """ # For human preference, we need a special for...
Format samples as a Label Studio task for human preference. Args: samples: List of samples to include in the task Returns: Dict: Formatted task data
_format_task
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
Apache-2.0
def _get_task_annotation(self, task_id: int) -> Optional[Dict]: """Get annotation for a task if available""" annotation = super()._get_task_annotation(task_id) # Process the annotation if available if annotation and 'result' in annotation: # Extract the preference informatio...
Get annotation for a task if available
_get_task_annotation
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
Apache-2.0
def _process_annotation_result(self, annotation: Dict, sample: Dict) -> Dict: """Process human preference annotation result and update the sample Args: annotation: The annotation result from Label Studio sample: The original sample that was ann...
Process human preference annotation result and update the sample Args: annotation: The annotation result from Label Studio sample: The original sample that was annotated Returns: Dict: The updated sample with preference results
_process_annotation_result
python
modelscope/data-juicer
data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/annotation/human_preference_annotation_mapper.py
Apache-2.0
def __init__(self, field_key: str = '', top_ratio: Optional[Annotated[float, Field(ge=0, le=1)]] = None, topk: Optional[PositiveInt] = None, reverse: bool = True, *args, *...
Initialization method. :param field_key: Selector based on the specified value corresponding to the target key. The target key corresponding to multi-level field information need to be separated by '.'. :param top_ratio: Ratio of selected top specified field...
__init__
python
modelscope/data-juicer
data_juicer/ops/selector/frequency_specified_field_selector.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/selector/frequency_specified_field_selector.py
Apache-2.0
def __init__(self, select_ratio: Optional[Annotated[float, Field(ge=0, le=1)]] = None, select_num: PositiveInt = None, *args, **kwargs): """ Initialization method. :param select...
Initialization method. :param select_ratio: The ratio to select. When both select_ratio and select_num are set, the value corresponding to the smaller number of samples will be applied. :param select_num: The number of samples to select. When both select_rat...
__init__
python
modelscope/data-juicer
data_juicer/ops/selector/random_selector.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/selector/random_selector.py
Apache-2.0
def __init__( self, field_key: str = '', lower_percentile: Optional[Annotated[float, Field(ge=0, le=1)]] = None, upper_percentile: Optional[Annotated[float, Field(ge=0, le=1)...
Initialization method. :param field_key: Selector based on the specified value corresponding to the target key. The target key corresponding to multi-level field information need to be separated by '.'. :param lower_percentile: The lower bound of the percent...
__init__
python
modelscope/data-juicer
data_juicer/ops/selector/range_specified_field_selector.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/selector/range_specified_field_selector.py
Apache-2.0
def __init__(self, field_key: str = '', target_tags: List[str] = None, *args, **kwargs): """ Initialization method. :param field_key: Selector based on the specified value corresponding to the target key. The target...
Initialization method. :param field_key: Selector based on the specified value corresponding to the target key. The target key corresponding to multi-level field information need to be separated by '.'. :param target_tags: Target tags to be select. :...
__init__
python
modelscope/data-juicer
data_juicer/ops/selector/tags_specified_field_selector.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/selector/tags_specified_field_selector.py
Apache-2.0
def __init__(self, field_key: str = '', top_ratio: Optional[Annotated[float, Field(ge=0, le=1)]] = None, topk: Optional[PositiveInt] = None, reverse: bool = True, *args, *...
Initialization method. :param field_key: Selector based on the specified value corresponding to the target key. The target key corresponding to multi-level field information need to be separated by '.'. :param top_ratio: Ratio of selected top samples, sample...
__init__
python
modelscope/data-juicer
data_juicer/ops/selector/topk_specified_field_selector.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/selector/topk_specified_field_selector.py
Apache-2.0
def load_words_asset(words_dir: str, words_type: str): """ Load words from a asset file named `words_type`, if not find a valid asset file, then download it from ASSET_LINKS cached by data_juicer team. :param words_dir: directory that stores asset file(s) :param words_type: name of target words ass...
Load words from a asset file named `words_type`, if not find a valid asset file, then download it from ASSET_LINKS cached by data_juicer team. :param words_dir: directory that stores asset file(s) :param words_type: name of target words assets :return: a dict that stores words assets, whose keys a...
load_words_asset
python
modelscope/data-juicer
data_juicer/utils/asset_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/asset_utils.py
Apache-2.0
def __enter__(self): """ Record the original cache state and turn it to the target state. """ self.previous_state = is_caching_enabled() if self.on: enable_caching() else: disable_caching()
Record the original cache state and turn it to the target state.
__enter__
python
modelscope/data-juicer
data_juicer/utils/cache_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/cache_utils.py
Apache-2.0
def dataset_cache_control(on): """ A more easy-to-use decorator for functions that need to control the cache state temporarily. """ def dataset_cache_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): with DatasetCacheControl(on=on): re...
A more easy-to-use decorator for functions that need to control the cache state temporarily.
dataset_cache_control
python
modelscope/data-juicer
data_juicer/utils/cache_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/cache_utils.py
Apache-2.0
def __init__(self, ckpt_dir, original_process_list, num_proc=1): """ Initialization method. :param ckpt_dir: path to save and load checkpoint :param original_process_list: process list in config :param num_proc: number of process workers when saving dataset """ s...
Initialization method. :param ckpt_dir: path to save and load checkpoint :param original_process_list: process list in config :param num_proc: number of process workers when saving dataset
__init__
python
modelscope/data-juicer
data_juicer/utils/ckpt_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/ckpt_utils.py
Apache-2.0
def check_ckpt(self): """ Check if checkpoint is available. :return: True when checkpoint is available, else False """ if os.path.exists(self.ckpt_ds_dir) \ and os.path.isdir(self.ckpt_ds_dir) \ and os.path.exists(self.ckpt_op_record) \ ...
Check if checkpoint is available. :return: True when checkpoint is available, else False
check_ckpt
python
modelscope/data-juicer
data_juicer/utils/ckpt_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/ckpt_utils.py
Apache-2.0
def check_ops_to_skip(self): """ Check which ops need to be skipped in the process list. If op record list from checkpoint are the same as the prefix part of process list, then skip these ops and start processing from the checkpoint. Otherwise, process the original dataset ...
Check which ops need to be skipped in the process list. If op record list from checkpoint are the same as the prefix part of process list, then skip these ops and start processing from the checkpoint. Otherwise, process the original dataset from scratch. :return: wheth...
check_ops_to_skip
python
modelscope/data-juicer
data_juicer/utils/ckpt_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/ckpt_utils.py
Apache-2.0
def save_ckpt(self, ds): """ Save dataset to checkpoint directory and dump processed ops list. :param ds: input dataset to save """ left_sample_num = len(ds) ds.save_to_disk(self.ckpt_ds_dir, num_proc=min(self.num_proc, left_sample_num)) ...
Save dataset to checkpoint directory and dump processed ops list. :param ds: input dataset to save
save_ckpt
python
modelscope/data-juicer
data_juicer/utils/ckpt_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/ckpt_utils.py
Apache-2.0
def load_ckpt(self): """ Load dataset from a checkpoint file. :return: a dataset stored in checkpoint file. """ from data_juicer.core.data import NestedDataset ds = NestedDataset.load_from_disk(self.ckpt_ds_dir) return ds
Load dataset from a checkpoint file. :return: a dataset stored in checkpoint file.
load_ckpt
python
modelscope/data-juicer
data_juicer/utils/ckpt_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/ckpt_utils.py
Apache-2.0
def stats_to_number(s, reverse=True): ''' convert a stats value which can be string of list to a float. ''' try: if isinstance(s, str): return float(s) if s is None or s == []: raise ValueError('empty value') return float(np.asarray(s).mean()) ...
convert a stats value which can be string of list to a float.
stats_to_number
python
modelscope/data-juicer
data_juicer/utils/common_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/common_utils.py
Apache-2.0
def dict_to_hash(input_dict: dict, hash_length=None): """ hash a dict to a string with length hash_length :param input_dict: the given dict """ sorted_items = sorted(input_dict.items()) dict_string = str(sorted_items).encode() hasher = hashlib.sha256() hasher.update(dict_string)...
hash a dict to a string with length hash_length :param input_dict: the given dict
dict_to_hash
python
modelscope/data-juicer
data_juicer/utils/common_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/common_utils.py
Apache-2.0
def nested_access(data, path, digit_allowed=True): """ Access nested data using a dot-separated path. :param data: A dictionary or a list to access the nested data from. :param path: A dot-separated string representing the path to access. This can include numeric indices when access...
Access nested data using a dot-separated path. :param data: A dictionary or a list to access the nested data from. :param path: A dot-separated string representing the path to access. This can include numeric indices when accessing list elements. :param digit_al...
nested_access
python
modelscope/data-juicer
data_juicer/utils/common_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/common_utils.py
Apache-2.0
def avg_split_string_list_under_limit(str_list: list, token_nums: list, max_token_num=None): """ Split the string list to several sub str_list, such that the total token num of each sub string list is less than max_token_num...
Split the string list to several sub str_list, such that the total token num of each sub string list is less than max_token_num, keeping the total token nums of sub string lists are similar. :param str_list: input string list. :param token_nums: token num of each string list. ...
avg_split_string_list_under_limit
python
modelscope/data-juicer
data_juicer/utils/common_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/common_utils.py
Apache-2.0
def extract( cls, input_path: Union[Path, str], output_path: Union[Path, str], extractor_format: str, ): """ Extract content from a compressed file. :param input_path: path to compressed file. :param output_path: path to uncompressed file. :pa...
Extract content from a compressed file. :param input_path: path to compressed file. :param output_path: path to uncompressed file. :param extractor_format: extraction format, see supported algorithm in `Extractor` of huggingface dataset.
extract
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def compress(input_path: Union[Path, str], output_path: Union[Path, str]): """ Compress input file and save to output file. :param input_path: path to uncompressed file. :param output_path: path to compressed file. """ import zstandard as zstd cctx = zstd.ZstdC...
Compress input file and save to output file. :param input_path: path to uncompressed file. :param output_path: path to compressed file.
compress
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def compress(input_path: Union[Path, str], output_path: Union[Path, str]): """ Compress a input file and save to output file. :param input_path: path to uncompressed file. :param output_path: path to compressed file. """ import lz4.frame with open(input_path, 'r...
Compress a input file and save to output file. :param input_path: path to uncompressed file. :param output_path: path to compressed file.
compress
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def compress( cls, input_path: Union[Path, str], output_path: Union[Path, str], compressor_format: str, ): """ Compress input file and save to output file. :param input_path: path to uncompressed file. :param output_path: path to compressed file. ...
Compress input file and save to output file. :param input_path: path to uncompressed file. :param output_path: path to compressed file. :param compressor_format: compression format, see supported algorithm in `compressors`.
compress
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def __init__(self, compressor_format: str = 'zstd'): """ Initialization method. :param compressor_format: compression format algorithms, default `zstd`. """ assert compressor_format in Compressor.compressors.keys() self.compressor_format = compressor_format ...
Initialization method. :param compressor_format: compression format algorithms, default `zstd`.
__init__
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def decompress( self, input_path: Union[Path, str], output_path: Union[Path, str], ): """ Decompress input file and save to output file. :param input_path: path to compressed file. :param output_path: path to uncompressed file. """ self.extrac...
Decompress input file and save to output file. :param input_path: path to compressed file. :param output_path: path to uncompressed file.
decompress
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def _get_cache_directory(self, ds): """ Get dataset cache directory. :param ds: input dataset. :return: dataset cache directory. """ current_cache_files = [ os.path.abspath(cache_file['filename']) for cache_file in ds.cache_files ] ...
Get dataset cache directory. :param ds: input dataset. :return: dataset cache directory.
_get_cache_directory
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def _get_cache_file_names(self, cache_directory: str, fingerprints: Union[str, List[str]] = None, extension='.arrow'): """ Get all cache files in the dataset cache directory with fingerprints, which ends wi...
Get all cache files in the dataset cache directory with fingerprints, which ends with specified extension. :param cache_directory: dataset cache directory. :param fingerprints: fingerprints of cache files. String or List are accepted. If `None`, we will find all cache files...
_get_cache_file_names
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def compress(self, prev_ds: Dataset, this_ds: Dataset = None, num_proc: int = 1): """ Compress cache files with fingerprint in dataset cache directory. :param prev_ds: previous dataset whose cache files need to be compressed here. ...
Compress cache files with fingerprint in dataset cache directory. :param prev_ds: previous dataset whose cache files need to be compressed here. :param this_ds: Current dataset that is computed from the previous dataset. There might be overlaps between cache files of th...
compress
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def decompress(self, ds: Dataset, fingerprints: Union[str, List[str]] = None, num_proc: int = 1): """ Decompress compressed cache files with fingerprint in dataset cache directory. :param ds: input dataset. :param fingerpr...
Decompress compressed cache files with fingerprint in dataset cache directory. :param ds: input dataset. :param fingerprints: fingerprints of cache files. String or List are accepted. If `None`, we will find all cache files which starts with `cache-` and ends wi...
decompress
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def format_cache_file_name( self, cache_file_name: Optional[str]) -> Optional[str]: """ Use `*` to replace the sub rank in a cache file name. :param cache_file_name: a cache file name. """ if not cache_file_name: return cache_file_name cache_file...
Use `*` to replace the sub rank in a cache file name. :param cache_file_name: a cache file name.
format_cache_file_name
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def cleanup_cache_files(self, ds): """ Clean up all compressed cache files in dataset cache directory, which starts with `cache-` and ends with compression format :param ds: input dataset. """ cache_directory = self._get_cache_directory(ds) if cache_directory is N...
Clean up all compressed cache files in dataset cache directory, which starts with `cache-` and ends with compression format :param ds: input dataset.
cleanup_cache_files
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def __enter__(self): """ Record the original cache compression method and turn it off. """ from . import cache_utils self.original_cache_compress = cache_utils.CACHE_COMPRESS cache_utils.CACHE_COMPRESS = None
Record the original cache compression method and turn it off.
__enter__
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
def __exit__(self, exc_type, exc_val, exc_tb): """ Restore the original cache compression method. """ from . import cache_utils cache_utils.CACHE_COMPRESS = self.original_cache_compress
Restore the original cache compression method.
__exit__
python
modelscope/data-juicer
data_juicer/utils/compress.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/compress.py
Apache-2.0
async def follow_read( logfile_path: str, skip_existing_content: bool = False, ) -> AsyncGenerator: """Read a file in online and iterative manner Args: logfile_path (`str`): The file path to be read. skip_existing_content (`bool`, defaults to `False): If True, re...
Read a file in online and iterative manner Args: logfile_path (`str`): The file path to be read. skip_existing_content (`bool`, defaults to `False): If True, read from the end, otherwise read from the beginning. Returns: One line string of the file content.
follow_read
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def find_files_with_suffix( path: Union[str, Path], suffixes: Union[str, List[str], None] = None) -> Dict[str, List[str]]: """ Traverse a path to find all files with the specified suffixes. :param path: path (str/Path): source path :param suffixes: specified file suffixes, '.txt' or ['....
Traverse a path to find all files with the specified suffixes. :param path: path (str/Path): source path :param suffixes: specified file suffixes, '.txt' or ['.txt', '.md'] etc :return: list of all files with the specified suffixes
find_files_with_suffix
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def add_suffix_to_filename(filename, suffix): """ Add a suffix to the filename. Only regard the content after the last dot as the file extension. E.g. 1. abc.jpg + "_resized" --> abc_resized.jpg 2. edf.xyz.csv + "_processed" --> edf.xyz_processed.csv 3. /path/to/file.json + "_suf" --> /path/...
Add a suffix to the filename. Only regard the content after the last dot as the file extension. E.g. 1. abc.jpg + "_resized" --> abc_resized.jpg 2. edf.xyz.csv + "_processed" --> edf.xyz_processed.csv 3. /path/to/file.json + "_suf" --> /path/to/file_suf.json 4. ds.tar.gz + "_whoops" --> ds....
add_suffix_to_filename
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def create_directory_if_not_exists(directory_path): """ create a directory if not exists, this function is process safe :param directory_path: directory path to be create """ directory_path = os.path.abspath(directory_path) try: os.makedirs(directory_path, exist_ok=True) exc...
create a directory if not exists, this function is process safe :param directory_path: directory path to be create
create_directory_if_not_exists
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def transfer_data_dir(original_dir, op_name): """ Transfer the original multimodal data dir to a new dir to store the newly generated multimodal data. The pattern is `{original_dir}/__dj__produced_data__/{op_name}` """ new_dir = os.path.join(original_dir, f'{Fields.mul...
Transfer the original multimodal data dir to a new dir to store the newly generated multimodal data. The pattern is `{original_dir}/__dj__produced_data__/{op_name}`
transfer_data_dir
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def transfer_filename(original_filepath: Union[str, Path], op_name, **op_kwargs): """ According to the op and hashing its parameters 'op_kwargs' addition to the process id and current time as the 'hash_val', map the original_filepath to another unique file path. E.g. ...
According to the op and hashing its parameters 'op_kwargs' addition to the process id and current time as the 'hash_val', map the original_filepath to another unique file path. E.g. 1. abc.jpg --> __dj__produced_data__/{op_name}/ abc__dj_hash_#{hash_...
transfer_filename
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def copy_data(from_dir, to_dir, data_path): """ Copy data from from_dir/data_path to to_dir/data_path. Return True if success. """ from_path = os.path.join(from_dir, data_path) to_path = os.path.join(to_dir, data_path) if not os.path.exists(from_path): return False parent...
Copy data from from_dir/data_path to to_dir/data_path. Return True if success.
copy_data
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def single_partition_write_with_filename( df: pd.DataFrame, output_file_dir: str, keep_filename_column: bool = False, output_type: str = 'jsonl', ) -> pd.Series: """ This function processes a DataFrame and writes it to disk Args: df: A DataFrame. output_file_dir: The output ...
This function processes a DataFrame and writes it to disk Args: df: A DataFrame. output_file_dir: The output file path. keep_filename_column: Whether to keep or drop the "filename" column, if it exists. output_type="jsonl": The type of output file to write. Returns: ...
single_partition_write_with_filename
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def read_single_partition( files, filetype='jsonl', add_filename=False, input_meta: Union[str, dict] = None, columns: Optional[List[str]] = None, **kwargs, ) -> pd.DataFrame: """ This function reads a file with cuDF, sorts the columns of the DataFrame and adds a "filename" column. ...
This function reads a file with cuDF, sorts the columns of the DataFrame and adds a "filename" column. Args: files: The path to the jsonl files to read. add_filename: Whether to add a "filename" column to the DataFrame. input_meta: A dictionary or a string formatted as a dictionary...
read_single_partition
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def get_all_files_paths_under(root, recurse_subdirectories=True, followlinks=False): """ This function returns a list of all the files under a specified directory. Args: root: The path to the directory to read. recurse_subdirecties:...
This function returns a list of all the files under a specified directory. Args: root: The path to the directory to read. recurse_subdirecties: Whether to recurse into subdirectories. Please note that this can be slow for large number ...
get_all_files_paths_under
python
modelscope/data-juicer
data_juicer/utils/file_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/file_utils.py
Apache-2.0
def update_fingerprint(fingerprint, transform, transform_args): """ Combining various objects to update the fingerprint. """ hasher = Hasher() hasher.update(fingerprint) try: hasher.update(transform) except: # noqa various errors might raise here from pickle or dill if _CAC...
Combining various objects to update the fingerprint.
update_fingerprint
python
modelscope/data-juicer
data_juicer/utils/fingerprint_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/fingerprint_utils.py
Apache-2.0
def generate_fingerprint(ds, *args, **kwargs): """ Generate new fingerprints by using various kwargs of the dataset. """ if args: args = list(args) dataset_kwargs = {'shard': ds, 'function': args[0]} else: dataset_kwargs = {'shard': ds} dataset_kwargs.update(kwargs) ...
Generate new fingerprints by using various kwargs of the dataset.
generate_fingerprint
python
modelscope/data-juicer
data_juicer/utils/fingerprint_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/fingerprint_utils.py
Apache-2.0
def get_toml_file_path(): """Get the path to pyproject.toml file.""" try: # First try to find it in the installed package data with importlib.resources.path('py_data_juicer', 'pyproject.toml') as toml_path: return toml_path except (ImportErro...
Get the path to pyproject.toml file.
get_toml_file_path
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def get_uv_lock_path(): """Get the path to uv.lock file.""" try: # First try to find it in the installed package data with importlib.resources.path('py_data_juicer', 'uv.lock') as lock_path: return lock_path except (ImportError, FileNotFoundE...
Get the path to uv.lock file.
get_uv_lock_path
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def get_package_name(cls, module_name: str) -> str: """Convert a module name to its corresponding package name. Args: module_name: The name of the module (e.g., 'cv2', 'PIL') Returns: str: The corresponding package name (e.g., 'opencv-python', 'Pillow') """ ...
Convert a module name to its corresponding package name. Args: module_name: The name of the module (e.g., 'cv2', 'PIL') Returns: str: The corresponding package name (e.g., 'opencv-python', 'Pillow')
get_package_name
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def get_all_dependencies(cls): """ Get all dependencies, prioritizing uv.lock if available. Falls back to pyproject.toml if uv.lock is not found or fails to parse. Returns: dict: A dictionary mapping module names to their full package specifications e.g. {'n...
Get all dependencies, prioritizing uv.lock if available. Falls back to pyproject.toml if uv.lock is not found or fails to parse. Returns: dict: A dictionary mapping module names to their full package specifications e.g. {'numpy': 'numpy>=1.26.4,<2.0.0', 'pandas': '...
get_all_dependencies
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def check_packages(cls, package_specs, pip_args=None): """ Check if packages are installed and install them if needed. Args: package_specs: A list of package specifications to check/install. Can be package names or URLs (e.g., 'torch' or 'git+https://github...
Check if packages are installed and install them if needed. Args: package_specs: A list of package specifications to check/install. Can be package names or URLs (e.g., 'torch' or 'git+https://github.com/...') pip_args: Optional list of additional argum...
check_packages
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def _is_package_installed(package_name): """Check if a package is installed by attempting to import it.""" if '@' in package_name: package_name = package_name.split('@')[0] if '[' in package_name: package_name = package_name.split('[')[0] i...
Check if a package is installed by attempting to import it.
_is_package_installed
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def __init__(self, module_name: str, package_name: str = None, package_url: str = None, auto_install: bool = True): """ Initialize the LazyLoader. Args: module_name: The name of the module to import (e.g., 'cv2', 'r...
Initialize the LazyLoader. Args: module_name: The name of the module to import (e.g., 'cv2', 'ray.data', 'torchvision.models') package_name: The name of the pip package to install (e.g., 'opencv-python', 'ray', 'torchvision') If None, will use the base m...
__init__
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def _install_package(cls, package_spec, pip_args=None): """Install a package using uv if available, otherwise pip.""" # Print trace information for package installation logger.debug(f'Installing package: {package_spec}') # Get last 3 frames of the stack trace stack = traceback.ex...
Install a package using uv if available, otherwise pip.
_install_package
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def _load(self): """Load the module and handle any missing dependencies.""" logger.debug(f'Loading {self._module_name}...') if self._module is not None: return self._module try: # Try to import the module directly first self._module = importlib.impor...
Load the module and handle any missing dependencies.
_load
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def __getattr__(self, item): """Handle attribute access, including submodule imports.""" if self._module is None: self._load() # Try to get the attribute directly try: return getattr(self._module, item) except AttributeError: # If not found, t...
Handle attribute access, including submodule imports.
__getattr__
python
modelscope/data-juicer
data_juicer/utils/lazy_loader.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/lazy_loader.py
Apache-2.0
def get_caller_name(depth=0): """ Get caller name by depth. :param depth: depth of caller context, use 0 for caller depth. :return: module name of the caller """ # the following logic is a little bit faster than inspect.stack() logic frame = inspect.currentframe().f_back for _ in range(...
Get caller name by depth. :param depth: depth of caller context, use 0 for caller depth. :return: module name of the caller
get_caller_name
python
modelscope/data-juicer
data_juicer/utils/logger_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/logger_utils.py
Apache-2.0
def __init__(self, level='INFO', caller_names=('datasets', 'logging')): """ Initialization method. :param level: log level string of loguru. Default value: "INFO". :param caller_names: caller names of redirected module. Default value: (apex, pycocotools). """...
Initialization method. :param level: log level string of loguru. Default value: "INFO". :param caller_names: caller names of redirected module. Default value: (apex, pycocotools).
__init__
python
modelscope/data-juicer
data_juicer/utils/logger_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/logger_utils.py
Apache-2.0
def redirect_sys_output(log_level='INFO'): """ Redirect stdout/stderr to loguru with log level. :param log_level: log level string of loguru. Default value: "INFO". """ redirect_logger = StreamToLoguru(level=log_level) sys.stderr = redirect_logger sys.stdout = redirect_logger
Redirect stdout/stderr to loguru with log level. :param log_level: log level string of loguru. Default value: "INFO".
redirect_sys_output
python
modelscope/data-juicer
data_juicer/utils/logger_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/logger_utils.py
Apache-2.0
def get_log_file_path(): """ Get the path to the location of the log file. :return: a location of log file. """ for _, handler in logger._core.handlers.items(): if isinstance(handler._sink, FileSink): return handler._sink._file.name
Get the path to the location of the log file. :return: a location of log file.
get_log_file_path
python
modelscope/data-juicer
data_juicer/utils/logger_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/logger_utils.py
Apache-2.0
def setup_logger(save_dir, distributed_rank=0, filename='log.txt', mode='o', level='INFO', redirect=True): """ Setup logger for training and testing. :param save_dir: location to save log file :param distributed_rank: ...
Setup logger for training and testing. :param save_dir: location to save log file :param distributed_rank: device rank when multi-gpu environment :param filename: log file name to save :param mode: log file write mode, `append` or `override`. default is `o`. :param level: log severity level. I...
setup_logger
python
modelscope/data-juicer
data_juicer/utils/logger_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/logger_utils.py
Apache-2.0
def __enter__(self): """ Store the original standard output and redirect the standard output to null when entering this range. """ self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w')
Store the original standard output and redirect the standard output to null when entering this range.
__enter__
python
modelscope/data-juicer
data_juicer/utils/logger_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/logger_utils.py
Apache-2.0
def __exit__(self, exc_type, exc_val, exc_tb): """ Close the redirected standard output and restore it when exiting from this range. """ sys.stdout.close() sys.stdout = self._original_stdout
Close the redirected standard output and restore it when exiting from this range.
__exit__
python
modelscope/data-juicer
data_juicer/utils/logger_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/logger_utils.py
Apache-2.0
def load_data_with_context(sample, context, loaded_data_keys, load_func): """ The unified loading function with contexts for multimodal data. """ data = {} for loaded_data_key in loaded_data_keys: if context and loaded_data_key in sample[Fields.context]: # load from context ...
The unified loading function with contexts for multimodal data.
load_data_with_context
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def calculate_resized_dimensions( original_size: Tuple[PositiveInt, PositiveInt], target_size: Union[PositiveInt, Tuple[PositiveInt, PositiveInt]], max_length: Optional[int] = None, divisible: PositiveInt = 1) -> Tuple[int, int]: """ Resize dimensions based on specified constrain...
Resize dimensions based on specified constraints. :param original_size: The original dimensions as (height, width). :param target_size: Desired target size; can be a single integer (short edge) or a tuple (height, width). :param max_length: Maximum allowed length for the longer edge. :para...
calculate_resized_dimensions
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def load_video(path, mode='r'): """ Load a video using its path. :param path: the path to this video. :param mode: the loading mode. It's "r" in default. :return: a container object form PyAv library, which contains all streams in this video (video/audio/...) and can be used to decode these...
Load a video using its path. :param path: the path to this video. :param mode: the loading mode. It's "r" in default. :return: a container object form PyAv library, which contains all streams in this video (video/audio/...) and can be used to decode these streams to frames.
load_video
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def get_video_duration(input_video: Union[str, av.container.InputContainer], video_stream_index: int = 0): """ Get the video's duration from the container :param input_video: the container object form PyAv library, which contains all streams in this video (video/audio/...) an...
Get the video's duration from the container :param input_video: the container object form PyAv library, which contains all streams in this video (video/audio/...) and can be used to decode these streams to frames. :param video_stream_index: the video stream index to decode, default...
get_video_duration
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def get_decoded_frames_from_video( input_video: Union[str, av.container.InputContainer], video_stream_index: int = 0): """ Get the video's frames from the container :param input_video: the container object form PyAv library, which contains all streams in this video (video/audio/...)...
Get the video's frames from the container :param input_video: the container object form PyAv library, which contains all streams in this video (video/audio/...) and can be used to decode these streams to frames. :param video_stream_index: the video stream index to decode, default s...
get_decoded_frames_from_video
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def cut_video_by_seconds( input_video: Union[str, av.container.InputContainer], output_video: str, start_seconds: float, end_seconds: Optional[float] = None, ): """ Cut a video into several segments by times in second. :param input_video: the path to input video or the video container. ...
Cut a video into several segments by times in second. :param input_video: the path to input video or the video container. :param output_video: the path to output video. :param start_seconds: the start time in second. :param end_seconds: the end time in second. If it's None, this function w...
cut_video_by_seconds
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def process_each_frame(input_video: Union[str, av.container.InputContainer], output_video: str, frame_func): """ Process each frame in video by replacing each frame by `frame_func(frame)`. :param input_video: the path to input video or the video container. :param output_video...
Process each frame in video by replacing each frame by `frame_func(frame)`. :param input_video: the path to input video or the video container. :param output_video: the path to output video. :param frame_func: a function which inputs a frame and outputs another frame.
process_each_frame
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def extract_key_frames_by_seconds( input_video: Union[str, av.container.InputContainer], duration: float = 1): """Extract key frames by seconds. :param input_video: input video path or av.container.InputContainer. :param duration: duration of each video split in seconds. """ ...
Extract key frames by seconds. :param input_video: input video path or av.container.InputContainer. :param duration: duration of each video split in seconds.
extract_key_frames_by_seconds
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def extract_key_frames(input_video: Union[str, av.container.InputContainer]): """ Extract key frames from the input video. If there is no keyframes in the video, return the first frame. :param input_video: input video path or container. :return: a list of key frames. """ # load the input vi...
Extract key frames from the input video. If there is no keyframes in the video, return the first frame. :param input_video: input video path or container. :return: a list of key frames.
extract_key_frames
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def get_key_frame_seconds(input_video: Union[str, av.container.InputContainer]): """ Get seconds of key frames in the input video. """ key_frames = extract_key_frames(input_video) ts = [float(f.pts * f.time_base) for f in key_frames] ts.sort() ret...
Get seconds of key frames in the input video.
get_key_frame_seconds
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def extract_video_frames_uniformly_by_seconds( input_video: Union[str, av.container.InputContainer], frame_num: PositiveInt, duration: float = 1): """Extract video frames uniformly by seconds. :param input_video: input video path or av.container.InputContainer. :param frame_n...
Extract video frames uniformly by seconds. :param input_video: input video path or av.container.InputContainer. :param frame_num: the number of frames to be extracted uniformly from each video split by duration. :param duration: duration of each video split in seconds.
extract_video_frames_uniformly_by_seconds
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def extract_video_frames_uniformly( input_video: Union[str, av.container.InputContainer], frame_num: PositiveInt, ): """ Extract a number of video frames uniformly within the video duration. :param input_video: input video path or container. :param frame_num: The number of frames to be extracte...
Extract a number of video frames uniformly within the video duration. :param input_video: input video path or container. :param frame_num: The number of frames to be extracted. If it's 1, only the middle frame will be extracted. If it's 2, only the first and the last frames will be extract...
extract_video_frames_uniformly
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def extract_audio_from_video( input_video: Union[str, av.container.InputContainer], output_audio: Optional[str] = None, start_seconds: int = 0, end_seconds: Optional[int] = None, stream_indexes: Union[int, List[int], None] = None, ): """ Extract audio data for the given video. :param in...
Extract audio data for the given video. :param input_video: input video. Can be a video path or an av.container.InputContainer. :param output_audio: output audio path. If it's None, the audio data won't be written to file. If stream_indexes is not None, it will output multiple audi...
extract_audio_from_video
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def timecode_string_to_seconds(timecode: str): """ Convert a timecode string to the float seconds. :param timecode: the input timecode string. Must in "HH:MM:SS.fff(fff)" format. """ # parse the timecode string dt = datetime.datetime.strptime(timecode, '%H:%M:%S.%f') # compute the ...
Convert a timecode string to the float seconds. :param timecode: the input timecode string. Must in "HH:MM:SS.fff(fff)" format.
timecode_string_to_seconds
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def parse_string_to_roi(roi_string, roi_type='pixel'): """ Convert a roi string to four number x1, y1, x2, y2 stand for the region. When the type is 'pixel', (x1, y1), (x2, y2) are the locations of pixels in the top left corner and the bottom right corner respectively. If the roi_type is 'ratio', th...
Convert a roi string to four number x1, y1, x2, y2 stand for the region. When the type is 'pixel', (x1, y1), (x2, y2) are the locations of pixels in the top left corner and the bottom right corner respectively. If the roi_type is 'ratio', the coordinates are normalized by widths and heights. :...
parse_string_to_roi
python
modelscope/data-juicer
data_juicer/utils/mm_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/mm_utils.py
Apache-2.0
def check_model(model_name, force=False): """ Check whether a model exists in DATA_JUICER_MODELS_CACHE. If exists, return its full path. Else, download it from cached models links. :param model_name: a specified model name :param force: Whether to download model forcefully or not, Sometimes ...
Check whether a model exists in DATA_JUICER_MODELS_CACHE. If exists, return its full path. Else, download it from cached models links. :param model_name: a specified model name :param force: Whether to download model forcefully or not, Sometimes the model file maybe incomplete for some rea...
check_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def filter_arguments(func, args_dict): """ Filters and returns only the valid arguments for a given function signature. :param func: The function or callable to inspect. :param args_dict: A dictionary of argument names and values to filter. :return: A dictionary containing only the arguments th...
Filters and returns only the valid arguments for a given function signature. :param func: The function or callable to inspect. :param args_dict: A dictionary of argument names and values to filter. :return: A dictionary containing only the arguments that match the function's signat...
filter_arguments
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def __init__(self, model, endpoint=None, response_path=None, **kwargs): """ Initializes an instance of the APIModel class. :param model: The name of the model to be used for making API calls. This should correspond to a valid model identifier recognized by the API server...
Initializes an instance of the APIModel class. :param model: The name of the model to be used for making API calls. This should correspond to a valid model identifier recognized by the API server. :param endpoint: The URL endpoint for the API. If provided as a ...
__init__
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def __call__(self, messages, **kwargs): """ Sends messages to the configured API model and returns the parsed response content. :param messages: A list of message dictionaries to send to the API. Each message should have a 'role' (e.g., 'user', ...
Sends messages to the configured API model and returns the parsed response content. :param messages: A list of message dictionaries to send to the API. Each message should have a 'role' (e.g., 'user', 'assistant') and 'content' (the message tex...
__call__
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def __init__(self, model, endpoint=None, response_path=None, **kwargs): """ Initializes an instance specialized for embedding APIs. :param model: The model identifier for embedding API calls. :param endpoint: API endpoint URL. Defaults to '/embeddings'. :param response_path: Pat...
Initializes an instance specialized for embedding APIs. :param model: The model identifier for embedding API calls. :param endpoint: API endpoint URL. Defaults to '/embeddings'. :param response_path: Path to extract embeddings from response. Defaults to 'data.0.embedding'. ...
__init__
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def __call__(self, input, **kwargs): """ Processes input text and returns embeddings. :param input: Input text or list of texts to embed. :param kwargs: Additional API parameters. :return: Extracted embeddings or empty list on error. """ body = { 'mod...
Processes input text and returns embeddings. :param input: Input text or list of texts to embed. :param kwargs: Additional API parameters. :return: Extracted embeddings or empty list on error.
__call__
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_api_model(model, *, endpoint=None, response_path=None, return_processor=False, processor_config=None, **model_params): """Creates a callable API model for interacting with ...
Creates a callable API model for interacting with OpenAI-compatible API. The callable supports custom response parsing and works with proxy servers that may be incompatible. :param model: The name of the model to interact with. :param endpoint: The URL endpoint for the API. If provided as a relative ...
prepare_api_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_diffusion_model(pretrained_model_name_or_path, diffusion_type, **model_params): """ Prepare and load an Diffusion model from HuggingFace. :param pretrained_model_name_or_path: input Diffusion model name or local path to the model :param diffusion_type: th...
Prepare and load an Diffusion model from HuggingFace. :param pretrained_model_name_or_path: input Diffusion model name or local path to the model :param diffusion_type: the use of the diffusion model. It can be 'image2image', 'text2image', 'inpainting' :return: a Diffusion model.
prepare_diffusion_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_fasttext_model(model_name='lid.176.bin', **model_params): """ Prepare and load a fasttext model. :param model_name: input model name :return: model instance. """ logger.info('Loading fasttext language identification model...') try: # Suppress FastText warnings by redirec...
Prepare and load a fasttext model. :param model_name: input model name :return: model instance.
prepare_fasttext_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_huggingface_model(pretrained_model_name_or_path, *, return_model=True, return_pipe=False, pipe_task='text-generation', **model_params): """ Prepare an...
Prepare and load a huggingface model. :param pretrained_model_name_or_path: model name or path :param return_model: return model or not :param return_pipe: return pipeline or not :param pipe_task: task for pipeline :return: a tuple (model, processor) if `return_model` is True; otherwis...
prepare_huggingface_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_kenlm_model(lang, name_pattern='{}.arpa.bin', **model_params): """ Prepare and load a kenlm model. :param model_name: input model name in formatting syntax. :param lang: language to render model name :return: model instance. """ model_params.pop('device', None) model_name =...
Prepare and load a kenlm model. :param model_name: input model name in formatting syntax. :param lang: language to render model name :return: model instance.
prepare_kenlm_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_nltk_model(lang, name_pattern='punkt.{}.pickle', **model_params): """ Prepare and load a nltk punkt model with enhanced resource handling. :param model_name: input model name in formatting syntax :param lang: language to render model name :return: model instance. """ model_param...
Prepare and load a nltk punkt model with enhanced resource handling. :param model_name: input model name in formatting syntax :param lang: language to render model name :return: model instance.
prepare_nltk_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_nltk_pos_tagger(**model_params): """ Prepare and load NLTK's part-of-speech tagger with enhanced resource handling. :return: The POS tagger model """ model_params.pop('device', None) # Ensure pickle security is patched patch_nltk_pickle_security() logger.info('Loadin...
Prepare and load NLTK's part-of-speech tagger with enhanced resource handling. :return: The POS tagger model
prepare_nltk_pos_tagger
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_recognizeAnything_model( pretrained_model_name_or_path='ram_plus_swin_large_14m.pth', input_size=384, **model_params): """ Prepare and load recognizeAnything model. :param model_name: input model name. :param input_size: the input size of the model. """ logge...
Prepare and load recognizeAnything model. :param model_name: input model name. :param input_size: the input size of the model.
prepare_recognizeAnything_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_sentencepiece_model(model_path, **model_params): """ Prepare and load a sentencepiece model. :param model_path: input model path :return: model instance """ logger.info('Loading sentencepiece model...') sentencepiece_model = sentencepiece.SentencePieceProcessor() try: ...
Prepare and load a sentencepiece model. :param model_path: input model path :return: model instance
prepare_sentencepiece_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_sentencepiece_for_lang(lang, name_pattern='{}.sp.model', **model_params): """ Prepare and load a sentencepiece model for specific language. :param lang: language to render model name :param name_pattern: pattern to render...
Prepare and load a sentencepiece model for specific language. :param lang: language to render model name :param name_pattern: pattern to render the model name :return: model instance.
prepare_sentencepiece_for_lang
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0
def prepare_simple_aesthetics_model(pretrained_model_name_or_path, *, return_model=True, **model_params): """ Prepare and load a simple aesthetics model. :param pretrained_model_name_or_path: model n...
Prepare and load a simple aesthetics model. :param pretrained_model_name_or_path: model name or path :param return_model: return model or not :return: a tuple (model, input processor) if `return_model` is True; otherwise, only the processor is returned.
prepare_simple_aesthetics_model
python
modelscope/data-juicer
data_juicer/utils/model_utils.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/utils/model_utils.py
Apache-2.0