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 _process_single_sample(self, ori_sample, rank=None): """ :param ori_sample: a single data sample before applying generation :return: batched results after generation """ # there is no image in this sample if self.image_key not in ori_sample or \ not o...
:param ori_sample: a single data sample before applying generation :return: batched results after generation
_process_single_sample
python
modelscope/data-juicer
data_juicer/ops/mapper/image_captioning_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_captioning_mapper.py
Apache-2.0
def process_batched(self, samples, rank=None): """ Note: This is a batched_OP, whose input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote caption_num as $M$. the number of total samples after gener...
Note: This is a batched_OP, whose input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote caption_num as $M$. the number of total samples after generation is $2Nb$ for 'random_any' and 'similar_o...
process_batched
python
modelscope/data-juicer
data_juicer/ops/mapper/image_captioning_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_captioning_mapper.py
Apache-2.0
def _process_single_sample(self, ori_sample, rank=None, context=False): """ :param ori_sample: a single data sample before applying generation :return: batched results after generation """ # there is no image in this sample if self.image_key not in ori_sample or \ ...
:param ori_sample: a single data sample before applying generation :return: batched results after generation
_process_single_sample
python
modelscope/data-juicer
data_juicer/ops/mapper/image_diffusion_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_diffusion_mapper.py
Apache-2.0
def process_batched(self, samples, rank=None, context=False): """ Note: This is a batched_OP, whose the input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote aug_num as $M$. the ...
Note: This is a batched_OP, whose the input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote aug_num as $M$. the number of total samples after generation is $(1+M)Nb$. :par...
process_batched
python
modelscope/data-juicer
data_juicer/ops/mapper/image_diffusion_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_diffusion_mapper.py
Apache-2.0
def __init__(self, cv_classifier: str = '', blur_type: str = 'gaussian', radius: NonNegativeFloat = 2, *args, **kwargs): """ Initialization method. :param cv_classifier: OpenCV classifier path for face detectio...
Initialization method. :param cv_classifier: OpenCV classifier path for face detection. By default, we will use 'haarcascade_frontalface_alt.xml'. :param blur_type: Type of blur kernel, including ['mean', 'box', 'gaussian']. :param radius: Radius of blur kernel....
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/image_face_blur_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_face_blur_mapper.py
Apache-2.0
def __init__(self, alpha_matting: bool = False, alpha_matting_foreground_threshold: int = 240, alpha_matting_background_threshold: int = 10, alpha_matting_erode_size: int = 10, bgcolor: Optional[Tuple[int, int, int, int]] = None, ...
Initialization method. alpha_matting (bool, optional): Flag indicating whether to use alpha matting. Defaults to False. alpha_matting_foreground_threshold (int, optional): Foreground threshold for alpha matting. Defaults to 240. alpha_matting_background_threshol...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/image_remove_background_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_remove_background_mapper.py
Apache-2.0
def __init__(self, imgsz=1024, conf=0.05, iou=0.5, model_path='FastSAM-x.pt', *args, **kwargs): """ Initialization method. :param imgsz: resolution for image resizing :param conf: confi...
Initialization method. :param imgsz: resolution for image resizing :param conf: confidence score threshold :param iou: IoU (Intersection over Union) score threshold :param model_path: the path to the FastSAM model. Model name should be one of ['FastSAM-x.pt', 'FastS...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/image_segment_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_segment_mapper.py
Apache-2.0
def __init__(self, tag_field_name: str = MetaKeys.image_tags, *args, **kwargs): """ Initialization method. :param tag_field_name: the field name to store the tags. It's "image_tags" in default. :param args: extra args ...
Initialization method. :param tag_field_name: the field name to store the tags. It's "image_tags" in default. :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/image_tagging_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/image_tagging_mapper.py
Apache-2.0
def __init__(self, hf_model: str = 'llava-hf/llava-v1.6-vicuna-7b-hf', max_new_tokens=256, temperature=0.2, top_p=None, num_beams=1, *args, **kwargs): """ Initialization method. ...
Initialization method. :param hf_model: hugginface model id. :param max_new_tokens: the maximum number of new tokens generated by the model. :param temperature: used to control the randomness of generated text. The higher the temperature, the more ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/mllm_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/mllm_mapper.py
Apache-2.0
def __init__(self, sequential: bool = False, aug_num: PositiveInt = 1, keep_original_sample: bool = True, delete_random_word: bool = False, swap_random_word: bool = False, spelling_error_word: bool = False, ...
Initialization method. All augmentation methods use default parameters in default. We recommend you to only use 1-3 augmentation methods at a time. Otherwise, the semantics of samples might be changed significantly. :param sequential: whether combine all augmentation methods to...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/nlpaug_en_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/nlpaug_en_mapper.py
Apache-2.0
def __init__(self, hf_model: str = 'Qwen/Qwen2.5-7B-Instruct', *, system_prompt: Optional[str] = None, input_template: Optional[str] = None, qa_pair_template: Optional[str] = None, output_pattern: Optional[str] = None,...
Initialization method. :param hf_model: Hugging Face model ID. :param system_prompt: System prompt for guiding the optimization task. :param input_template: Template for building the input for the model. Please make sure the template contains one placeholder '{}', which ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/optimize_qa_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/optimize_qa_mapper.py
Apache-2.0
def __init__(self, api_model: str = 'gpt-4o', *, api_endpoint: Optional[str] = None, response_path: Optional[str] = None, system_prompt: Optional[str] = None, input_template: Optional[str] = None, outp...
Initialization method. :param api_model: API model name. :param api_endpoint: URL endpoint for the API. :param response_path: Path to extract content from the API response. Defaults to 'choices.0.message.content'. :param system_prompt: System prompt for guiding the ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/pair_preference_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/pair_preference_mapper.py
Apache-2.0
def __init__(self, file_path: str = '', function_name: str = 'process_single', batched: bool = False, **kwargs): """ Initialization method. :param file_path: The path to the Python file containing the function to be...
Initialization method. :param file_path: The path to the Python file containing the function to be executed. :param function_name: The name of the function defined in the file to be executed. :param batched: A boolean indicating whether to process input data in ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/python_file_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/python_file_mapper.py
Apache-2.0
def process_single(self, sample): """Invoke the loaded function with the provided sample.""" result = self.func(sample) if not isinstance(result, dict): raise ValueError( f'Function must return a dictionary, got {type(result).__name__} instead.' # noqa: E501 ...
Invoke the loaded function with the provided sample.
process_single
python
modelscope/data-juicer
data_juicer/ops/mapper/python_file_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/python_file_mapper.py
Apache-2.0
def process_batched(self, samples): """Invoke the loaded function with the provided samples.""" result = self.func(samples) if not isinstance(result, dict): raise ValueError( f'Function must return a dictionary, got {type(result).__name__} instead.' # noqa: E501 ...
Invoke the loaded function with the provided samples.
process_batched
python
modelscope/data-juicer
data_juicer/ops/mapper/python_file_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/python_file_mapper.py
Apache-2.0
def __init__(self, lambda_str: str = '', batched: bool = False, **kwargs): """ Initialization method. :param lambda_str: A string representation of the lambda function to be executed on data samples. If empty, the identity function is used. :param batched: A boolean indicati...
Initialization method. :param lambda_str: A string representation of the lambda function to be executed on data samples. If empty, the identity function is used. :param batched: A boolean indicating whether to process input data in batches. :param kwargs: Additi...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/python_lambda_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/python_lambda_mapper.py
Apache-2.0
def __init__( self, hf_model: str = 'bespin-global/klue-roberta-small-3i4k-intent-classification', # noqa: E501 E131 zh_to_en_hf_model: Optional[str] = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, ...
Initialization method. :param hf_model: Huggingface model ID to predict intent label. :param zh_to_en_hf_model: Translation model from Chinese to English. If not None, translate the query from Chinese to English. :param model_params: model param for hf_model. :param...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/query_intent_detection_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/query_intent_detection_mapper.py
Apache-2.0
def __init__( self, hf_model: str = 'mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis', # noqa: E501 E131 zh_to_en_hf_model: Optional[str] = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, ...
Initialization method. :param hf_model: Huggingface model ID to predict sentiment label. :param zh_to_en_hf_model: Translation model from Chinese to English. If not None, translate the query from Chinese to English. :param model_params: model param for hf_model. :pa...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/query_sentiment_detection_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/query_sentiment_detection_mapper.py
Apache-2.0
def __init__( self, hf_model: str = 'dstefa/roberta-base_topic_classification_nyt_news', # noqa: E501 E131 zh_to_en_hf_model: Optional[str] = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, *, ...
Initialization method. :param hf_model: Huggingface model ID to predict topic label. :param zh_to_en_hf_model: Translation model from Chinese to English. If not None, translate the query from Chinese to English. :param model_params: model param for hf_model. :param ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/query_topic_detection_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/query_topic_detection_mapper.py
Apache-2.0
def __init__(self, api_model: str = 'gpt-4o', source_entity: str = None, target_entity: str = None, *, output_key: str = MetaKeys.role_relation, api_endpoint: Optional[str] = None, response_path: Optio...
Initialization method. :param api_model: API model name. :param source_entity: The source entity of the relation to be identified. :param target_entity: The target entity of the relation to be identified. :param output_key: The output key in the meta fiel...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/relation_identity_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/relation_identity_mapper.py
Apache-2.0
def __init__(self, *args, **kwargs): """ Initialization method. :param args: extra args :param kwargs: extra args """ super().__init__(*args, **kwargs) self.pattern = r'(\\appendix|' self.pattern += r'\\begin\{references\}|' self.pattern += r'\\be...
Initialization method. :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/remove_bibliography_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/remove_bibliography_mapper.py
Apache-2.0
def __init__(self, doc_type: Union[str, List[str]] = 'tex', inline: bool = True, multiline: bool = True, *args, **kwargs): """ Initialization method. :param doc_type: Type of document to remove comments. ...
Initialization method. :param doc_type: Type of document to remove comments. :param inline: Whether to remove inline comments. :param multiline: Whether to remove multiline comments. :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/remove_comments_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/remove_comments_mapper.py
Apache-2.0
def __init__(self, drop_no_head: bool = True, *args, **kwargs): """ Initialization method. :param drop_no_head: whether to drop sample texts without headers. :param args: extra args :param kwargs: extra args """ super().__init__(*args, **kwargs) ...
Initialization method. :param drop_no_head: whether to drop sample texts without headers. :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/remove_header_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/remove_header_mapper.py
Apache-2.0
def __init__(self, min_len: int = 1, max_len: int = sys.maxsize, *args, **kwargs): """ Initialization method. :param min_len: The min mapper word length in this op, words will be filtered if their length is below th...
Initialization method. :param min_len: The min mapper word length in this op, words will be filtered if their length is below this parameter. :param max_len: The max mapper word length in this op, words will be filtered if their length exceeds this parameter. :p...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/remove_long_words_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/remove_long_words_mapper.py
Apache-2.0
def __init__(self, lowercase: bool = False, ignore_special_character: bool = True, min_repeat_sentence_length: int = 2, *args, **kwargs): """ Initialization method. :param lowercase: Whether to convert sample t...
Initialization method. :param lowercase: Whether to convert sample text to lower case :param ignore_special_character: Whether to ignore special characters when judging repeated sentences. Special characters are all characters except Chinese characters, letters and ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/remove_repeat_sentences_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/remove_repeat_sentences_mapper.py
Apache-2.0
def __init__(self, min_col: Annotated[int, Field(ge=2, le=20)] = 2, max_col: Annotated[int, Field(ge=2, le=20)] = 20, *args, **kwargs): """ Initialization method. :param min_col: The min number of columns of table to remove. ...
Initialization method. :param min_col: The min number of columns of table to remove. :param max_col: The max number of columns of table to remove. :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/remove_table_text_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/remove_table_text_mapper.py
Apache-2.0
def __init__(self, lang: str = 'en', tokenization: bool = False, substrings: Optional[List[str]] = None, *args, **kwargs): """ Initialization method. :param lang: sample in which language :param tokeniz...
Initialization method. :param lang: sample in which language :param tokenization: whether to use model to tokenize documents :param substrings: The incorrect substrings in words. :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/remove_words_with_incorrect_substrings_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/remove_words_with_incorrect_substrings_mapper.py
Apache-2.0
def __init__(self, pattern: Union[str, List[str], None] = None, repl: Union[str, List[str]] = '', *args, **kwargs): """ Initialization method. :param pattern: regular expression pattern(s) to search for within text :par...
Initialization method. :param pattern: regular expression pattern(s) to search for within text :param repl: replacement string(s), default is empty string :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/replace_content_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/replace_content_mapper.py
Apache-2.0
def __init__( self, hf_diffusion: str = 'stabilityai/stable-diffusion-xl-base-1.0', trust_remote_code=False, torch_dtype: str = 'fp32', num_inference_steps: float = 50, guidance_scale: float = 7.5, text_key=None, text_key_se...
Initialization method. :param hf_diffusion: diffusion model name on huggingface to generate the image. :param torch_dtype: the floating point type used to load the diffusion model. :param num_inference_steps: The larger the value, the better the image ge...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/sdxl_prompt2prompt_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/sdxl_prompt2prompt_mapper.py
Apache-2.0
def __init__(self, hf_model: str = 'Qwen/Qwen2-7B-Instruct', system_prompt: str = None, task_sentence: str = None, max_new_tokens=256, temperature=0.2, top_p=None, num_beams=1, text_ke...
Initialization method. :param hf_model: Huggingface model id. :param system_prompt: System prompt. :param task_sentence: The instruction for the current task. :param max_new_tokens: the maximum number of new tokens generated by the model. :param temperature: ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/sentence_augmentation_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/sentence_augmentation_mapper.py
Apache-2.0
def __init__(self, lang: str = 'en', *args, **kwargs): """ Initialization method. :param lang: split sentence of text in which language. :param args: extra args :param kwargs: extra args """ super().__init__(*args, **kwargs) self.lang = lang # En...
Initialization method. :param lang: split sentence of text in which language. :param args: extra args :param kwargs: extra args
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/sentence_split_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/sentence_split_mapper.py
Apache-2.0
def __init__(self, max_len: Union[PositiveInt, None] = None, split_pattern: Union[str, None] = r'\n\n', overlap_len: NonNegativeInt = 0, tokenizer: Union[str, None] = None, trust_remote_code: bool = False, *args, ...
Initialization method. :param max_len: Split text into multi texts with this max len if not None. :param split_pattern: Make sure split in this pattern if it is not None and force cut if the length exceeds max_len. :param overlap_len: Overlap length of the split...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/text_chunk_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/text_chunk_mapper.py
Apache-2.0
def __init__(self, keep_original_sample: bool = True, *args, **kwargs): """ Initialization method. :param keep_original_sample: whether to keep the original sample. If it's set to False, there will be only captioned sample in the final datasets and the original sample wi...
Initialization method. :param keep_original_sample: whether to keep the original sample. If it's set to False, there will be only captioned sample in the final datasets and the original sample will be removed. It's True in default. :param args: extra args ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_captioning_from_audio_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_captioning_from_audio_mapper.py
Apache-2.0
def __init__( self, hf_img2seq: str = 'Salesforce/blip2-opt-2.7b', trust_remote_code: bool = False, caption_num: PositiveInt = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: Optional[str] = None, prompt_key: Optional...
Initialization method. :param hf_img2seq: model name on huggingface to generate caption :param caption_num: how many candidate captions to generate for each video :param keep_candidate_mode: retain strategy for the generated $caption_num$ candidates. ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_captioning_from_frames_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_captioning_from_frames_mapper.py
Apache-2.0
def process_batched(self, samples, rank=None, context=False): """ :param samples: :return: Note: This is a batched_OP, whose the input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote caption_nu...
:param samples: :return: Note: This is a batched_OP, whose the input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote caption_num as $M$. the number of total samples after generation is $2N...
process_batched
python
modelscope/data-juicer
data_juicer/ops/mapper/video_captioning_from_frames_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_captioning_from_frames_mapper.py
Apache-2.0
def __init__(self, hf_summarizer: str = None, trust_remote_code: bool = False, consider_video_caption_from_video: bool = True, consider_video_caption_from_audio: bool = True, consider_video_caption_from_frames: bool = True, ...
Initialization method. :param hf_summarizer: the summarizer model used to summarize texts generated by other methods. :param consider_video_caption_from_video: whether to consider the video caption generated from video directly in the summarization process. ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_captioning_from_summarizer_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_captioning_from_summarizer_mapper.py
Apache-2.0
def __init__( self, hf_video_blip: str = 'kpyu/video-blip-opt-2.7b-ego4d', trust_remote_code: bool = False, caption_num: PositiveInt = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: Optional[str] = None, prompt_key: ...
Initialization method. :param hf_video_blip: video-blip model name on huggingface to generate caption :param caption_num: how many candidate captions to generate for each video :param keep_candidate_mode: retain strategy for the generated $caption_nu...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_captioning_from_video_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_captioning_from_video_mapper.py
Apache-2.0
def process_batched(self, samples, rank=None, context=False): """ :param samples: :return: Note: This is a batched_OP, whose the input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote caption_nu...
:param samples: :return: Note: This is a batched_OP, whose the input and output type are both list. Suppose there are $N$ input sample list with batch size as $b$, and denote caption_num as $M$. the number of total samples after generation is $2N...
process_batched
python
modelscope/data-juicer
data_juicer/ops/mapper/video_captioning_from_video_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_captioning_from_video_mapper.py
Apache-2.0
def __init__( self, frame_sampling_method: str = 'all_keyframes', frame_num: PositiveInt = 3, duration: float = 0, frame_dir: str = None, frame_key=MetaKeys.video_frames, *args, **kwargs, ): """ Initialization method. :param fra...
Initialization method. :param frame_sampling_method: sampling method of extracting frame videos from the videos. Should be one of ["all_keyframes", "uniform"]. The former one extracts all key frames (the number of which depends on the duration of the vide...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_extract_frames_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_extract_frames_mapper.py
Apache-2.0
def __init__(self, cv_classifier: str = '', blur_type: str = 'gaussian', radius: float = 2, *args, **kwargs): """ Initialization method. :param cv_classifier: OpenCV classifier path for face detection. ...
Initialization method. :param cv_classifier: OpenCV classifier path for face detection. By default, we will use 'haarcascade_frontalface_alt.xml'. :param blur_type: Type of blur kernel, including ['mean', 'box', 'gaussian']. :param radius: Radius of blur kernel....
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_face_blur_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_face_blur_mapper.py
Apache-2.0
def __init__( self, filter_name: Optional[str] = None, filter_kwargs: Optional[Dict] = None, global_args: Optional[List[str]] = None, capture_stderr: bool = True, overwrite_output: bool = True, *args, **kwargs, ): """ Initialization met...
Initialization method. :param filter_name: ffmpeg video filter name. :param filter_kwargs: keyword-arguments passed to ffmpeg filter. :param global_args: list-arguments passed to ffmpeg command-line. :param capture_stderr: whether to capture stderr. :param overwrite_out...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_ffmpeg_wrapped_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_ffmpeg_wrapped_mapper.py
Apache-2.0
def __init__(self, roi_strings: List[str] = ['0,0,0.1,0.1'], roi_type: str = 'ratio', roi_key: Optional[str] = None, frame_num: PositiveInt = 10, min_frame_threshold: PositiveInt = 7, detection_method: str = 'pixel_val...
Initialization method. :param roi_strings: a given list of regions the watermarks locate. The format of each can be "x1, y1, x2, y2", "(x1, y1, x2, y2)", or "[x1, y1, x2, y2]". :param roi_type: the roi string type. When the type is 'pixel', (x1, y1), (x2, y2...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_remove_watermark_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_remove_watermark_mapper.py
Apache-2.0
def __init__( self, min_ratio: str = '9/21', max_ratio: str = '21/9', strategy: str = 'increase', *args, **kwargs, ): """ Initialization method. :param min_ratio: The minimum aspect ratio to enforce videos with an aspect ratio belo...
Initialization method. :param min_ratio: The minimum aspect ratio to enforce videos with an aspect ratio below `min_ratio` will be resized to match this minimum ratio. The ratio should be provided as a string in the format "9:21" or "9/21". :param max_ratio:...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_resize_aspect_ratio_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_resize_aspect_ratio_mapper.py
Apache-2.0
def __init__(self, min_width: int = 1, max_width: int = sys.maxsize, min_height: int = 1, max_height: int = sys.maxsize, force_original_aspect_ratio: str = 'disable', force_divisible_by: PositiveInt = 2, ...
Initialization method. :param min_width: Videos with width less than 'min_width' will be mapped to videos with equal or bigger width. :param max_width: Videos with width more than 'max_width' will be mapped to videos with equal of smaller width. :param min_heigh...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_resize_resolution_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_resize_resolution_mapper.py
Apache-2.0
def __init__(self, split_duration: float = 10, min_last_split_duration: float = 0, keep_original_sample: bool = True, *args, **kwargs): """ Initialization method. :param split_duration: duration of each video s...
Initialization method. :param split_duration: duration of each video split in seconds. :param min_last_split_duration: The minimum allowable duration in seconds for the last video split. If the duration of the last split is less than this value, it will be discarded. ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_split_by_duration_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_split_by_duration_mapper.py
Apache-2.0
def __init__(self, keep_original_sample: bool = True, *args, **kwargs): """ Initialization method. :param keep_original_sample: whether to keep the original sample. If it's set to False, there will be only split sample in the final datasets and the original sample will b...
Initialization method. :param keep_original_sample: whether to keep the original sample. If it's set to False, there will be only split sample in the final datasets and the original sample will be removed. It's True in default. :param args: extra args ...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_split_by_key_frame_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_split_by_key_frame_mapper.py
Apache-2.0
def __init__(self, detector: str = 'ContentDetector', threshold: NonNegativeFloat = 27.0, min_scene_len: NonNegativeInt = 15, show_progress: bool = False, *args, **kwargs): """ Initialization method. ...
Initialization method. :param detector: Algorithm from `scenedetect.detectors`. Should be one of ['ContentDetector', 'ThresholdDetector', 'AdaptiveDetector`]. :param threshold: Threshold passed to the detector. :param min_scene_len: Minimum length of any scene. :par...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_split_by_scene_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_split_by_scene_mapper.py
Apache-2.0
def __init__(self, hf_ast: str = 'MIT/ast-finetuned-audioset-10-10-0.4593', trust_remote_code: bool = False, tag_field_name: str = MetaKeys.video_audio_tags, *args, **kwargs): """ Initialization method. :param ...
Initialization method. :param hf_ast: path to the HF model to tag from audios. :param trust_remote_code: whether to trust the remote code of HF models :param tag_field_name: the field name to store the tags. It's "video_audio_tags" in default. :param args: extra arg...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_tagging_from_audio_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_tagging_from_audio_mapper.py
Apache-2.0
def __init__(self, frame_sampling_method: str = 'all_keyframes', frame_num: PositiveInt = 3, tag_field_name: str = MetaKeys.video_frame_tags, *args, **kwargs): """ Initialization method. :param frame_sampling_m...
Initialization method. :param frame_sampling_method: sampling method of extracting frame images from the videos. Should be one of ["all_keyframes", "uniform"]. The former one extracts all key frames (the number of which depends on the duration of the vid...
__init__
python
modelscope/data-juicer
data_juicer/ops/mapper/video_tagging_from_frames_mapper.py
https://github.com/modelscope/data-juicer/blob/master/data_juicer/ops/mapper/video_tagging_from_frames_mapper.py
Apache-2.0
def __init__(self, project_name_prefix: str = 'DataJuicer_Annotation', wait_for_annotations: bool = False, timeout: int = 3600, poll_interval: int = 60, samples_per_task: int = 1, max_tasks_per_batch: int = 100, ...
Initialize the base annotation operation Args: project_name_prefix: Prefix for the project name project_id: ID of existing project (if None, creates new project) wait_for_annotations: Whether to wait for annotations to complete timeout: Maximum time to wait for a...
__init__
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 _handle_task_created(self, data): """Handle task created event with notification""" task_id = data.get('task_id') sample_ids = data.get('sample_ids', []) logger.debug(f'Task {task_id} created with {len(sample_ids)} samples') # Send notification if configured if self...
Handle task created event with notification
_handle_task_created
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 _handle_batch_created(self, data): """Handle batch created event with notification""" batch_id = data.get('batch_id') task_count = data.get('task_count', 0) sample_count = data.get('sample_count', 0) logger.info( f'Batch {batch_id} created with {task_count} tasks...
Handle batch created event with notification
_handle_batch_created
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 _handle_annotation_completed(self, data): """Handle annotation completed event with notification""" task_id = data.get('task_id') annotation_id = data.get('annotation_id') logger.debug( f'Annotation {annotation_id} completed for task {task_id}') # Mark this task...
Handle annotation completed event with notification
_handle_annotation_completed
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 _handle_batch_annotation_completed(self, data): """Handle batch annotation completed event with notification""" batch_id = data.get('batch_id') task_count = data.get('task_count', 0) sample_count = data.get('sample_count', 0) if self.notification_events.get('batch_annotation...
Handle batch annotation completed event with notification
_handle_batch_annotation_completed
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 _create_tasks_batch(self, tasks_data: List[Dict], sample_ids: List[Any]) -> List[int]: """Create multiple tasks in the annotation platform Args: tasks_data: List of task data sample_ids: List of sample IDs corresponding to each task Retur...
Create multiple tasks in the annotation platform Args: tasks_data: List of task data sample_ids: List of sample IDs corresponding to each task Returns: List[int]: List of created task IDs
_create_tasks_batch
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 _process_annotation_result(self, annotation: Dict, sample: Dict) -> Dict: """Process annotation result and update the sample Args: annotation: The annotation result from the annotation platform sample: The original sample that was annotated...
Process annotation result and update the sample Args: annotation: The annotation result from the annotation platform sample: The original sample that was annotated Returns: Dict: The updated sample with annotation results
_process_annotation_result
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 process_batched(self, samples): """Process a batch of samples by creating annotation tasks Args: samples: Dictionary of samples to process (column-oriented) Returns: Dict: Processed samples (column-oriented) """ # Get dimensions of the data k...
Process a batch of samples by creating annotation tasks Args: samples: Dictionary of samples to process (column-oriented) Returns: Dict: Processed samples (column-oriented)
process_batched
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 _create_and_process_batch(self, tasks_data, task_sample_ids): """Create a batch of tasks and process the results""" if not tasks_data: return # Generate a batch ID batch_id = f'batch_{self.batch_counter}_{int(time.time())}' self.batch_counter += 1 # Flat...
Create a batch of tasks and process the results
_create_and_process_batch
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 _wait_for_batch_annotations(self, task_ids=None): """Wait for all tasks in a batch to be annotated. Args: task_ids: List of task IDs to wait for Returns: Dict: Mapping of task IDs to their annotations """ if not self.wait_for_annotations or not task_...
Wait for all tasks in a batch to be annotated. Args: task_ids: List of task IDs to wait for Returns: Dict: Mapping of task IDs to their annotations
_wait_for_batch_annotations
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, api_url: str = None, api_key: str = None, label_config: Optional[str] = None, **kwargs): """Initialize the Label Studio annotation operation Args: api_url: Base URL for Label Studio API api_ke...
Initialize the Label Studio annotation operation Args: api_url: Base URL for Label Studio API api_key: API key for authentication label_config: XML configuration for the labeling interface **kwargs: Additional parameters passed to BaseAnnotationMapper
__init__
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 setup_project(self): """Create a new project or use existing one""" try: # Create new project logger.info( f'Creating new Label Studio project: {self.project_name}') project = self.client.create_project( title=self.project_name, ...
Create a new project or use existing one
setup_project
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 _create_tasks_batch(self, tasks_data: List[Dict], sample_ids: List[Any]) -> List[int]: """Create multiple tasks in Label Studio Args: tasks_data: List of task data sample_ids: List of sample IDs corresponding to each task Returns: ...
Create multiple tasks in Label Studio Args: tasks_data: List of task data sample_ids: List of sample IDs corresponding to each task Returns: List[int]: List of created task IDs
_create_tasks_batch
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 _check_annotation_status(self, task_ids=None): """Check the status of annotations for the given task IDs Args: task_ids: List of task IDs to check. If None, uses all in batch Returns: Tuple[bool, Dict]: (has_changes, completed_tasks_dict) """ # Handl...
Check the status of annotations for the given task IDs Args: task_ids: List of task IDs to check. If None, uses all in batch Returns: Tuple[bool, Dict]: (has_changes, completed_tasks_dict)
_check_annotation_status
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_annotation(self, task_id: int) -> Optional[Dict]: """Get annotation for a task if available Args: task_id: ID of the task Returns: Optional[Dict]: Annotation data or None if not yet annotated """ try: # Get task with annotations...
Get annotation for a task if available Args: task_id: ID of the task Returns: Optional[Dict]: Annotation data or None if not yet annotated
_get_task_annotation
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_all_annotations(self) -> Dict[int, Dict]: """Get all annotations for tasks created by this operation Returns: Dict[int, Dict]: Dictionary mapping task IDs to annotations """ task_ids = list(self.task_to_samples.keys()) annotations = {} for task_id in...
Get all annotations for tasks created by this operation Returns: Dict[int, Dict]: Dictionary mapping task IDs to annotations
get_all_annotations
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 __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(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 gzip with open(input_path, 'rb') as ...
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( 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 compress( self, 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. """ self.compressor...
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 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 __init__(self, compressor_format: str = 'zstd'): """ Initialization method. :param compressor_format: compression format algorithms, default `zstd`. """ self.compressor_format = compressor_format self.compressor_extension = '.' + 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 _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