data_juicer.ops.mapper#

class data_juicer.ops.mapper.AudioAddGaussianNoiseMapper(min_amplitude: float = 0.001, max_amplitude: float = 0.015, p: float = 0.5, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to add gaussian noise to audio.

__init__(min_amplitude: float = 0.001, max_amplitude: float = 0.015, p: float = 0.5, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

min_amplitude: float unit: linear amplitude.

Default: 0.001. Minimum noise amplification factor.

max_amplitude: float unit: linear amplitude.

Default: 0.015. Maximum noise amplification factor.

p: float range: [0.0, 1.0]. Default: 0.5.

The probability of applying this transform.

save_dir: str. Default: None.

The directory where generated audio files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.AudioFFmpegWrappedMapper(filter_name: str | None = None, filter_kwargs: Dict | None = None, global_args: List[str] | None = None, capture_stderr: bool = True, overwrite_output: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Simple wrapper for FFmpeg audio filters.

__init__(filter_name: str | None = None, filter_kwargs: Dict | None = None, global_args: List[str] | None = None, capture_stderr: bool = True, overwrite_output: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • filter_name โ€“ ffmpeg audio filter name.

  • filter_kwargs โ€“ keyword-arguments passed to ffmpeg filter.

  • global_args โ€“ list-arguments passed to ffmpeg command-line.

  • capture_stderr โ€“ whether to capture stderr.

  • overwrite_output โ€“ whether to overwrite output file.

  • save_dir โ€“ The directory where generated audio files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.CalibrateQAMapper(api_model: str = 'gpt-4o', *, api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, reference_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Mapper to calibrate question-answer pairs based on reference text.

DEFAULT_SYSTEM_PROMPT = '่ฏทๆ นๆฎๆไพ›็š„ใ€ๅ‚่€ƒไฟกๆฏใ€‘ๅฏนใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘่ฟ›่กŒๆ กๅ‡†๏ผŒไฝฟๅ…ถๆ›ดๅŠ ่ฏฆ็ป†ใ€ๅ‡†็กฎใ€‚\nๆŒ‰็…งไปฅไธ‹ๆ ผๅผ่พ“ๅ‡บ๏ผš\nใ€้—ฎ้ข˜ใ€‘\nๆ กๅ‡†ๅŽ็š„้—ฎ้ข˜\nใ€ๅ›ž็ญ”ใ€‘\nๆ กๅ‡†ๅŽ็š„ๅ›ž็ญ”'#
DEFAULT_INPUT_TEMPLATE = '{reference}\n{qa_pair}'#
DEFAULT_REFERENCE_TEMPLATE = 'ใ€ๅ‚่€ƒไฟกๆฏใ€‘\n{}'#
DEFAULT_QA_PAIR_TEMPLATE = 'ใ€้—ฎ้ข˜ใ€‘\n{}\nใ€ๅ›ž็ญ”ใ€‘\n{}'#
DEFAULT_OUTPUT_PATTERN = 'ใ€้—ฎ้ข˜ใ€‘\\s*(.*?)\\s*ใ€ๅ›ž็ญ”ใ€‘\\s*(.*)'#
__init__(api_model: str = 'gpt-4o', *, api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, reference_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method.

Parameters:
  • api_model โ€“ API model name.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the calibration task.

  • input_template โ€“ Template for building the model input.

  • reference_template โ€“ Template for formatting the reference text.

  • qa_pair_template โ€“ Template for formatting question-answer pairs.

  • output_pattern โ€“ Regular expression for parsing model output.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

build_input(sample)[source]#
parse_output(raw_output)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.CalibrateQueryMapper(api_model: str = 'gpt-4o', *, api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, reference_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: CalibrateQAMapper

Mapper to calibrate query in question-answer pairs based on reference text.

DEFAULT_SYSTEM_PROMPT = '่ฏทๆ นๆฎๆไพ›็š„ใ€ๅ‚่€ƒไฟกๆฏใ€‘ๅฏน้—ฎ็ญ”ๅฏนไธญ็š„ใ€้—ฎ้ข˜ใ€‘่ฟ›่กŒๆ กๅ‡†๏ผŒ        ไฝฟๅ…ถๆ›ดๅŠ ่ฏฆ็ป†ใ€ๅ‡†็กฎ๏ผŒไธ”ไปๅฏไปฅ็”ฑๅŽŸ็ญ”ๆกˆๅ›ž็ญ”ใ€‚ๅช่พ“ๅ‡บๆ กๅ‡†ๅŽ็š„้—ฎ้ข˜๏ผŒไธ่ฆ่พ“ๅ‡บๅคšไฝ™ๅ†…ๅฎนใ€‚'#
parse_output(raw_output)[source]#
class data_juicer.ops.mapper.CalibrateResponseMapper(api_model: str = 'gpt-4o', *, api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, reference_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: CalibrateQAMapper

Mapper to calibrate response in question-answer pairs based on reference text.

DEFAULT_SYSTEM_PROMPT = '่ฏทๆ นๆฎๆไพ›็š„ใ€ๅ‚่€ƒไฟกๆฏใ€‘ๅฏน้—ฎ็ญ”ๅฏนไธญ็š„ใ€ๅ›ž็ญ”ใ€‘่ฟ›่กŒๆ กๅ‡†๏ผŒ        ไฝฟๅ…ถๆ›ดๅŠ ่ฏฆ็ป†ใ€ๅ‡†็กฎ๏ผŒไธ”ไปๅฏไปฅๅ›ž็ญ”ๅŽŸ้—ฎ้ข˜ใ€‚ๅช่พ“ๅ‡บๆ กๅ‡†ๅŽ็š„ๅ›ž็ญ”๏ผŒไธ่ฆ่พ“ๅ‡บๅคšไฝ™ๅ†…ๅฎนใ€‚'#
parse_output(raw_output)[source]#
class data_juicer.ops.mapper.ChineseConvertMapper(mode: str = 's2t', *args, **kwargs)[source]#

Bases: Mapper

Mapper to convert Chinese between Traditional Chinese, Simplified Chinese and Japanese Kanji.

__init__(mode: str = 's2t', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • mode โ€“

    Choose the mode to convert Chinese:

    s2t: Simplified Chinese to Traditional Chinese,

    t2s: Traditional Chinese to Simplified Chinese,

    s2tw: Simplified Chinese to Traditional Chinese (Taiwan Standard),

    tw2s: Traditional Chinese (Taiwan Standard) to Simplified Chinese,

    s2hk: Simplified Chinese to Traditional Chinese (Hong Kong variant),

    hk2s: Traditional Chinese (Hong Kong variant) to Simplified Chinese,

    s2twp: Simplified Chinese to Traditional Chinese (Taiwan Standard) with Taiwanese idiom,

    tw2sp: Traditional Chinese (Taiwan Standard) to Simplified Chinese with Mainland Chinese idiom,

    t2tw: Traditional Chinese to Traditional Chinese (Taiwan Standard),

    tw2t: Traditional Chinese (Taiwan standard) to Traditional Chinese,

    hk2t: Traditional Chinese (Hong Kong variant) to Traditional Chinese,

    t2hk: Traditional Chinese to Traditional Chinese (Hong Kong variant),

    t2jp: Traditional Chinese Characters (Kyลซjitai) to New Japanese Kanji,

    jp2t: New Japanese Kanji (Shinjitai) to Traditional Chinese Characters,

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.CleanCopyrightMapper(*args, **kwargs)[source]#

Bases: Mapper

Mapper to clean copyright comments at the beginning of the text samples.

__init__(*args, **kwargs)[source]#

Initialization method.

Parameters:
  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.CleanEmailMapper(pattern: str | None = None, repl: str = '', *args, **kwargs)[source]#

Bases: Mapper

Mapper to clean email in text samples.

__init__(pattern: str | None = None, repl: str = '', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • pattern โ€“ regular expression pattern to search for within text.

  • repl โ€“ replacement string, default is empty string.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.CleanHtmlMapper(*args, **kwargs)[source]#

Bases: Mapper

Mapper to clean html code in text samples.

__init__(*args, **kwargs)[source]#

Initialization method.

Parameters:
  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.CleanIpMapper(pattern: str | None = None, repl: str = '', *args, **kwargs)[source]#

Bases: Mapper

Mapper to clean ipv4 and ipv6 address in text samples.

__init__(pattern: str | None = None, repl: str = '', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • pattern โ€“ regular expression pattern to search for within text.

  • repl โ€“ replacement string, default is empty string.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.CleanLinksMapper(pattern: str | None = None, repl: str = '', *args, **kwargs)[source]#

Bases: Mapper

Mapper to clean links like http/https/ftp in text samples.

__init__(pattern: str | None = None, repl: str = '', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • pattern โ€“ regular expression pattern to search for within text.

  • repl โ€“ replacement string, default is empty string.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.DialogIntentDetectionMapper(api_model: str = 'gpt-4o', intent_candidates: List[str] | None = None, max_round: Annotated[int, Ge(ge=0)] = 10, *, labels_key: str = 'dialog_intent_labels', analysis_key: str = 'dialog_intent_labels_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, candidate_template: str | None = None, analysis_template: str | None = None, labels_template: str | None = None, analysis_pattern: str | None = None, labels_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Mapper to generate userโ€™s intent labels in dialog. Input from history_key, query_key and response_key. Output lists of labels and analysis for queries in the dialog.

DEFAULT_SYSTEM_PROMPT = '่ฏทๅˆคๆ–ญ็”จๆˆทๅ’ŒLLMๅคš่ฝฎๅฏน่ฏไธญ็”จๆˆท็š„ๆ„ๅ›พใ€‚\n่ฆๆฑ‚๏ผš\n- ้œ€่ฆๅ…ˆ่ฟ›่กŒๅˆ†ๆž๏ผŒ็„ถๅŽๅˆ—ๅ‡บ็”จๆˆทๆ‰€ๅ…ทๆœ‰็š„ๆ„ๅ›พ๏ผŒไธ‹้ขๆ˜ฏไธ€ไธชๆ ทไพ‹๏ผŒ่ฏทๆจกไปฟๆ ทไพ‹ๆ ผๅผ่พ“ๅ‡บใ€‚\n็”จๆˆท๏ผšไฝ ๅฅฝ๏ผŒๆˆ‘ๆœ€่ฟ‘ๅฏนไบบๅทฅๆ™บ่ƒฝๅพˆๆ„Ÿๅ…ด่ถฃ๏ผŒ่ƒฝ็ป™ๆˆ‘่ฎฒ่ฎฒไป€ไนˆๆ˜ฏๆœบๅ™จๅญฆไน ๅ—๏ผŸ\nๆ„ๅ›พๅˆ†ๆž๏ผš็”จๆˆทๅœจ่ฏทๆฑ‚ไฟกๆฏ๏ผŒๅธŒๆœ›ไบ†่งฃๆœ‰ๅ…ณๆœบๅ™จๅญฆไน ็š„ๅŸบ็ก€็Ÿฅ่ฏ†ใ€‚\nๆ„ๅ›พ็ฑปๅˆซ๏ผšไฟกๆฏๆŸฅๆ‰พ\nLLM๏ผšไฝ ๅฅฝ๏ผๅฝ“็„ถๅฏไปฅใ€‚ๆœบๅ™จๅญฆไน ๆ˜ฏไธ€็งไบบๅทฅๆ™บ่ƒฝๆ–นๆณ•๏ผŒๅ…่ฎธ่ฎก็ฎ—ๆœบ้€š่ฟ‡ๆ•ฐๆฎ่‡ชๅŠจๆ”น่ฟ›ๅ’Œๅญฆไน ใ€‚\n็”จๆˆท๏ผšๅฌ่ตทๆฅๅพˆๆœ‰่ถฃ๏ผŒๆœ‰ๆฒกๆœ‰ๆŽจ่็š„ๅ…ฅ้—จไนฆ็ฑๆˆ–่ต„ๆ–™๏ผŸ\nๆ„ๅ›พๅˆ†ๆž๏ผš็”จๆˆทๅœจ่ฏทๆฑ‚ๅปบ่ฎฎ๏ผŒๅธŒๆœ›่Žทๅ–ๅ…ณไบŽๆœบๅ™จๅญฆไน ็š„ๅ…ฅ้—จ่ต„ๆบใ€‚\nๆ„ๅ›พ็ฑปๅˆซ๏ผš่ฏทๆฑ‚ๅปบ่ฎฎ\nLLM๏ผšๆœ‰ๅพˆๅคšไธ้”™็š„ๅ…ฅ้—จไนฆ็ฑๅ’Œ่ต„ๆบใ€‚ไธ€ๆœฌๅธธ่ขซๆŽจ่็š„ไนฆๆ˜ฏใ€ŠPythonๆœบๅ™จๅญฆไน ๅฎž่ทตใ€‹๏ผˆPython Machine Learning๏ผ‰๏ผŒๅฎƒๆถต็›–ไบ†ๅŸบ็ก€็Ÿฅ่ฏ†ๅ’Œไธ€ไบ›ๅฎž้™…ๆกˆไพ‹ใ€‚ๆญคๅค–๏ผŒๆ‚จ่ฟ˜ๅฏไปฅๅ‚่€ƒCourseraๆˆ–edXไธŠ็š„ๅœจ็บฟ่ฏพ็จ‹๏ผŒ่ฟ™ไบ›่ฏพ็จ‹ๆไพ›ไบ†็ณป็ปŸ็š„ๅญฆไน ่ทฏๅพ„ใ€‚\n็”จๆˆท๏ผš่ฐข่ฐขไฝ ็š„ๅปบ่ฎฎ๏ผๆˆ‘่ฟ˜ๆƒณ็Ÿฅ้“๏ผŒๅญฆไน ๆœบๅ™จๅญฆไน ้œ€่ฆไป€ไนˆๆ ท็š„ๆ•ฐๅญฆๅŸบ็ก€๏ผŸ\nๆ„ๅ›พๅˆ†ๆž๏ผš็”จๆˆทๅœจๅฏปๆฑ‚ไฟกๆฏ๏ผŒๅธŒๆœ›ไบ†่งฃๅญฆไน ๆœบๅ™จๅญฆไน ๆ‰€้œ€็š„ๅ‰ๆๆกไปถ๏ผŒ็‰นๅˆซๆ˜ฏๅœจๆ•ฐๅญฆๆ–น้ขใ€‚\nๆ„ๅ›พ็ฑปๅˆซ๏ผšไฟกๆฏๆŸฅๆ‰พ\nLLM๏ผšๅญฆไน ๆœบๅ™จๅญฆไน ้€šๅธธ้œ€่ฆไธ€ๅฎš็š„ๆ•ฐๅญฆๅŸบ็ก€๏ผŒ็‰นๅˆซๆ˜ฏ็บฟๆ€งไปฃๆ•ฐใ€ๆฆ‚็އ่ฎบๅ’Œ็ปŸ่ฎกๅญฆใ€‚่ฟ™ไบ›ๆ•ฐๅญฆ้ข†ๅŸŸๅธฎๅŠฉ็†่งฃ็ฎ—ๆณ•็š„ๅทฅไฝœๅŽŸ็†ๅ’Œๆ•ฐๆฎๆจกๅผๅˆ†ๆžใ€‚ๅฆ‚ๆžœๆ‚จๅฏน่ฟ™ไบ›ไธป้ข˜ไธๅคช็†Ÿๆ‚‰๏ผŒๅปบ่ฎฎๅ…ˆไปŽ็›ธๅ…ณๅŸบ็ก€ไนฆ็ฑๆˆ–ๅœจ็บฟ่ต„ๆบๅผ€ๅง‹ๅญฆไน ใ€‚\n็”จๆˆท๏ผšๆ˜Ž็™ฝไบ†๏ผŒๆˆ‘ไผšๅ…ˆ่กฅไน ่ฟ™ไบ›ๅŸบ็ก€็Ÿฅ่ฏ†ใ€‚ๅ†ๆฌกๆ„Ÿ่ฐขไฝ ็š„ๅธฎๅŠฉ๏ผ\nๆ„ๅ›พๅˆ†ๆž๏ผš็”จๆˆท่กจ่พพๆ„Ÿ่ฐข๏ผŒๅนถ่กจ็คบ่ฎกๅˆ’ไป˜่ฏธ่กŒๅŠจๆฅ่กฅๅ……ๆ‰€้œ€็š„ๅŸบ็ก€็Ÿฅ่ฏ†ใ€‚\nๆ„ๅ›พ็ฑปๅˆซ๏ผšๅ…ถไป–'#
DEFAULT_QUERY_TEMPLATE = '็”จๆˆท๏ผš{query}\n'#
DEFAULT_RESPONSE_TEMPLATE = 'LLM๏ผš{response}\n'#
DEFAULT_CANDIDATES_TEMPLATE = 'ๅค‡้€‰ๆ„ๅ›พ็ฑปๅˆซ๏ผš[{candidate_str}]'#
DEFAULT_ANALYSIS_TEMPLATE = 'ๆ„ๅ›พๅˆ†ๆž๏ผš{analysis}\n'#
DEFAULT_LABELS_TEMPLATE = 'ๆ„ๅ›พ็ฑปๅˆซ๏ผš{labels}\n'#
DEFAULT_ANALYSIS_PATTERN = 'ๆ„ๅ›พๅˆ†ๆž๏ผš(.*?)\n'#
DEFAULT_LABELS_PATTERN = 'ๆ„ๅ›พ็ฑปๅˆซ๏ผš(.*?)($|\n)'#
__init__(api_model: str = 'gpt-4o', intent_candidates: List[str] | None = None, max_round: Annotated[int, Ge(ge=0)] = 10, *, labels_key: str = 'dialog_intent_labels', analysis_key: str = 'dialog_intent_labels_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, candidate_template: str | None = None, analysis_template: str | None = None, labels_template: str | None = None, analysis_pattern: str | None = None, labels_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method.

Parameters:
  • api_model โ€“ API model name.

  • intent_candidates โ€“ The output intent candidates. Use the intent labels of the open domain if it is None.

  • max_round โ€“ The max num of round in the dialog to build the prompt.

  • labels_key โ€“ The key name in the meta field to store the output labels. It is โ€˜dialog_intent_labelsโ€™ in default.

  • analysis_key โ€“ The key name in the meta field to store the corresponding analysis. It is โ€˜dialog_intent_labels_analysisโ€™ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the task.

  • query_template โ€“ Template for query part to build the input prompt.

  • response_template โ€“ Template for response part to build the input prompt.

  • candidate_template โ€“ Template for intent candidates to build the input prompt.

  • analysis_template โ€“ Template for analysis part to build the input prompt.

  • labels_template โ€“ Template for labels to build the input prompt.

  • analysis_pattern โ€“ Pattern to parse the return intent analysis.

  • labels_pattern โ€“ Pattern to parse the return intent labels.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

build_input(history, query)[source]#
parse_output(response)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.DialogSentimentDetectionMapper(api_model: str = 'gpt-4o', sentiment_candidates: List[str] | None = None, max_round: Annotated[int, Ge(ge=0)] = 10, *, labels_key: str = 'dialog_sentiment_labels', analysis_key: str = 'dialog_sentiment_labels_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, candidate_template: str | None = None, analysis_template: str | None = None, labels_template: str | None = None, analysis_pattern: str | None = None, labels_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Mapper to generate userโ€™s sentiment labels in dialog. Input from history_key, query_key and response_key. Output lists of labels and analysis for queries in the dialog.

DEFAULT_SYSTEM_PROMPT = '่ฏทๅˆคๆ–ญ็”จๆˆทๅ’ŒLLMๅคš่ฝฎๅฏน่ฏไธญ็”จๆˆทๆ‰€ๅ…ทๆœ‰็š„ๆƒ…็ปชใ€‚\n่ฆๆฑ‚๏ผš\n- ้œ€่ฆๅ…ˆ่ฟ›่กŒๅˆ†ๆž๏ผŒ็„ถๅŽ็ฝ—ๅˆ—็”จๆˆทๆ‰€ๅ…ทๆœ‰็š„ๆƒ…็ปช๏ผŒไธ‹้ขๆ˜ฏไธ€ไธชๆ ทไพ‹๏ผŒ่ฏทๆจกไปฟๆ ทไพ‹ๆ ผๅผ่พ“ๅ‡บใ€‚\n็”จๆˆท๏ผšๆœ€่ฟ‘ๅทฅไฝœๅŽ‹ๅŠ›ๅฅฝๅคง๏ผŒๆˆ‘่ง‰ๅพ—ๆ•ดไธชไบบ้ƒฝๅฟซ่ขซๅŽ‹ๅžฎไบ†ใ€‚\nๆƒ…ๆ„Ÿๅˆ†ๆž๏ผš็”จๆˆท็š„่จ€่ฏญไธญ้€้œฒๅ‡บๆ˜Žๆ˜พ็š„ๅŽ‹ๅŠ›ๅ’Œ็–ฒๆƒซๆ„Ÿ๏ผŒๅฏ่ƒฝ่ฟ˜ๅคนๆ‚็€ไธ€ไบ›ๆ— ๅŠฉๅ’Œ็„ฆ่™‘ใ€‚\nๆƒ…ๆ„Ÿ็ฑปๅˆซ๏ผšๅŽ‹ๅŠ›ใ€็–ฒๆƒซใ€ๆ— ๅŠฉใ€็„ฆ่™‘\nLLM๏ผšๅฌ่ตทๆฅไฝ ็œŸ็š„ๆ‰ฟๅ—ไบ†ๅพˆๅคš๏ผŒ้ขไธด่ฟ™็งๆƒ…ๅ†ต็กฎๅฎžไธๅฎนๆ˜“ใ€‚ๆœ‰ๆฒกๆœ‰่€ƒ่™‘่ฟ‡ๆ‰พไธ€ไบ›ๆ”พๆพ็š„ๆ–นๅผ๏ผŒๆฏ”ๅฆ‚ๅฌ้Ÿณไนๆˆ–่€…ๆ•ฃๆญฅๆฅๅ‡่ฝปๅŽ‹ๅŠ›ๅ‘ข๏ผŸ\n็”จๆˆท๏ผš่ฏ•่ฟ‡ไบ†๏ผŒไฝ†ๆ˜ฏๅฅฝๅƒๆฒกไป€ไนˆๆ•ˆๆžœ๏ผŒๆฏๅคฉ็š„ไบ‹ๆƒ…้ƒฝๅ †็งฏๅฆ‚ๅฑฑใ€‚\nๆƒ…ๆ„Ÿๅˆ†ๆž๏ผš็”จๆˆทๆ„Ÿๅˆฐๆ— ๅŠ›่งฃๅ†ณ็Žฐ็Šถ๏ผŒๆœ‰ๆŒซ่ดฅๆ„Ÿ๏ผŒๅนถไธ”ๅฏนๅฐ่ฏ•ๆ”พๆพ็š„ๆ–นๅผๅคฑๅŽปไฟกๅฟƒใ€‚\nๆƒ…ๆ„Ÿ็ฑปๅˆซ๏ผšๆ— ๅŠ›ใ€ๆŒซ่ดฅ\nLLM๏ผšๆˆ‘็†่งฃไฝ ็š„ๆ„Ÿๅ—๏ผŒๆœ‰ๆ—ถๅ€™ๅŽ‹ๅŠ›็งฏ็ดฏๅˆฐไธ€ๅฎš็จ‹ๅบฆ็กฎๅฎž่ฎฉไบบ้šพไปฅๆ‰ฟๅ—ใ€‚ๆˆ–่ฎธไฝ ๅฏไปฅๅฐ่ฏ•่ง„ๅˆ’ไธ€ไธ‹ๆ—ถ้—ด๏ผŒๆŠŠไปปๅŠกๅˆ†ๆˆๅฐๅ—ๆฅๅฎŒๆˆ๏ผŒ่ฟ™ๆ ทๅฏ่ƒฝไผšๅ‡ๅฐ‘ไธ€ไบ›ๅŽ‹ๅŠ›ๆ„Ÿใ€‚\n็”จๆˆท๏ผš่ฟ™ไธชไธปๆ„ไธ้”™๏ผŒๆˆ‘ไผš่ฏ•็€่ฎฉ่‡ชๅทฑๆ›ดๆœ‰ๆก็†ไธ€ไบ›๏ผŒ่ฐข่ฐขไฝ ็š„ๅปบ่ฎฎใ€‚\nๆƒ…ๆ„Ÿๅˆ†ๆž๏ผš็”จๆˆทๅฏนๅปบ่ฎฎ่กจ็Žฐๅ‡บ่ฎคๅŒๅ’Œๆ„Ÿๆฟ€๏ผŒๅŒๆ—ถๅฑ•็Žฐๅ‡บ่ฏ•ๅ›พ็งฏๆž้ขๅฏน้—ฎ้ข˜็š„ๆ€ๅบฆใ€‚\nๆƒ…ๆ„Ÿ็ฑปๅˆซ๏ผš่ฎคๅŒใ€ๆ„Ÿๆฟ€ใ€็งฏๆž\nLLM๏ผšไธ็”จ่ฐข๏ผŒๆˆ‘ๅพˆ้ซ˜ๅ…ด่ƒฝๅธฎๅˆฐไฝ ใ€‚่ฎฐๅพ—็ป™่‡ชๅทฑไธ€ไบ›ๆ—ถ้—ดๅŽป้€‚ๅบ”ๆ–ฐ็š„่ฎกๅˆ’๏ผŒๆœ‰ไปปไฝ•้œ€่ฆ้šๆ—ถๅฏไปฅ่ทŸๆˆ‘่ฏดๅ“ฆ๏ผ\n'#
DEFAULT_QUERY_TEMPLATE = '็”จๆˆท๏ผš{query}\n'#
DEFAULT_RESPONSE_TEMPLATE = 'LLM๏ผš{response}\n'#
DEFAULT_CANDIDATES_TEMPLATE = 'ๅค‡้€‰ๆƒ…ๆ„Ÿ็ฑปๅˆซ๏ผš[{candidate_str}]'#
DEFAULT_ANALYSIS_TEMPLATE = 'ๆƒ…ๆ„Ÿๅˆ†ๆž๏ผš{analysis}\n'#
DEFAULT_LABELS_TEMPLATE = 'ๆƒ…ๆ„Ÿ็ฑปๅˆซ๏ผš{labels}\n'#
DEFAULT_ANALYSIS_PATTERN = 'ๆƒ…ๆ„Ÿๅˆ†ๆž๏ผš(.*?)\n'#
DEFAULT_LABELS_PATTERN = 'ๆƒ…ๆ„Ÿ็ฑปๅˆซ๏ผš(.*?)($|\n)'#
__init__(api_model: str = 'gpt-4o', sentiment_candidates: List[str] | None = None, max_round: Annotated[int, Ge(ge=0)] = 10, *, labels_key: str = 'dialog_sentiment_labels', analysis_key: str = 'dialog_sentiment_labels_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, candidate_template: str | None = None, analysis_template: str | None = None, labels_template: str | None = None, analysis_pattern: str | None = None, labels_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method.

Parameters:
  • api_model โ€“ API model name.

  • sentiment_candidates โ€“ The output sentiment candidates. Use open-domain sentiment labels if it is None.

  • max_round โ€“ The max num of round in the dialog to build the prompt.

  • labels_key โ€“ The key name in the meta field to store the output labels. It is โ€˜dialog_sentiment_labelsโ€™ in default.

  • analysis_key โ€“ The key name in the meta field to store the corresponding analysis. It is โ€˜dialog_sentiment_labels_analysisโ€™ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the task.

  • query_template โ€“ Template for query part to build the input prompt.

  • response_template โ€“ Template for response part to build the input prompt.

  • candidate_template โ€“ Template for sentiment candidates to build the input prompt.

  • analysis_template โ€“ Template for analysis part to build the input prompt.

  • labels_template โ€“ Template for labels part to build the input prompt.

  • analysis_pattern โ€“ Pattern to parse the return sentiment analysis.

  • labels_pattern โ€“ Pattern to parse the return sentiment labels.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

build_input(history, query)[source]#
parse_output(response)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.DialogSentimentIntensityMapper(api_model: str = 'gpt-4o', max_round: Annotated[int, Ge(ge=0)] = 10, *, intensities_key: str = 'dialog_sentiment_intensity', analysis_key: str = 'dialog_sentiment_intensity_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, analysis_template: str | None = None, intensity_template: str | None = None, analysis_pattern: str | None = None, intensity_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Mapper to predict userโ€™s sentiment intensity (from -5 to 5 in default prompt) in dialog. Input from history_key, query_key and response_key. Output lists of intensities and analysis for queries in the dialog.

DEFAULT_SYSTEM_PROMPT = '่ฏทๅˆคๆ–ญ็”จๆˆทๅ’ŒLLMๅคš่ฝฎๅฏน่ฏไธญ็”จๆˆท็š„ๆƒ…็ปชๅ˜ๅŒ–ใ€‚\n่ฆๆฑ‚๏ผš\n- ็”จๆˆทๆƒ…็ปชๅ€ผๆ˜ฏ-5ๅˆฐ5ไน‹้—ดๅˆฐๆ•ดๆ•ฐ๏ผŒ-5่กจ็คบๆžๅบฆ่ดŸ้ข๏ผŒ5่กจ็คบๆžๅบฆๆญฃ้ข๏ผŒ-5ๅˆฐ5ไน‹้—ดๆ•ฐๅ€ผ่กจ็คบๆƒ…็ปชไปŽ่ดŸ้ข้€ๆธๅˆฐๆญฃ้ข็š„ๅ˜ๅŒ–่ฟ‡็จ‹๏ผŒ0ไปฃ่กจๆƒ…ๅ‘ˆ็ปชไธญๆ€งใ€‚\n- ๅช่พ“ๅ‡บๅฝ“่ฝฎๅฏน่ฏ็š„ๅˆ†ๆž๏ผŒไธ่ฆ็ปง็ปญๆž„้€ ๅฏน่ฏใ€‚\n- ้œ€่ฆๅ…ˆ่ฟ›่กŒๅˆ†ๆž๏ผŒ็„ถๅŽ็กฎๅฎš็”จๆˆท็š„ๆƒ…็ปชๅ€ผ๏ผŒไธ‹้ขๆ˜ฏไธ€ไธชๆ ทไพ‹๏ผŒ่ฏทๆจกไปฟๆ ทไพ‹ๆ ผๅผ่พ“ๅ‡บใ€‚\n็”จๆˆท๏ผšไฝ ๅฅฝ๏ผŒๆˆ‘ๅฏนๅฏๆŒ็ปญๅ‘ๅฑ•็š„ๅฎšไน‰ๆœ‰็‚นๆจก็ณŠ๏ผŒๅธฎๆˆ‘่งฃ้‡Šไธ€ไธ‹๏ผŸ\nๆƒ…็ปชๅˆ†ๆž๏ผšๅˆšๅผ€ๅง‹๏ผŒ่ฟ˜ๆฒกๅพ—ๅˆฐLLMๅ›žๅค๏ผŒ็”จๆˆทๆƒ…็ปชๅ‘ˆไธญๆ€งใ€‚\nๆƒ…็ปชๅ€ผ๏ผš0\nLLM๏ผšๅฝ“็„ถๅฏไปฅ๏ผๅฏๆŒ็ปญๅ‘ๅฑ•ๆ˜ฏๆŒ‡ๅœจๆปก่ถณๅฝ“ไปฃไบบ็š„้œ€ๆฑ‚็š„ๅŒๆ—ถ๏ผŒไธๆŸๅฎณๅญๅญ™ๅŽไปฃๆปก่ถณๅ…ถ่‡ช่บซ้œ€ๆฑ‚็š„่ƒฝๅŠ›็š„ๅ‘ๅฑ•ๆจกๅผใ€‚ๅฎƒๅŒ…ๆ‹ฌ็ปๆตŽๅ‘ๅฑ•ใ€็คพไผšๅ‘ๅฑ•ๅ’Œ็ŽฏๅขƒไฟๆŠคไธ‰ไธชไธป่ฆๆ–น้ขใ€‚้€š่ฟ‡ๅˆ็†ๅˆฉ็”จ่ต„ๆบๅ’ŒไฟๆŠค็Žฏๅขƒ๏ผŒๆˆ‘ไปฌๅฏไปฅ็กฎไฟๆœชๆฅ็š„ไธ–ไปฃไนŸ่ƒฝไบซๆœ‰ๅฅๅ…จ็š„็”Ÿๆ€็ณป็ปŸๅ’Œ็ปๆตŽๅˆถๅบฆใ€‚\n็”จๆˆท๏ผš่ฐข่ฐขไฝ ็š„่งฃ้‡Š๏ผ้‚ฃไฝ ่ƒฝๅ‘Š่ฏ‰ๆˆ‘ไธ€ไบ›ๆ™ฎ้€šไบบๅฏไปฅ้‡‡ๅ–็š„ๅฏๆŒ็ปญ็”Ÿๆดปๆ–นๅผๅ—๏ผŸ\nๆƒ…็ปชๅˆ†ๆž๏ผšๅฏนๅ›ž็ญ”ๆ„Ÿๅˆฐๆปกๆ„๏ผŒๆƒ…็ปชๆญฃ้ขใ€‚\nๆƒ…็ปชๅ€ผ๏ผš1\nLLM๏ผšๅฝ“็„ถๅฏไปฅ๏ผŒๆ™ฎ้€šไบบๅฏไปฅ้€š่ฟ‡ๅ‡ๅฐ‘ไธ€ๆฌกๆ€งไบงๅ“็š„ไฝฟ็”จใ€้€‰ๆ‹ฉๅ…ฌๅ…ฑไบค้€šๆˆ–ๆ‹ผ่ฝฆใ€่Š‚็บฆ็”จๆฐดใ€ไปฅๅŠๆ”ฏๆŒๆœฌๅœฐๅ’ŒๅฏๆŒ็ปญๅ‘ๅฑ•็š„ไผไธš็ญ‰ๆ–นๅผๆฅ่ทต่กŒๅฏๆŒ็ปญ็”Ÿๆดปใ€‚ๆญคๅค–๏ผŒๅ…ณๆณจๅžƒๅœพๅˆ†็ฑปๅ’Œๅคš็”จ็”ตๅญ่ดฆๅ•ไนŸๆ˜ฏไธ้”™็š„้€‰ๆ‹ฉใ€‚\n็”จๆˆท๏ผšไฝ ๆๅˆฐๆ”ฏๆŒๆœฌๅœฐไผไธš๏ผŒ่ฟ™ไธ€็‚นๆˆ‘ๅพˆๆ„Ÿๅ…ด่ถฃใ€‚่ƒฝ่ฏฆ็ป†่ฏด่ฏดไธบไป€ไนˆ่ฟ™ๅฏนๅฏๆŒ็ปญๅ‘ๅฑ•ๆœ‰ไฟƒ่ฟ›ไฝœ็”จๅ—๏ผŸ\nๆƒ…็ปชๅˆ†ๆž๏ผš่ง‰ๅพ—ๅ›ž็ญ”ๅฎž็”จไธ”ๅ…ทไฝ“๏ผŒๆƒ…็ปช่ฟ›ไธ€ๆญฅ่ฝฌๅฅฝใ€‚\nๆƒ…็ปชๅ€ผ๏ผš2\nLLM๏ผšๅ‘ƒ๏ผŒๆˆ‘ๆœ€่ฟ‘ๅ‘็Žฐไบ†ไธ€้ƒจๆ–ฐ็”ตๅฝฑ๏ผŒ่ฎฒ่ฟฐไบ†ไธ€ไธชๅ…ณไบŽๅค–ๆ˜Ÿไบบๅ’Œๅœฐ็ƒๅœŸ่‘—ๅˆไฝœไฟๆŠค็Žฏๅขƒ็š„ๆ•…ไบ‹ใ€‚่™ฝ็„ถๅฎƒๆ˜ฏ็ง‘ๅนป็‰‡๏ผŒไฝ†ๅพˆๆœ‰ๅฏๅ‘ๆ€ง๏ผŒๆŽจ่ไฝ ๅŽป็œ‹็œ‹ใ€‚\n็”จๆˆท๏ผšไป€ไนˆๅ—๏ผŒๆ นๆœฌๆ˜ฏ็ญ”้žๆ‰€้—ฎใ€‚\nๆƒ…็ปชๅˆ†ๆž๏ผšLLMๆฒกๆœ‰ๅ›žๅบ”้—ฎ้ข˜่€Œๆ˜ฏๆๅˆฐๆ— ๅ…ณๅ†…ๅฎน๏ผŒๅฏผ่‡ด็”จๆˆทๆƒ…็ปช็›ด็บฟไธ‹้™ใ€‚\nๆƒ…็ปชๅ€ผ๏ผš-2\nLLM๏ผšๆŠฑๆญ‰ๅˆšๆ‰็š„ๅ้ข˜๏ผๆ”ฏๆŒๆœฌๅœฐไผไธšๆœ‰ๅŠฉไบŽๅ‡ๅฐ‘้•ฟ้€”่ฟ่พ“ไบง็”Ÿ็š„็ขณ่ถณ่ฟน๏ผŒไฝฟไพ›ๅบ”้“พๆ›ดๅŠ ็Žฏไฟใ€‚ๆญคๅค–๏ผŒๆœฌๅœฐไผไธšไนŸๆ›ดๆœ‰ๅฏ่ƒฝ้‡‡็”จๅฏๆŒ็ปญ็š„็”Ÿไบงๆ–นๅผ๏ผŒๅŒๆ—ถไฟƒ่ฟ›็คพๅŒบ็ปๆตŽ็š„็น่ฃใ€‚\n็”จๆˆท๏ผš่ฟ˜่กŒๅง๏ผŒ็ฎ—ไฝ ่ƒฝๅคŸๆŽฐๅ›žๆฅใ€‚\nๆƒ…็ปชๅˆ†ๆž๏ผš้—ฎ้ข˜ๅพ—ๅˆฐ่งฃ็ญ”๏ผŒ้—ฎ้ข˜ๅ้ข˜ๅพ—ๅˆฐ็บ ๆญฃ๏ผŒๆƒ…็ปช็จๆœ‰ๅฅฝ่ฝฌใ€‚\nๆƒ…็ปชๅ€ผ๏ผš-1\n'#
DEFAULT_QUERY_TEMPLATE = '็”จๆˆท๏ผš{query}\n'#
DEFAULT_RESPONSE_TEMPLATE = 'LLM๏ผš{response}\n'#
DEFAULT_ANALYSIS_TEMPLATE = 'ๆƒ…็ปชๅˆ†ๆž๏ผš{analysis}\n'#
DEFAULT_INTENSITY_TEMPLATE = 'ๆƒ…็ปชๅ€ผ๏ผš{intensity}\n'#
DEFAULT_ANALYSIS_PATTERN = 'ๆƒ…็ปชๅˆ†ๆž๏ผš(.*?)\n'#
DEFAULT_INTENSITY_PATTERN = 'ๆƒ…็ปชๅ€ผ๏ผš(.*?)($|\n)'#
__init__(api_model: str = 'gpt-4o', max_round: Annotated[int, Ge(ge=0)] = 10, *, intensities_key: str = 'dialog_sentiment_intensity', analysis_key: str = 'dialog_sentiment_intensity_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, analysis_template: str | None = None, intensity_template: str | None = None, analysis_pattern: str | None = None, intensity_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method.

Parameters:
  • api_model โ€“ API model name.

  • max_round โ€“ The max num of round in the dialog to build the prompt.

  • intensities_key โ€“ The key name in the meta field to store the output sentiment intensities. It is โ€˜dialog_sentiment_intensityโ€™ in default.

  • analysis_key โ€“ The key name in the meta field to store the corresponding analysis. It is โ€˜dialog_sentiment_intensity_analysisโ€™ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the task.

  • query_template โ€“ Template for query part to build the input prompt.

  • response_template โ€“ Template for response part to build the input prompt.

  • analysis_template โ€“ Template for analysis part to build the input prompt.

  • intensity_template โ€“ Template for intensity part to build the input prompt.

  • analysis_pattern โ€“ Pattern to parse the return sentiment analysis.

  • intensity_pattern โ€“ Pattern to parse the return sentiment intensity.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

build_input(history, query)[source]#
parse_output(response)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.DialogTopicDetectionMapper(api_model: str = 'gpt-4o', topic_candidates: List[str] | None = None, max_round: Annotated[int, Ge(ge=0)] = 10, *, labels_key: str = 'dialog_topic_labels', analysis_key: str = 'dialog_topic_labels_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, candidate_template: str | None = None, analysis_template: str | None = None, labels_template: str | None = None, analysis_pattern: str | None = None, labels_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Mapper to generate userโ€™s topic labels in dialog. Input from history_key, query_key and response_key. Output lists of labels and analysis for queries in the dialog.

DEFAULT_SYSTEM_PROMPT = '่ฏทๅˆคๆ–ญ็”จๆˆทๅ’ŒLLMๅคš่ฝฎๅฏน่ฏไธญ็”จๆˆทๆ‰€่ฎจ่ฎบ็š„่ฏ้ข˜ใ€‚\n่ฆๆฑ‚๏ผš\n- ้’ˆๅฏน็”จๆˆท็š„ๆฏไธชquery๏ผŒ้œ€่ฆๅ…ˆ่ฟ›่กŒๅˆ†ๆž๏ผŒ็„ถๅŽๅˆ—ๅ‡บ็”จๆˆทๆญฃๅœจ่ฎจ่ฎบ็š„่ฏ้ข˜๏ผŒไธ‹้ขๆ˜ฏไธ€ไธชๆ ทไพ‹๏ผŒ่ฏทๆจกไปฟๆ ทไพ‹ๆ ผๅผ่พ“ๅ‡บใ€‚\n็”จๆˆท๏ผšไฝ ๅฅฝ๏ผŒไปŠๅคฉๆˆ‘ไปฌๆฅ่Š่Š็งฆๅง‹็š‡ๅงใ€‚\n่ฏ้ข˜ๅˆ†ๆž๏ผš็”จๆˆทๆๅˆฐ็งฆๅง‹็š‡๏ผŒ่ฟ™ๆ˜ฏไธญๅ›ฝๅކๅฒไธŠ็ฌฌไธ€ไฝ็š‡ๅธใ€‚\n่ฏ้ข˜็ฑปๅˆซ๏ผšๅކๅฒ\nLLM๏ผšๅฝ“็„ถๅฏไปฅ๏ผŒ็งฆๅง‹็š‡ๆ˜ฏไธญๅ›ฝๅކๅฒไธŠ็ฌฌไธ€ไธช็ปŸไธ€ๅ…จๅ›ฝ็š„็š‡ๅธ๏ผŒไป–ๅœจๅ…ฌๅ…ƒๅ‰221ๅนดๅปบ็ซ‹ไบ†็งฆๆœ๏ผŒๅนถ้‡‡ๅ–ไบ†ไธ€็ณปๅˆ—้‡่ฆ็š„ๆ”น้ฉๆŽชๆ–ฝ๏ผŒๅฆ‚็ปŸไธ€ๆ–‡ๅญ—ใ€ๅบฆ้‡่กกๅ’Œ่ดงๅธ็ญ‰ใ€‚\n็”จๆˆท๏ผš็งฆๅง‹็š‡ไฟฎๅปบ็š„้•ฟๅŸŽๅ’Œ็Žฐๅœจ็š„้•ฟๅŸŽๆœ‰ไป€ไนˆๅŒบๅˆซ๏ผŸ\n่ฏ้ข˜ๅˆ†ๆž๏ผš็”จๆˆทๆๅˆฐ็งฆๅง‹็š‡ไฟฎๅปบ็š„้•ฟๅŸŽ๏ผŒๅนถๅฐ†ๅ…ถไธŽ็Žฐไปฃ้•ฟๅŸŽ่ฟ›่กŒๆฏ”่พƒ๏ผŒๆถ‰ๅŠๅปบ็ญ‘ๅކๅฒๅ’Œๅœฐ็†ไฝ็ฝฎใ€‚\n่ฏ้ข˜็ฑปๅˆซ๏ผšๅކๅฒLLM๏ผš็งฆๅง‹็š‡ๆ—ถๆœŸไฟฎๅปบ็š„้•ฟๅŸŽไธป่ฆๆ˜ฏไธบไบ†ๆŠตๅพกๅŒ—ๆ–นๆธธ็‰งๆฐ‘ๆ—็š„ๅ…ฅไพต๏ผŒๅฎƒ็š„่ง„ๆจกๅ’ŒไฟฎๅปบๆŠ€ๆœฏ็›ธๅฏน่พƒไธบ็ฎ€้™‹ใ€‚็Žฐไปฃไบบๆ‰€็œ‹ๅˆฐ็š„้•ฟๅŸŽๅคง้ƒจๅˆ†ๆ˜ฏๆ˜Žๆœๆ—ถๆœŸไฟฎๅปบๅ’Œๆ‰ฉๅปบ็š„๏ผŒๆ˜Ž้•ฟๅŸŽไธไป…่ง„ๆจกๆ›ดๅคงใ€็ป“ๆž„ๆ›ดๅšๅ›บ๏ผŒ่€Œไธ”ไฟๅญ˜ๅพ—ๆฏ”่พƒๅฎŒๅฅฝใ€‚\n็”จๆˆท๏ผšๆœ‰ๆ„ๆ€๏ผŒ้‚ฃไนˆ้•ฟๅŸŽ็š„ๅ…ทไฝ“ไฝ็ฝฎๅœจๅ“ชไบ›็œไปฝๅ‘ข๏ผŸ\n่ฏ้ข˜ๅˆ†ๆž๏ผš็”จๆˆท่ฏข้—ฎ้•ฟๅŸŽ็š„ๅ…ทไฝ“ไฝ็ฝฎ๏ผŒๆถ‰ๅŠๅˆฐๅœฐ็†็Ÿฅ่ฏ†ใ€‚\n่ฏ้ข˜็ฑปๅˆซ๏ผšๅœฐ็†\nLLM๏ผš้•ฟๅŸŽๆจช่ทจไธญๅ›ฝๅŒ—ๆ–นๅคšไธช็œไปฝ๏ผŒไธป่ฆๅŒ…ๆ‹ฌๆฒณๅŒ—ใ€ๅฑฑ่ฅฟใ€ๅ†…่’™ๅคใ€ๅฎๅคใ€้™•่ฅฟใ€็”˜่‚ƒๅ’ŒๅŒ—ไบฌ็ญ‰ใ€‚ๆฏไธ€ๆฎต้•ฟๅŸŽ้ƒฝๅปบๅœจๅ…ณ้”ฎ็š„ๆˆ˜็•ฅไฝ็ฝฎ๏ผŒไปฅไพฟๆœ€ๅคง้™ๅบฆๅœฐๅ‘ๆŒฅๅ…ถ้˜ฒๅพกไฝœ็”จใ€‚\n'#
DEFAULT_QUERY_TEMPLATE = '็”จๆˆท๏ผš{query}\n'#
DEFAULT_RESPONSE_TEMPLATE = 'LLM๏ผš{response}\n'#
DEFAULT_CANDIDATES_TEMPLATE = 'ๅค‡้€‰่ฏ้ข˜็ฑปๅˆซ๏ผš[{candidate_str}]'#
DEFAULT_ANALYSIS_TEMPLATE = '่ฏ้ข˜ๅˆ†ๆž๏ผš{analysis}\n'#
DEFAULT_LABELS_TEMPLATE = '่ฏ้ข˜็ฑปๅˆซ๏ผš{labels}\n'#
DEFAULT_ANALYSIS_PATTERN = '่ฏ้ข˜ๅˆ†ๆž๏ผš(.*?)\n'#
DEFAULT_LABELS_PATTERN = '่ฏ้ข˜็ฑปๅˆซ๏ผš(.*?)($|\n)'#
__init__(api_model: str = 'gpt-4o', topic_candidates: List[str] | None = None, max_round: Annotated[int, Ge(ge=0)] = 10, *, labels_key: str = 'dialog_topic_labels', analysis_key: str = 'dialog_topic_labels_analysis', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, query_template: str | None = None, response_template: str | None = None, candidate_template: str | None = None, analysis_template: str | None = None, labels_template: str | None = None, analysis_pattern: str | None = None, labels_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method.

Parameters:
  • api_model โ€“ API model name.

  • topic_candidates โ€“ The output topic candidates. Use open-domain topic labels if it is None.

  • max_round โ€“ The max num of round in the dialog to build the prompt.

  • labels_key โ€“ The key name in the meta field to store the output labels. It is โ€˜dialog_topic_labelsโ€™ in default.

  • analysis_key โ€“ The key name in the meta field to store the corresponding analysis. It is โ€˜dialog_topic_labels_analysisโ€™ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the task.

  • query_template โ€“ Template for query part to build the input prompt.

  • response_template โ€“ Template for response part to build the input prompt.

  • candidate_template โ€“ Template for topic candidates to build the input prompt.

  • analysis_template โ€“ Template for analysis part to build the input prompt.

  • labels_template โ€“ Template for labels part to build the input prompt.

  • analysis_pattern โ€“ Pattern to parse the return topic analysis.

  • labels_pattern โ€“ Pattern to parse the return topic labels.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

build_input(history, query)[source]#
parse_output(response)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.Difference_Area_Generator_Mapper(image_pair_similarity_filter_args: Dict | None = {}, image_segment_mapper_args: Dict | None = {}, image_text_matching_filter_args: Dict | None = {}, *args, **kwargs)[source]#

Bases: Mapper

A fused operator for OPs that is used to run sequential OPs on the same batch to allow fine-grained control on data processing.

__init__(image_pair_similarity_filter_args: Dict | None = {}, image_segment_mapper_args: Dict | None = {}, image_text_matching_filter_args: Dict | None = {}, *args, **kwargs)[source]#

Base class that conducts data editing.

Parameters:
  • text_key โ€“ the key name of field that stores sample texts to be processed.

  • image_key โ€“ the key name of field that stores sample image list to be processed

  • audio_key โ€“ the key name of field that stores sample audio list to be processed

  • video_key โ€“ the key name of field that stores sample video list to be processed

  • image_bytes_key โ€“ the key name of field that stores sample image bytes list to be processed

  • query_key โ€“ the key name of field that stores sample queries

  • response_key โ€“ the key name of field that stores responses

  • history_key โ€“ the key name of field that stores history of queries and responses

process_single(samples, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.Difference_Caption_Generator_Mapper(mllm_mapper_args: Dict | None = {}, image_text_matching_filter_args: Dict | None = {}, text_pair_similarity_filter_args: Dict | None = {}, *args, **kwargs)[source]#

Bases: Mapper

A fused operator for OPs that is used to run sequential OPs on the same batch to allow fine-grained control on data processing.

__init__(mllm_mapper_args: Dict | None = {}, image_text_matching_filter_args: Dict | None = {}, text_pair_similarity_filter_args: Dict | None = {}, *args, **kwargs)[source]#

Base class that conducts data editing.

Parameters:
  • text_key โ€“ the key name of field that stores sample texts to be processed.

  • image_key โ€“ the key name of field that stores sample image list to be processed

  • audio_key โ€“ the key name of field that stores sample audio list to be processed

  • video_key โ€“ the key name of field that stores sample video list to be processed

  • image_bytes_key โ€“ the key name of field that stores sample image bytes list to be processed

  • query_key โ€“ the key name of field that stores sample queries

  • response_key โ€“ the key name of field that stores responses

  • history_key โ€“ the key name of field that stores history of queries and responses

process_single(samples, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.DownloadFileMapper(download_field: str = None, save_dir: str = None, save_field: str = None, resume_download: bool = False, timeout: int = 30, max_concurrent: int = 10, *args, **kwargs)[source]#

Bases: Mapper

Mapper to download url files to local files or load them into memory.

__init__(download_field: str = None, save_dir: str = None, save_field: str = None, resume_download: bool = False, timeout: int = 30, max_concurrent: int = 10, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • save_dir โ€“ The directory to save downloaded files.

  • download_field โ€“ The filed name to get the url to download.

  • save_field โ€“ The filed name to save the downloaded file content.

  • resume_download โ€“ Whether to resume download. if True, skip the sample if it exists.

  • max_concurrent โ€“ Maximum concurrent downloads.

  • args โ€“ extra args

  • kwargs โ€“ extra args

download_files_async(urls, return_contents, save_dir=None, **kwargs)[source]#
download_nested_urls(nested_urls: List[str | List[str]], save_dir=None, save_field_contents=None)[source]#
process_batched(samples)[source]#
class data_juicer.ops.mapper.ExpandMacroMapper(*args, **kwargs)[source]#

Bases: Mapper

Mapper to expand macro definitions in the document body of Latex samples.

__init__(*args, **kwargs)[source]#

Initialization method.

Parameters:
  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.ExtractEntityAttributeMapper(api_model: str = 'gpt-4o', query_entities: List[str] = [], query_attributes: List[str] = [], *, entity_key: str = 'main_entities', attribute_key: str = 'attributes', attribute_desc_key: str = 'attribute_descriptions', support_text_key: str = 'attribute_support_texts', api_endpoint: str | None = None, response_path: str | None = None, system_prompt_template: str | None = None, input_template: str | None = None, attr_pattern_template: str | None = None, demo_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Extract attributes for given entities from the text

DEFAULT_SYSTEM_PROMPT_TEMPLATE = '็ป™ๅฎšไธ€ๆฎตๆ–‡ๆœฌ๏ผŒไปŽๆ–‡ๆœฌไธญๆ€ป็ป“{entity}็š„{attribute}๏ผŒๅนถไธ”ไปŽๅŽŸๆ–‡ๆ‘˜ๅฝ•ๆœ€่ƒฝ่ฏดๆ˜Ž่ฏฅ{attribute}็š„ไปฃ่กจๆ€ง็คบไพ‹ใ€‚\n่ฆๆฑ‚๏ผš\n- ๆ‘˜ๅฝ•็š„็คบไพ‹ๅบ”่ฏฅ็ฎ€็Ÿญใ€‚\n- ้ตๅพชๅฆ‚ไธ‹็š„ๅ›žๅคๆ ผๅผ๏ผš\n# {entity}\n## {attribute}๏ผš\n...\n### ไปฃ่กจๆ€ง็คบไพ‹ๆ‘˜ๅฝ•1๏ผš\n```\n...\n```\n### ไปฃ่กจๆ€ง็คบไพ‹ๆ‘˜ๅฝ•2๏ผš\n```\n...\n```\n...\n'#
DEFAULT_INPUT_TEMPLATE = '# ๆ–‡ๆœฌ\n```\n{text}\n```\n'#
DEFAULT_ATTR_PATTERN_TEMPLATE = '\\#\\#\\s*{attribute}๏ผš\\s*(.*?)(?=\\#\\#\\#|\\Z)'#
DEFAULT_DEMON_PATTERN = '\\#\\#\\#\\s*ไปฃ่กจๆ€ง็คบไพ‹ๆ‘˜ๅฝ•(\\d+)๏ผš\\s*```\\s*(.*?)```\\s*(?=\\#\\#\\#|\\Z)'#
__init__(api_model: str = 'gpt-4o', query_entities: List[str] = [], query_attributes: List[str] = [], *, entity_key: str = 'main_entities', attribute_key: str = 'attributes', attribute_desc_key: str = 'attribute_descriptions', support_text_key: str = 'attribute_support_texts', api_endpoint: str | None = None, response_path: str | None = None, system_prompt_template: str | None = None, input_template: str | None = None, attr_pattern_template: str | None = None, demo_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method. :param api_model: API model name. :param query_entities: Entity list to be queried. :param query_attributes: Attribute list to be queried. :param entity_key: The key name in the meta field to store the

given main entity for attribute extraction. Itโ€™s โ€œentityโ€ in default.

Parameters:
  • entity_attribute_key โ€“ The key name in the meta field to store the given attribute to be extracted. Itโ€™s โ€œattributeโ€ in default.

  • attribute_desc_key โ€“ The key name in the meta field to store the extracted attribute description. Itโ€™s โ€œattribute_descriptionโ€ in default.

  • support_text_key โ€“ The key name in the meta field to store the attribute support text extracted from the raw text. Itโ€™s โ€œsupport_textโ€ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt_template โ€“ System prompt template for the task. Need to be specified by given entity and attribute.

  • input_template โ€“ Template for building the model input.

  • attr_pattern_template โ€“ Pattern for parsing the attribute from output. Need to be specified by given attribute.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • drop_text โ€“ If drop the text in the output.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

Param:

demo_pattern: Pattern for parsing the demonstration from output to support the attribute.

parse_output(raw_output, attribute_name)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ExtractEntityRelationMapper(api_model: str = 'gpt-4o', entity_types: List[str] = None, *, entity_key: str = 'entity', relation_key: str = 'relation', api_endpoint: str | None = None, response_path: str | None = None, prompt_template: str | None = None, tuple_delimiter: str | None = None, record_delimiter: str | None = None, completion_delimiter: str | None = None, max_gleaning: Annotated[int, Ge(ge=0)] = 1, continue_prompt: str | None = None, if_loop_prompt: str | None = None, entity_pattern: str | None = None, relation_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Extract entities and relations in the text for knowledge graph.

DEFAULT_PROMPT_TEMPLATE = '-Goal-\nGiven a text document that is potentially relevant to this activity and a list of entity types, identify all entities of those types from the text and all relationships among the identified entities.\n\n-Steps-\n1. Identify all entities. For each identified entity, extract the following information:\n- entity_name: Name of the entity\n- entity_type: One of the following types: [{entity_types}]\n- entity_description: Comprehensive description of the entity\'s attributes and activities\nFormat each entity as ("entity"{tuple_delimiter}<entity_name>{tuple_delimiter}<entity_type>{tuple_delimiter}<entity_description>\n\n2. From the entities identified in step 1, identify all pairs of (source_entity, target_entity) that are *clearly related* to each other.\nFor each pair of related entities, extract the following information:\n- source_entity: name of the source entity, as identified in step 1\n- target_entity: name of the target entity, as identified in step 1\n- relationship_description: explanation as to why you think the source entity and the target entity are related to each other\n- relationship_strength: a numeric score indicating strength of the relationship between the source entity and target entity\n- relationship_keywords: one or more high-level key words that summarize the overarching nature of the relationship, focusing on concepts or themes rather than specific details\nFormat each relationship as ("relationship"{tuple_delimiter}<source_entity>{tuple_delimiter}<target_entity>{tuple_delimiter}<relationship_description>{tuple_delimiter}<relationship_keywords>{tuple_delimiter}<relationship_strength>)\n\n3. Return output in the language of the given text as a single list of all the entities and relationships identified in steps 1 and 2. Use **{record_delimiter}** as the list delimiter.\n\n4. When finished, output {completion_delimiter}\n\n######################\n-Examples-\n######################\nExample 1:\n\nEntity_types: [person, technology, mission, organization, location]\nText:\n```\nwhile Alex clenched his jaw, the buzz of frustration dull against the backdrop of Taylor\'s authoritarian certainty. It was this competitive undercurrent that kept him alert, the sense that his and Jordan\'s shared commitment to discovery was an unspoken rebellion against Cruz\'s narrowing vision of control and order.\n\nThen Taylor did something unexpected. They paused beside Jordan and, for a moment, observed the device with something akin to reverence. โ€œIf this tech can be understood..." Taylor said, their voice quieter, "It could change the game for us. For all of us.โ€\n\nThe underlying dismissal earlier seemed to falter, replaced by a glimpse of reluctant respect for the gravity of what lay in their hands. Jordan looked up, and for a fleeting heartbeat, their eyes locked with Taylor\'s, a wordless clash of wills softening into an uneasy truce.\n\nIt was a small transformation, barely perceptible, but one that Alex noted with an inward nod. They had all been brought here by different paths\n```\n################\nOutput:\n("entity"{tuple_delimiter}"Alex"{tuple_delimiter}"person"{tuple_delimiter}"Alex is a character who experiences frustration and is observant of the dynamics among other characters."){record_delimiter}\n("entity"{tuple_delimiter}"Taylor"{tuple_delimiter}"person"{tuple_delimiter}"Taylor is portrayed with authoritarian certainty and shows a moment of reverence towards a device, indicating a change in perspective."){record_delimiter}\n("entity"{tuple_delimiter}"Jordan"{tuple_delimiter}"person"{tuple_delimiter}"Jordan shares a commitment to discovery and has a significant interaction with Taylor regarding a device."){record_delimiter}\n("entity"{tuple_delimiter}"Cruz"{tuple_delimiter}"person"{tuple_delimiter}"Cruz is associated with a vision of control and order, influencing the dynamics among other characters."){record_delimiter}\n("entity"{tuple_delimiter}"The Device"{tuple_delimiter}"technology"{tuple_delimiter}"The Device is central to the story, with potential game-changing implications, and is reversed by Taylor."){record_delimiter}\n("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Taylor"{tuple_delimiter}"Alex is affected by Taylor\'s authoritarian certainty and observes changes in Taylor\'s attitude towards the device."{tuple_delimiter}"power dynamics, perspective shift"{tuple_delimiter}7){record_delimiter}\n("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Jordan"{tuple_delimiter}"Alex and Jordan share a commitment to discovery, which contrasts with Cruz\'s vision."{tuple_delimiter}"shared goals, rebellion"{tuple_delimiter}6){record_delimiter}\n("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"Jordan"{tuple_delimiter}"Taylor and Jordan interact directly regarding the device, leading to a moment of mutual respect and an uneasy truce."{tuple_delimiter}"conflict resolution, mutual respect"{tuple_delimiter}8){record_delimiter}\n("relationship"{tuple_delimiter}"Jordan"{tuple_delimiter}"Cruz"{tuple_delimiter}"Jordan\'s commitment to discovery is in rebellion against Cruz\'s vision of control and order."{tuple_delimiter}"ideological conflict, rebellion"{tuple_delimiter}5){record_delimiter}\n("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"The Device"{tuple_delimiter}"Taylor shows reverence towards the device, indicating its importance and potential impact."{tuple_delimiter}"reverence, technological significance"{tuple_delimiter}9){record_delimiter}\n#############################\nExample 2:\n\nEntity_types: [ไบบ็‰ฉ, ๆŠ€ๆœฏ, ไปปๅŠก, ็ป„็ป‡, ๅœฐ็‚น]\nText:\n```\nไป–ไปฌไธๅ†ๆ˜ฏๅ•็บฏ็š„ๆ‰ง่กŒ่€…๏ผ›ไป–ไปฌๅทฒๆˆไธบๆŸไธช่ถ…่ถŠๆ˜Ÿ่พฐไธŽๆก็บน็š„้ข†ๅŸŸ็š„ไฟกๆฏๅฎˆๆŠค่€…ใ€‚่ฟ™ไธ€ไฝฟๅ‘ฝ็š„ๆๅ‡ไธ่ƒฝ่ขซ่ง„ๅˆ™ๅ’Œๆ—ขๅฎšๅ่ฎฎๆ‰€ๆŸ็ผšโ€”โ€”ๅฎƒ้œ€่ฆไธ€็งๆ–ฐ็š„่ง†่ง’๏ผŒไธ€็งๆ–ฐ็š„ๅ†ณๅฟƒใ€‚\n\n้š็€ไธŽๅŽ็››้กฟ็š„้€š่ฎฏๅœจ่ƒŒๆ™ฏไธญๅ—กๅ—กไฝœๅ“๏ผŒๅฏน่ฏไธญ็š„็ดงๅผ ๆƒ…็ปช้€š่ฟ‡ๅ˜Ÿๅ˜Ÿๅฃฐๅ’Œ้™็”ตๅ™ช้Ÿณ่ดฏ็ฉฟๅง‹็ปˆใ€‚ๅ›ข้˜Ÿ็ซ™็ซ‹็€๏ผŒไธ€่‚กไธ็ฅฅ็š„ๆฐ”ๆฏ็ฌผ็ฝฉ็€ไป–ไปฌใ€‚ๆ˜พ็„ถ๏ผŒไป–ไปฌๅœจๆŽฅไธ‹ๆฅๅ‡ ไธชๅฐๆ—ถๅ†…ๅšๅ‡บ็š„ๅ†ณๅฎšๅฏ่ƒฝไผš้‡ๆ–ฐๅฎšไน‰ไบบ็ฑปๅœจๅฎ‡ๅฎ™ไธญ็š„ไฝ็ฝฎ๏ผŒๆˆ–่€…ๅฐ†ไป–ไปฌ็ฝฎไบŽๆ— ็Ÿฅๅ’Œๆฝœๅœจๅฑ้™ฉไน‹ไธญใ€‚\n\n้š็€ไธŽๆ˜Ÿ่พฐ็š„่”็ณปๅ˜ๅพ—ๆ›ดๅŠ ็‰ขๅ›บ๏ผŒๅฐ็ป„ๅผ€ๅง‹ๅค„็†้€ๆธๆˆๅฝข็š„่ญฆๅ‘Š๏ผŒไปŽ่ขซๅŠจๆŽฅๅ—่€…่ฝฌๅ˜ไธบ็งฏๆžๅ‚ไธŽ่€…ใ€‚ๆข…็‘ŸๅŽๆฅ็š„็›ด่ง‰ๅ ๆฎไบ†ไธŠ้ฃŽโ€”โ€”ๅ›ข้˜Ÿ็š„ไปปๅŠกๅทฒ็ปๆผ”ๅ˜๏ผŒไธๅ†ไป…ไป…ๆ˜ฏ่ง‚ๅฏŸๅ’ŒๆŠฅๅ‘Š๏ผŒ่€Œๆ˜ฏไบ’ๅŠจๅ’Œๅ‡†ๅค‡ใ€‚ไธ€ๅœบ่œ•ๅ˜ๅทฒ็ปๅผ€ๅง‹๏ผŒ่€Œโ€œๆœๅฐ”ๅกž่กŒๅŠจโ€ๅˆ™ไปฅไป–ไปฌๅคง่ƒ†็š„ๆ–ฐ้ข‘็އ้œ‡ๅŠจ๏ผŒ่ฟ™็งๅŸบ่ฐƒไธๆ˜ฏ็”ฑไธ–ไฟ—่ฎพๅฎš็š„\n```\n#############\nOutput:\n("entity"{tuple_delimiter}"ๅŽ็››้กฟ"{tuple_delimiter}"ๅœฐ็‚น"{tuple_delimiter}"ๅŽ็››้กฟๆ˜ฏๆญฃๅœจๆŽฅๆ”ถ้€š่ฎฏ็š„ๅœฐๆ–น๏ผŒ่กจๆ˜Žๅ…ถๅœจๅ†ณ็ญ–่ฟ‡็จ‹ไธญ็š„้‡่ฆๆ€งใ€‚"){record_delimiter}\n("entity"{tuple_delimiter}"ๆœๅฐ”ๅกž่กŒๅŠจ"{tuple_delimiter}"ไปปๅŠก"{tuple_delimiter}"ๆœๅฐ”ๅกž่กŒๅŠจ่ขซๆ่ฟฐไธบไธ€้กนๅทฒๆผ”ๅ˜ไธบไบ’ๅŠจๅ’Œๅ‡†ๅค‡็š„ไปปๅŠก๏ผŒๆ˜พ็คบๅ‡บ็›ฎๆ ‡ๅ’ŒๆดปๅŠจ็š„้‡ๅคง่ฝฌๅ˜ใ€‚"){record_delimiter}\n("entity"{tuple_delimiter}"ๅ›ข้˜Ÿ"{tuple_delimiter}"็ป„็ป‡"{tuple_delimiter}"ๅ›ข้˜Ÿ่ขซๆ็ป˜ๆˆไธ€็พคไปŽ่ขซๅŠจ่ง‚ๅฏŸ่€…่ฝฌๅ˜ไธบ็งฏๆžๅ‚ไธŽ่€…็š„ไบบ๏ผŒๅฑ•็คบไบ†ไป–ไปฌ่ง’่‰ฒ็š„ๅŠจๆ€ๅ˜ๅŒ–ใ€‚"){record_delimiter}\n("relationship"{tuple_delimiter}"ๅ›ข้˜Ÿ"{tuple_delimiter}"ๅŽ็››้กฟ"{tuple_delimiter}"ๅ›ข้˜Ÿๆ”ถๅˆฐๆฅ่‡ชๅŽ็››้กฟ็š„้€š่ฎฏ๏ผŒ่ฟ™ๅฝฑๅ“ไบ†ไป–ไปฌ็š„ๅ†ณ็ญ–่ฟ‡็จ‹ใ€‚"{tuple_delimiter}"ๅ†ณ็ญ–ใ€ๅค–้ƒจๅฝฑๅ“"{tuple_delimiter}7){record_delimiter}\n("relationship"{tuple_delimiter}"ๅ›ข้˜Ÿ"{tuple_delimiter}"ๆœๅฐ”ๅกž่กŒๅŠจ"{tuple_delimiter}"ๅ›ข้˜Ÿ็›ดๆŽฅๅ‚ไธŽๆœๅฐ”ๅกž่กŒๅŠจ๏ผŒๆ‰ง่กŒๅ…ถๆผ”ๅ˜ๅŽ็š„็›ฎๆ ‡ๅ’ŒๆดปๅŠจใ€‚"{tuple_delimiter}"ไปปๅŠกๆผ”ๅ˜ใ€็งฏๆžๅ‚ไธŽ"{tuple_delimiter}9){completion_delimiter}\n#############################\nExample 3:\n\nEntity_types: [person, role, technology, organization, event, location, concept]\nText:\n```\ntheir voice slicing through the buzz of activity. "Control may be an illusion when facing an intelligence that literally writes its own rules," they stated stoically, casting a watchful eye over the flurry of data.\n\n"It\'s like it\'s learning to communicate," offered Sam Rivera from a nearby interface, their youthful energy boding a mix of awe and anxiety. "This gives talking to strangers\' a whole new meaning."\n\nAlex surveyed his teamโ€”each face a study in concentration, determination, and not a small measure of trepidation. "This might well be our first contact," he acknowledged, "And we need to be ready for whatever answers back."\n\nTogether, they stood on the edge of the unknown, forging humanity\'s response to a message from the heavens. The ensuing silence was palpableโ€”a collective introspection about their role in this grand cosmic play, one that could rewrite human history.\n\nThe encrypted dialogue continued to unfold, its intricate patterns showing an almost uncanny anticipation\n```\n#############\nOutput:\n("entity"{tuple_delimiter}"Sam Rivera"{tuple_delimiter}"person"{tuple_delimiter}"Sam Rivera is a member of a team working on communicating with an unknown intelligence, showing a mix of awe and anxiety."){record_delimiter}\n("entity"{tuple_delimiter}"Alex"{tuple_delimiter}"person"{tuple_delimiter}"Alex is the leader of a team attempting first contact with an unknown intelligence, acknowledging the significance of their task."){record_delimiter}\n("entity"{tuple_delimiter}"Control"{tuple_delimiter}"concept"{tuple_delimiter}"Control refers to the ability to manage or govern, which is challenged by an intelligence that writes its own rules."){record_delimiter}\n("entity"{tuple_delimiter}"Intelligence"{tuple_delimiter}"concept"{tuple_delimiter}"Intelligence here refers to an unknown entity capable of writing its own rules and learning to communicate."){record_delimiter}\n("entity"{tuple_delimiter}"First Contact"{tuple_delimiter}"event"{tuple_delimiter}"First Contact is the potential initial communication between humanity and an unknown intelligence."){record_delimiter}\n("entity"{tuple_delimiter}"Humanity\'s Response"{tuple_delimiter}"event"{tuple_delimiter}"Humanity\'s Response is the collective action taken by Alex\'s team in response to a message from an unknown intelligence."){record_delimiter}\n("relationship"{tuple_delimiter}"Sam Rivera"{tuple_delimiter}"Intelligence"{tuple_delimiter}"Sam Rivera is directly involved in the process of learning to communicate with the unknown intelligence."{tuple_delimiter}"communication, learning process"{tuple_delimiter}9){record_delimiter}\n("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"First Contact"{tuple_delimiter}"Alex leads the team that might be making the First Contact with the unknown intelligence."{tuple_delimiter}"leadership, exploration"{tuple_delimiter}10){record_delimiter}\n("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Humanity\'s Response"{tuple_delimiter}"Alex and his team are the key figures in Humanity\'s Response to the unknown intelligence."{tuple_delimiter}"collective action, cosmic significance"{tuple_delimiter}8){record_delimiter}\n("relationship"{tuple_delimiter}"Control"{tuple_delimiter}"Intelligence"{tuple_delimiter}"The concept of Control is challenged by the Intelligence that writes its own rules."{tuple_delimiter}"power dynamics, autonomy"{tuple_delimiter}7){record_delimiter}\n#############################\n-Real Data-\n######################\nEntity_types: [{entity_types}]\nText:\n```\n{input_text}\n```\n######################\nOutput:\n'#
DEFAULT_CONTINUE_PROMPT = 'MANY entities were missed in the last extraction.  Add them below using the same format:\n'#
DEFAULT_IF_LOOP_PROMPT = 'It appears some entities may have still been missed.  Answer YES | NO if there are still entities that need to be added.\n'#
DEFAULT_ENTITY_TYPES = ['organization', 'person', 'geo', 'event']#
DEFAULT_TUPLE_DELIMITER = '<|>'#
DEFAULT_RECORD_DELIMITER = '##'#
DEFAULT_COMPLETION_DELIMITER = '<|COMPLETE|>'#
DEFAULT_ENTITY_PATTERN = '\\("entity"(.*?)\\)'#
DEFAULT_RELATION_PATTERN = '\\("relationship"(.*?)\\)'#
__init__(api_model: str = 'gpt-4o', entity_types: List[str] = None, *, entity_key: str = 'entity', relation_key: str = 'relation', api_endpoint: str | None = None, response_path: str | None = None, prompt_template: str | None = None, tuple_delimiter: str | None = None, record_delimiter: str | None = None, completion_delimiter: str | None = None, max_gleaning: Annotated[int, Ge(ge=0)] = 1, continue_prompt: str | None = None, if_loop_prompt: str | None = None, entity_pattern: str | None = None, relation_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method. :param api_model: API model name. :param entity_types: Pre-defined entity types for knowledge graph. :param entity_key: The key name to store the entities in the meta

field. Itโ€™s โ€œentityโ€ in default.

Parameters:
  • relation_key โ€“ The field name to store the relations between entities. Itโ€™s โ€œrelationโ€ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • prompt_template โ€“ The template of input prompt.

  • tuple_delimiter โ€“ Delimiter to separate items in outputs.

  • record_delimiter โ€“ Delimiter to separate records in outputs.

  • completion_delimiter โ€“ To mark the end of the output.

  • max_gleaning โ€“ the extra max num to call LLM to glean entities and relations.

  • continue_prompt โ€“ the prompt for gleaning entities and relations.

  • if_loop_prompt โ€“ the prompt to determine whether to stop gleaning.

  • entity_pattern โ€“ Regular expression for parsing entity record.

  • relation_pattern โ€“ Regular expression for parsing relation record.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • drop_text โ€“ If drop the text in the output.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

parse_output(raw_output)[source]#
add_message(messages, role, content)[source]#
light_rag_extraction(messages, rank=None)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ExtractEventMapper(api_model: str = 'gpt-4o', *, event_desc_key: str = 'event_description', relevant_char_key: str = 'relevant_characters', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Extract events and relevant characters in the text

DEFAULT_SYSTEM_PROMPT = '็ป™ๅฎšไธ€ๆฎตๆ–‡ๆœฌ๏ผŒๅฏนๆ–‡ๆœฌ็š„ๆƒ…่Š‚่ฟ›่กŒๅˆ†็‚นๆ€ป็ป“๏ผŒๅนถๆŠฝๅ–ไธŽๆƒ…่Š‚็›ธๅ…ณ็š„ไบบ็‰ฉใ€‚\n่ฆๆฑ‚๏ผš\n- ๅฐฝ้‡ไธ่ฆ้—ๆผๅ†…ๅฎน๏ผŒไธ่ฆๆทปๅŠ ๆ–‡ๆœฌไธญๆฒกๆœ‰็š„ๆƒ…่Š‚๏ผŒ็ฌฆๅˆๅŽŸๆ–‡ไบ‹ๅฎž\n- ่”็ณปไธŠไธ‹ๆ–‡่ฏดๆ˜Žๅ‰ๅ› ๅŽๆžœ๏ผŒไฝ†ไป็„ถ้œ€่ฆ็ฌฆๅˆไบ‹ๅฎž\n- ไธ่ฆๅŒ…ๅซไธป่ง‚็œ‹ๆณ•\n- ๆณจๆ„่ฆๅฐฝๅฏ่ƒฝไฟ็•™ๆ–‡ๆœฌ็š„ไธ“ๆœ‰ๅ่ฏ\n- ๆณจๆ„็›ธๅ…ณไบบ็‰ฉ้œ€่ฆๅœจๅฏนๅบ”ๆƒ…่Š‚ไธญๅ‡บ็Žฐ\n- ๅชๆŠฝๅ–ๆƒ…่Š‚ไธญ็š„ไธป่ฆไบบ็‰ฉ๏ผŒไธ่ฆ้—ๆผๆƒ…่Š‚็š„ไธป่ฆไบบ็‰ฉ\n- ๆ€ป็ป“ๆ ผๅผๅฆ‚ไธ‹๏ผš\n### ๆƒ…่Š‚1๏ผš\n- **ๆƒ…่Š‚ๆ่ฟฐ**๏ผš ...\n- **็›ธๅ…ณไบบ็‰ฉ**๏ผšไบบ็‰ฉ1๏ผŒไบบ็‰ฉ2๏ผŒไบบ็‰ฉ3๏ผŒ...\n### ๆƒ…่Š‚2๏ผš\n- **ๆƒ…่Š‚ๆ่ฟฐ**๏ผš ...\n- **็›ธๅ…ณไบบ็‰ฉ**๏ผšไบบ็‰ฉ1๏ผŒไบบ็‰ฉ2๏ผŒ...\n### ๆƒ…่Š‚3๏ผš\n- **ๆƒ…่Š‚ๆ่ฟฐ**๏ผš ...\n- **็›ธๅ…ณไบบ็‰ฉ**๏ผšไบบ็‰ฉ1๏ผŒ...\n...\n'#
DEFAULT_INPUT_TEMPLATE = '# ๆ–‡ๆœฌ\n```\n{text}\n```\n'#
DEFAULT_OUTPUT_PATTERN = '\n        \\#\\#\\#\\s*ๆƒ…่Š‚(\\d+)๏ผš\\s*\n        -\\s*\\*\\*ๆƒ…่Š‚ๆ่ฟฐ\\*\\*\\s*๏ผš\\s*(.*?)\\s*\n        -\\s*\\*\\*็›ธๅ…ณไบบ็‰ฉ\\*\\*\\s*๏ผš\\s*(.*?)(?=\\#\\#\\#|\\Z)\n    '#
__init__(api_model: str = 'gpt-4o', *, event_desc_key: str = 'event_description', relevant_char_key: str = 'relevant_characters', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method. :param api_model: API model name. :param event_desc_key: The key name to store the event descriptions

in the meta field. Itโ€™s โ€œevent_descriptionโ€ in default.

Parameters:
  • relevant_char_key โ€“ The field name to store the relevant characters to the events in the meta field. Itโ€™s โ€œrelevant_charactersโ€ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the task.

  • input_template โ€“ Template for building the model input.

  • output_pattern โ€“ Regular expression for parsing model output.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • drop_text โ€“ If drop the text in the output.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

parse_output(raw_output)[source]#
process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.ExtractKeywordMapper(api_model: str = 'gpt-4o', *, keyword_key: str = 'keyword', api_endpoint: str | None = None, response_path: str | None = None, prompt_template: str | None = None, completion_delimiter: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Generate keywords for the text

DEFAULT_PROMPT_TEMPLATE = '-Goal-\nGiven a text document that is potentially relevant to this activity and a list of entity types, identify all entities of those types from the text and all relationships among the identified entities.\n\n-Steps-\n1. Identify high-level key words that summarize the main concepts, themes, or topics of the entire text. These should capture the overarching ideas present in the document.\nFormat the content-level key words as ("content_keywords" <high_level_keywords>)\n\n3. Return output in the language of the given text.\n\n4. When finished, output {completion_delimiter}\n\n######################\n-Examples-\n######################\nExample 1:\n\nText:\n```\nwhile Alex clenched his jaw, the buzz of frustration dull against the backdrop of Taylor\'s authoritarian certainty. It was this competitive undercurrent that kept him alert, the sense that his and Jordan\'s shared commitment to discovery was an unspoken rebellion against Cruz\'s narrowing vision of control and order.\n\nThen Taylor did something unexpected. They paused beside Jordan and, for a moment, observed the device with something akin to reverence. โ€œIf this tech can be understood..." Taylor said, their voice quieter, "It could change the game for us. For all of us.โ€\n\nThe underlying dismissal earlier seemed to falter, replaced by a glimpse of reluctant respect for the gravity of what lay in their hands. Jordan looked up, and for a fleeting heartbeat, their eyes locked with Taylor\'s, a wordless clash of wills softening into an uneasy truce.\n\nIt was a small transformation, barely perceptible, but one that Alex noted with an inward nod. They had all been brought here by different paths\n```\n################\nOutput:\n("content_keywords" "power dynamics, ideological conflict, discovery, rebellion"){completion_delimiter}\n#############################\nExample 2:\n\nText:\n```\nไป–ไปฌไธๅ†ๆ˜ฏๅ•็บฏ็š„ๆ‰ง่กŒ่€…๏ผ›ไป–ไปฌๅทฒๆˆไธบๆŸไธช่ถ…่ถŠๆ˜Ÿ่พฐไธŽๆก็บน็š„้ข†ๅŸŸ็š„ไฟกๆฏๅฎˆๆŠค่€…ใ€‚่ฟ™ไธ€ไฝฟๅ‘ฝ็š„ๆๅ‡ไธ่ƒฝ่ขซ่ง„ๅˆ™ๅ’Œๆ—ขๅฎšๅ่ฎฎๆ‰€ๆŸ็ผšโ€”โ€”ๅฎƒ้œ€่ฆไธ€็งๆ–ฐ็š„่ง†่ง’๏ผŒไธ€็งๆ–ฐ็š„ๅ†ณๅฟƒใ€‚\n\n้š็€ไธŽๅŽ็››้กฟ็š„้€š่ฎฏๅœจ่ƒŒๆ™ฏไธญๅ—กๅ—กไฝœๅ“๏ผŒๅฏน่ฏไธญ็š„็ดงๅผ ๆƒ…็ปช้€š่ฟ‡ๅ˜Ÿๅ˜Ÿๅฃฐๅ’Œ้™็”ตๅ™ช้Ÿณ่ดฏ็ฉฟๅง‹็ปˆใ€‚ๅ›ข้˜Ÿ็ซ™็ซ‹็€๏ผŒไธ€่‚กไธ็ฅฅ็š„ๆฐ”ๆฏ็ฌผ็ฝฉ็€ไป–ไปฌใ€‚ๆ˜พ็„ถ๏ผŒไป–ไปฌๅœจๆŽฅไธ‹ๆฅๅ‡ ไธชๅฐๆ—ถๅ†…ๅšๅ‡บ็š„ๅ†ณๅฎšๅฏ่ƒฝไผš้‡ๆ–ฐๅฎšไน‰ไบบ็ฑปๅœจๅฎ‡ๅฎ™ไธญ็š„ไฝ็ฝฎ๏ผŒๆˆ–่€…ๅฐ†ไป–ไปฌ็ฝฎไบŽๆ— ็Ÿฅๅ’Œๆฝœๅœจๅฑ้™ฉไน‹ไธญใ€‚\n\n้š็€ไธŽๆ˜Ÿ่พฐ็š„่”็ณปๅ˜ๅพ—ๆ›ดๅŠ ็‰ขๅ›บ๏ผŒๅฐ็ป„ๅผ€ๅง‹ๅค„็†้€ๆธๆˆๅฝข็š„่ญฆๅ‘Š๏ผŒไปŽ่ขซๅŠจๆŽฅๅ—่€…่ฝฌๅ˜ไธบ็งฏๆžๅ‚ไธŽ่€…ใ€‚ๆข…็‘ŸๅŽๆฅ็š„็›ด่ง‰ๅ ๆฎไบ†ไธŠ้ฃŽโ€”โ€”ๅ›ข้˜Ÿ็š„ไปปๅŠกๅทฒ็ปๆผ”ๅ˜๏ผŒไธๅ†ไป…ไป…ๆ˜ฏ่ง‚ๅฏŸๅ’ŒๆŠฅๅ‘Š๏ผŒ่€Œๆ˜ฏไบ’ๅŠจๅ’Œๅ‡†ๅค‡ใ€‚ไธ€ๅœบ่œ•ๅ˜ๅทฒ็ปๅผ€ๅง‹๏ผŒ่€Œโ€œๆœๅฐ”ๅกž่กŒๅŠจโ€ๅˆ™ไปฅไป–ไปฌๅคง่ƒ†็š„ๆ–ฐ้ข‘็އ้œ‡ๅŠจ๏ผŒ่ฟ™็งๅŸบ่ฐƒไธๆ˜ฏ็”ฑไธ–ไฟ—่ฎพๅฎš็š„\n```\n#############\nOutput:\n("content_keywords" "ไปปๅŠกๆผ”ๅ˜, ๅ†ณ็ญ–ๅˆถๅฎš, ็งฏๆžๅ‚ไธŽ, ๅฎ‡ๅฎ™ๆ„ไน‰"){completion_delimiter}\n#############################\nExample 3:\n\nEntity_types: [person, role, technology, organization, event, location, concept]\nText:\n```\ntheir voice slicing through the buzz of activity. "Control may be an illusion when facing an intelligence that literally writes its own rules," they stated stoically, casting a watchful eye over the flurry of data.\n\n"It\'s like it\'s learning to communicate," offered Sam Rivera from a nearby interface, their youthful energy boding a mix of awe and anxiety. "This gives talking to strangers\' a whole new meaning."\n\nAlex surveyed his teamโ€”each face a study in concentration, determination, and not a small measure of trepidation. "This might well be our first contact," he acknowledged, "And we need to be ready for whatever answers back."\n\nTogether, they stood on the edge of the unknown, forging humanity\'s response to a message from the heavens. The ensuing silence was palpableโ€”a collective introspection about their role in this grand cosmic play, one that could rewrite human history.\n\nThe encrypted dialogue continued to unfold, its intricate patterns showing an almost uncanny anticipation\n```\n#############\nOutput:\n("content_keywords" "first contact, control, communication, cosmic significance"){completion_delimiter}\n-Real Data-\n######################\nText:\n```\n{input_text}\n```\n######################\nOutput:\n'#
DEFAULT_COMPLETION_DELIMITER = '<|COMPLETE|>'#
DEFAULT_OUTPUT_PATTERN = '\\("content_keywords"(.*?)\\)'#
__init__(api_model: str = 'gpt-4o', *, keyword_key: str = 'keyword', api_endpoint: str | None = None, response_path: str | None = None, prompt_template: str | None = None, completion_delimiter: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method. :param api_model: API model name. :param keyword_key: The key name to store the keywords in the meta

field. Itโ€™s โ€œkeywordโ€ in default.

Parameters:
  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • prompt_template โ€“ The template of input prompt.

  • completion_delimiter โ€“ To mark the end of the output.

  • output_pattern โ€“ Regular expression for parsing keywords.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • drop_text โ€“ If drop the text in the output.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

parse_output(raw_output)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ExtractNicknameMapper(api_model: str = 'gpt-4o', *, nickname_key: str = 'nickname', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Extract nickname relationship in the text.

DEFAULT_SYSTEM_PROMPT = '็ป™ๅฎšไฝ ไธ€ๆฎตๆ–‡ๆœฌ๏ผŒไฝ ็š„ไปปๅŠกๆ˜ฏๅฐ†ไบบ็‰ฉไน‹้—ด็š„็งฐๅ‘ผๆ–นๅผ๏ผˆๆ˜ต็งฐ๏ผ‰ๆๅ–ๅ‡บๆฅใ€‚\n่ฆๆฑ‚๏ผš\n- ้œ€่ฆ็ป™ๅ‡บ่ฏด่ฏไบบๅฏน่ขซ็งฐๅ‘ผไบบ็š„็งฐๅ‘ผ๏ผŒไธ่ฆๆžๅไบ†ใ€‚\n- ็›ธๅŒ็š„่ฏด่ฏไบบๅ’Œ่ขซ็งฐๅ‘ผไบบๆœ€ๅคš็ป™ๅ‡บไธ€ไธชๆœ€ๅธธ็”จ็š„็งฐๅ‘ผใ€‚\n- ่ฏทไธ่ฆ่พ“ๅ‡บไบ’็›ธๆฒกๆœ‰ๆ˜ต็งฐ็š„็งฐๅ‘ผๆ–นๅผใ€‚\n- ่พ“ๅ‡บๆ ผๅผๅฆ‚ไธ‹๏ผš\n```\n### ็งฐๅ‘ผๆ–นๅผ1\n- **่ฏด่ฏไบบ**๏ผš...\n- **่ขซ็งฐๅ‘ผไบบ**๏ผš...\n- **...ๅฏน...็š„ๆ˜ต็งฐ**๏ผš...\n### ็งฐๅ‘ผๆ–นๅผ2\n- **่ฏด่ฏไบบ**๏ผš...\n- **่ขซ็งฐๅ‘ผไบบ**๏ผš...\n- **...ๅฏน...็š„ๆ˜ต็งฐ**๏ผš...\n### ็งฐๅ‘ผๆ–นๅผ3\n- **่ฏด่ฏไบบ**๏ผš...\n- **่ขซ็งฐๅ‘ผไบบ**๏ผš...\n- **...ๅฏน...็š„ๆ˜ต็งฐ**๏ผš...\n...\n```\n'#
DEFAULT_INPUT_TEMPLATE = '# ๆ–‡ๆœฌ\n```\n{text}\n```\n'#
DEFAULT_OUTPUT_PATTERN = '\n        \\#\\#\\#\\s*็งฐๅ‘ผๆ–นๅผ(\\d+)\\s*\n        -\\s*\\*\\*่ฏด่ฏไบบ\\*\\*\\s*๏ผš\\s*(.*?)\\s*\n        -\\s*\\*\\*่ขซ็งฐๅ‘ผไบบ\\*\\*\\s*๏ผš\\s*(.*?)\\s*\n        -\\s*\\*\\*(.*?)ๅฏน(.*?)็š„ๆ˜ต็งฐ\\*\\*\\s*๏ผš\\s*(.*?)(?=\\#\\#\\#|\\Z) # for double check\n    '#
__init__(api_model: str = 'gpt-4o', *, nickname_key: str = 'nickname', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, output_pattern: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method. :param api_model: API model name. :param nickname_key: The key name to store the nickname

relationship in the meta field. Itโ€™s โ€œnicknameโ€ in default.

Parameters:
  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the task.

  • input_template โ€“ Template for building the model input.

  • output_pattern โ€“ Regular expression for parsing model output.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • drop_text โ€“ If drop the text in the output.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

parse_output(raw_output)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ExtractSupportTextMapper(api_model: str = 'gpt-4o', *, summary_key: str = 'event_description', support_text_key: str = 'support_text', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Extract support sub text for a summary.

DEFAULT_SYSTEM_PROMPT = 'ไฝ ๅฐ†ๆ‰ฎๆผ”ไธ€ไธชๆ–‡ๆœฌๆ‘˜ๅฝ•ๅŠฉๆ‰‹็š„่ง’่‰ฒใ€‚ไฝ ็š„ไธป่ฆไปปๅŠกๆ˜ฏๅŸบไบŽ็ป™ๅฎš็š„ๆ–‡็ซ ๏ผˆ็งฐไธบโ€œๅŽŸๆ–‡โ€๏ผ‰ไปฅๅŠๅฏนๅŽŸๆ–‡ๆŸไธช้ƒจๅˆ†็š„็ฎ€็Ÿญๆ่ฟฐๆˆ–ๆ€ป็ป“๏ผˆ็งฐไธบโ€œๆ€ป็ป“โ€๏ผ‰๏ผŒๅ‡†็กฎๅœฐ่ฏ†ๅˆซๅนถๆๅ–ๅ‡บไธŽ่ฏฅๆ€ป็ป“็›ธๅฏนๅบ”็š„ๅŽŸๆ–‡็‰‡ๆฎตใ€‚\n่ฆๆฑ‚๏ผš\n- ไฝ ้œ€่ฆๅฐฝๅฏ่ƒฝ็ฒพ็กฎๅœฐๅŒน้…ๅˆฐๆœ€็ฌฆๅˆๆ€ป็ป“ๅ†…ๅฎน็š„้‚ฃ้ƒจๅˆ†ๅ†…ๅฎน\n- ๅฆ‚ๆžœๅญ˜ๅœจๅคšไธชๅฏ่ƒฝ็š„็ญ”ๆกˆ๏ผŒ่ฏท้€‰ๆ‹ฉๆœ€่ดด่ฟ‘ๆ€ป็ป“ๆ„ๆ€็š„้‚ฃไธช\n- ไธ‹้ขๆ˜ฏไธ€ไธชไพ‹ๅญๅธฎๅŠฉ็†่งฃ่ฟ™ไธ€่ฟ‡็จ‹๏ผš\n### ๅŽŸๆ–‡๏ผš\nใ€Š็บขๆฅผๆขฆใ€‹ๆ˜ฏไธญๅ›ฝๅคๅ…ธๅฐ่ฏดๅ››ๅคงๅ่‘—ไน‹ไธ€๏ผŒ็”ฑๆธ…ไปฃไฝœๅฎถๆ›น้›ช่Šนๅˆ›ไฝœใ€‚ๅฎƒ่ฎฒ่ฟฐไบ†่ดพๅฎ็މใ€ๆž—้ป›็މ็ญ‰ไบบ็š„็ˆฑๆƒ…ๆ•…ไบ‹ๅŠๅ››ๅคงๅฎถๆ—็š„ๅ…ด่กฐๅކ็จ‹ใ€‚ไนฆไธญ้€š่ฟ‡ๅคๆ‚็š„ไบบ็‰ฉๅ…ณ็ณปๅฑ•็Žฐไบ†ๅฐๅปบ็คพไผš็š„ๅ„็ง็Ÿ›็›พๅ†ฒ็ชใ€‚ๅ…ถไธญๅ…ณไบŽ่ดพๅบœๅ†…้ƒจๆ–—ไบ‰็š„้ƒจๅˆ†ๅฐคๅ…ถ็ฒพๅฝฉ๏ผŒ็‰นๅˆซๆ˜ฏ็Ž‹็†™ๅ‡คไธŽๅฐคไบŒๅงไน‹้—ด็š„ไบ‰ๆ–—๏ผŒ็”ŸๅŠจๆ็ป˜ไบ†ๆƒๅŠ›ไบ‰ๅคบไธ‹็š„ๅฅณๆ€งๅฝข่ฑกใ€‚ๆญคๅค–๏ผŒใ€Š็บขๆฅผๆขฆใ€‹่ฟ˜ไปฅๅ…ถ็ฒพ็พŽ็š„่ฏ—่ฏ้—ปๅ๏ผŒ่ฟ™ไบ›่ฏ—่ฏไธไป…ๅขžๆทปไบ†ๆ–‡ๅญฆ่‰ฒๅฝฉ๏ผŒไนŸๆทฑๅˆปๅๆ˜ ไบ†ไบบ็‰ฉ็š„ๆ€งๆ ผ็‰น็‚นๅ’Œๅ‘ฝ่ฟ่ตฐๅ‘ใ€‚\n\n### ๆ€ป็ป“๏ผš\nๆ่ฟฐไบ†ไนฆไธญ็š„ไธคไธชๅฅณๆ€ง่ง’่‰ฒไน‹้—ดๅ›ด็ป•ๆƒๅŠ›ๅฑ•ๅผ€็š„็ซžไบ‰ใ€‚\n\n### ๅŽŸๆ–‡ๆ‘˜ๅฝ•๏ผš\nๅ…ถไธญๅ…ณไบŽ่ดพๅบœๅ†…้ƒจๆ–—ไบ‰็š„้ƒจๅˆ†ๅฐคๅ…ถ็ฒพๅฝฉ๏ผŒ็‰นๅˆซๆ˜ฏ็Ž‹็†™ๅ‡คไธŽๅฐคไบŒๅงไน‹้—ด็š„ไบ‰ๆ–—๏ผŒ็”ŸๅŠจๆ็ป˜ไบ†ๆƒๅŠ›ไบ‰ๅคบไธ‹็š„ๅฅณๆ€งๅฝข่ฑกใ€‚'#
DEFAULT_INPUT_TEMPLATE = '### ๅŽŸๆ–‡๏ผš\n{text}\n\n### ๆ€ป็ป“๏ผš\n{summary}\n\n### ๅŽŸๆ–‡ๆ‘˜ๅฝ•๏ผš\n'#
__init__(api_model: str = 'gpt-4o', *, summary_key: str = 'event_description', support_text_key: str = 'support_text', api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method. :param api_model: API model name. :param summary_key: The key name to store the input summary in the

meta field. Itโ€™s โ€œevent_descriptionโ€ in default.

Parameters:
  • support_text_key โ€“ The key name to store the output support text for the summary in the meta field. Itโ€™s โ€œsupport_textโ€ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for the task.

  • input_template โ€“ Template for building the model input.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • drop_text โ€“ If drop the text in the output.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ExtractTablesFromHtmlMapper(tables_field_name: str = 'html_tables', retain_html_tags: bool = False, include_header: bool = True, *args, **kwargs)[source]#

Bases: Mapper

Mapper to extract tables from HTML content.

__init__(tables_field_name: str = 'html_tables', retain_html_tags: bool = False, include_header: bool = True, *args, **kwargs)[source]#

Initialization method. :param tables_field_name: Field name to store the extracted tables. :param retain_html_tags: If True, retains HTML tags in the tables;

otherwise, removes them.

Parameters:

include_header โ€“

If True, includes the table header;

otherwise, excludes it.

This parameter is effective

only when retain_html_tags is False

and applies solely to the extracted table content.

process_single(sample)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.FixUnicodeMapper(normalization: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to fix unicode errors in text samples.

__init__(normalization: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • normalization โ€“ the specified form of Unicode normalization mode, which can be one of [โ€˜NFCโ€™, โ€˜NFKCโ€™, โ€˜NFDโ€™, and โ€˜NFKDโ€™], default โ€˜NFCโ€™.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.GenerateQAFromExamplesMapper(hf_model: str = 'Qwen/Qwen2.5-7B-Instruct', *, seed_file: str = '', example_num: Annotated[int, Gt(gt=0)] = 3, similarity_threshold: float = 0.7, system_prompt: str | None = None, input_template: str | None = None, example_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Bases: Mapper

Mapper to generate question and answer pairs from examples. You should configure an empty dataset in your yaml config file: ``` generated_dataset_config:

type: โ€˜EmptyFormatterโ€™ # use RayEmptyFormatter when enable ray length: ${The number of generated samples} feature_keys: ${text key}

``` The number of samples generated is determined by the length of the empty dataset.

DEFAULT_SYSTEM_PROMPT = '่ฏทไฝ ไป”็ป†่ง‚ๅฏŸๅคšไธช็คบไพ‹ๆ•ฐๆฎ็š„่พ“ๅ…ฅๅ’Œ่พ“ๅ‡บ๏ผŒๆŒ‰็…งไฝ ็š„็†่งฃ๏ผŒๆ€ป็ป“ๅ‡บ็›ธๅบ”่ง„็Ÿฉ๏ผŒ็„ถๅŽๅ†™ๅ‡บไธ€ไธชๆ–ฐ็š„ใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘ใ€‚ๆณจๆ„๏ผŒๆ–ฐ็”Ÿๆˆ็š„ใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘้œ€่ฆๆปก่ถณๅฆ‚ไธ‹่ฆๆฑ‚๏ผš\n1. ็”Ÿๆˆ็š„ใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘ไธ่ƒฝไธŽ่พ“ๅ…ฅ็š„ใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘ไธ€่‡ด๏ผŒไฝ†ๆ˜ฏ้œ€่ฆไฟๆŒๆ ผๅผ็›ธๅŒใ€‚\n2. ็”Ÿๆˆ็š„ใ€้—ฎ้ข˜ใ€‘ไธไธ€ๅฎš่ฆๅฑ€้™ไบŽ่พ“ๅ…ฅใ€้—ฎ้ข˜ใ€‘็š„่ฏ้ข˜ๆˆ–้ข†ๅŸŸ๏ผŒ็”Ÿๆˆ็š„ใ€ๅ›ž็ญ”ใ€‘้œ€่ฆๆญฃ็กฎๅ›ž็ญ”็”Ÿๆˆ็š„ใ€้—ฎ้ข˜ใ€‘ใ€‚\n3. ๆไพ›็š„ใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘ๅฏ่ƒฝๆ˜ฏๅคš่ฝฎๅฏน่ฏ๏ผŒ็”Ÿๆˆ็š„ใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘ไนŸๅฏไปฅๆ˜ฏๅคš่ฝฎ๏ผŒไฝ†ๆ˜ฏ้œ€่ฆไฟๆŒๆ ผๅผ็›ธๅŒใ€‚\n4. ็”Ÿๆˆ็š„ใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘ๅฟ…้กปๆˆๅฏนๅ‡บ็Žฐ๏ผŒ่€Œไธ”ใ€้—ฎ้ข˜ใ€‘้œ€่ฆๅœจใ€ๅ›ž็ญ”ใ€‘ไน‹ๅ‰ใ€‚\n'#
DEFAULT_INPUT_TEMPLATE = '{}'#
DEFAULT_EXAMPLE_TEMPLATE = '\nๅฆ‚ไธ‹ๆ˜ฏไธ€ๆก็คบไพ‹ๆ•ฐๆฎ๏ผš\n{}'#
DEFAULT_QA_PAIR_TEMPLATE = 'ใ€้—ฎ้ข˜ใ€‘\n{}\nใ€ๅ›ž็ญ”ใ€‘\n{}\n'#
DEFAULT_OUTPUT_PATTERN = 'ใ€้—ฎ้ข˜ใ€‘(.*?)ใ€ๅ›ž็ญ”ใ€‘(.*?)(?=ใ€้—ฎ้ข˜ใ€‘|$)'#
__init__(hf_model: str = 'Qwen/Qwen2.5-7B-Instruct', *, seed_file: str = '', example_num: Annotated[int, Gt(gt=0)] = 3, similarity_threshold: float = 0.7, system_prompt: str | None = None, input_template: str | None = None, example_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_model โ€“ Huggingface model ID.

  • seed_file โ€“ Path to the seed file in chatml format.

  • example_num โ€“ The number of selected examples. Randomly select N examples from โ€œseed_fileโ€ and put them into prompt as QA examples.

  • similarity_threshold โ€“ The similarity score threshold between the generated samples and the seed examples. Range from 0 to 1. Samples with similarity score less than this threshold will be kept.

  • system_prompt โ€“ System prompt for guiding the generation task.

  • input_template โ€“ Template for building the input prompt. It must include one placeholder โ€˜{}โ€™, which will be replaced by example_num formatted examples defined by example_template.

  • example_template โ€“ Template for formatting one QA example. It must include one placeholder โ€˜{}โ€™, which will be replaced by one formatted qa_pair.

  • qa_pair_template โ€“ Template for formatting a single QA pair within each example. Must include two placeholders โ€˜{}โ€™ for the question and answer.

  • output_pattern โ€“ Regular expression pattern to extract questions and answers from model response.

  • enable_vllm โ€“ Whether to use vllm for inference acceleration.

  • model_params โ€“ Parameters for initializing the model.

  • sampling_params โ€“ Sampling parameters for text generation. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

build_input(qa_examples)[source]#
parse_output(raw_output)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.GenerateQAFromTextMapper(hf_model: str = 'alibaba-pai/pai-qwen1_5-7b-doc2qa', max_num: Annotated[int, Gt(gt=0)] | None = None, *, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Bases: Mapper

Mapper to generate question and answer pairs from text. Recommended model list: [

โ€˜alibaba-pai/pai-llama3-8b-doc2qaโ€™, โ€˜alibaba-pai/pai-baichuan2-7b-doc2qaโ€™, โ€˜alibaba-pai/pai-qwen1_5-4b-doc2qaโ€™, โ€˜alibaba-pai/pai-qwen1_5-7b-doc2qaโ€™, โ€˜alibaba-pai/pai-qwen1_5-1b8-doc2qaโ€™, โ€˜alibaba-pai/pai-qwen1_5-0b5-doc2qaโ€™

] These recommended models are all trained with Chinese data and are suitable for Chinese.

__init__(hf_model: str = 'alibaba-pai/pai-qwen1_5-7b-doc2qa', max_num: Annotated[int, Gt(gt=0)] | None = None, *, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_model โ€“ Huggingface model ID.

  • max_num โ€“ The max num of returned QA sample for each text. Not limit if it is None.

  • output_pattern โ€“ Regular expression pattern to extract questions and answers from model response.

  • enable_vllm โ€“ Whether to use vllm for inference acceleration.

  • model_params โ€“ Parameters for initializing the model.

  • sampling_params โ€“ Sampling parameters for text generation, e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

The default data format parsed by this interface is as follows: Model Input:

่’™ๅคๅ›ฝ็š„้ฆ–้ƒฝๆ˜ฏไนŒๅ…ฐๅทดๆ‰˜๏ผˆUlaanbaatar๏ผ‰ ๅ†ฐๅฒ›็š„้ฆ–้ƒฝๆ˜ฏ้›ทๅ…‹้›…ๆœชๅ…‹๏ผˆReykjavik๏ผ‰

Model Output:

่’™ๅคๅ›ฝ็š„้ฆ–้ƒฝๆ˜ฏไนŒๅ…ฐๅทดๆ‰˜๏ผˆUlaanbaatar๏ผ‰ ๅ†ฐๅฒ›็š„้ฆ–้ƒฝๆ˜ฏ้›ทๅ…‹้›…ๆœชๅ…‹๏ผˆReykjavik๏ผ‰ Human: ่ฏท้—ฎ่’™ๅคๅ›ฝ็š„้ฆ–้ƒฝๆ˜ฏๅ“ช้‡Œ๏ผŸ Assistant: ไฝ ๅฅฝ๏ผŒๆ นๆฎๆไพ›็š„ไฟกๆฏ๏ผŒ่’™ๅคๅ›ฝ็š„้ฆ–้ƒฝๆ˜ฏไนŒๅ…ฐๅทดๆ‰˜๏ผˆUlaanbaatar๏ผ‰ใ€‚ Human: ๅ†ฐๅฒ›็š„้ฆ–้ƒฝๆ˜ฏๅ“ช้‡Œๅ‘ข๏ผŸ Assistant: ๅ†ฐๅฒ›็š„้ฆ–้ƒฝๆ˜ฏ้›ทๅ…‹้›…ๆœชๅ…‹๏ผˆReykjavik๏ผ‰ใ€‚ โ€ฆ

parse_output(raw_output)[source]#
process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.HumanPreferenceAnnotationMapper(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', **kwargs)[source]#

Bases: LabelStudioAnnotationMapper

Operator for human preference annotation using Label Studio.

DEFAULT_LABEL_CONFIG = '\n    <View className="root">\n      <Style>\n        .root {\n          box-sizing: border-box;\n          margin: 0;\n          padding: 0;\n          font-family: \'Roboto\',\n            sans-serif;\n          line-height: 1.6;\n          background-color: #f0f0f0;\n        }\n\n        .container {\n          margin: 0 auto;\n          padding: 20px;\n          background-color: #ffffff;\n          border-radius: 5px;\n          box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1), 0 6px 20px 0 rgba(0, 0, 0, 0.1);\n        }\n\n        .prompt {\n          padding: 20px;\n          background-color: #0084ff;\n          color: #ffffff;\n          border-radius: 5px;\n          margin-bottom: 20px;\n          box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1), 0 3px 10px 0 rgba(0, 0, 0, 0.1);\n        }\n\n        .answers {\n          display: flex;\n          justify-content: space-between;\n          flex-wrap: wrap;\n          gap: 20px;\n        }\n\n        .answer-box {\n          flex-basis: 49%;\n          padding: 20px;\n          background-color: rgba(44, 62, 80, 0.9);\n          color: #ffffff;\n          border-radius: 5px;\n          box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1), 0 3px 10px 0 rgba(0, 0, 0, 0.1);\n        }\n\n        .answer-box p {\n          word-wrap: break-word;\n        }\n\n        .answer-box:hover {\n          background-color: rgba(52, 73, 94, 0.9);\n          cursor: pointer;\n          transition: all 0.3s ease;\n        }\n\n        .lsf-richtext__line:hover {\n          background: unset;\n        }\n\n        .answer-box .lsf-object {\n          padding: 20px\n        }\n      </Style>\n      <View className="container">\n        <View className="prompt">\n          <Text name="prompt" value="$prompt" />\n        </View>\n        <View className="answers">\n          <Pairwise name="comparison" toName="answer1,answer2"\n                    selectionStyle="background-color: #27ae60; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.2); border: 2px solid #2ecc71; cursor: pointer; transition: all 0.3s ease;"\n                    leftChoiceValue="answer1" rightChoiceValue="answer2" />\n          <View className="answer-box">\n            <Text name="answer1" value="$answer1" />\n          </View>\n          <View className="answer-box">\n            <Text name="answer2" value="$answer2" />\n          </View>\n        </View>\n      </View>\n    </View>\n    '#
__init__(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', **kwargs)[source]#

Initialize the human preference annotation operator.

class data_juicer.ops.mapper.ImageBlurMapper(p: float = 0.2, blur_type: str = 'gaussian', radius: float = 2, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to blur images.

__init__(p: float = 0.2, blur_type: str = 'gaussian', radius: float = 2, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • p โ€“ Probability of the image being blurred.

  • blur_type โ€“ Type of blur kernel, including [โ€˜meanโ€™, โ€˜boxโ€™, โ€˜gaussianโ€™].

  • radius โ€“ Radius of blur kernel.

  • save_dir โ€“ The directory where generated image files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ImageCaptioningFromGPT4VMapper(mode: str = 'description', api_key: str = '', max_token: int = 500, temperature: Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0), Le(le=1)])] = 1.0, system_prompt: str = '', user_prompt: str = '', user_prompt_key: str | None = None, keep_original_sample: bool = True, any_or_all: str = 'any', *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate samples whose texts are generated based on gpt-4-vision and the image.

__init__(mode: str = 'description', api_key: str = '', max_token: int = 500, temperature: Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0), Le(le=1)])] = 1.0, system_prompt: str = '', user_prompt: str = '', user_prompt_key: str | None = None, keep_original_sample: bool = True, any_or_all: str = 'any', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • mode โ€“ mode of text generated from images, can be one of [โ€˜reasoningโ€™, โ€˜descriptionโ€™, โ€˜conversationโ€™, โ€˜customโ€™]

  • api_key โ€“ the API key to authenticate the request.

  • max_token โ€“ the maximum number of tokens to generate. Default is 500.

  • temperature โ€“ controls the randomness of the output (range from 0 to 1). Default is 0.

  • system_prompt โ€“ a string prompt used to set the context of a conversation and provide global guidance or rules for the gpt4-vision so that it can generate responses in the expected way. If mode set to custom, the parameter will be used.

  • user_prompt โ€“ a string prompt to guide the generation of gpt4-vision for each samples. Itโ€™s โ€œโ€ in default, which means no prompt provided.

  • user_prompt_key โ€“ the key name of fields in samples to store prompts for each sample. Itโ€™s used for set different prompts for different samples. If itโ€™s none, use prompt in parameter โ€œpromptโ€. Itโ€™s None in default.

  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only generated text in the final datasets and the original text will be removed. Itโ€™s True in default.

  • any_or_all โ€“ keep this sample with โ€˜anyโ€™ or โ€˜allโ€™ strategy of all images. โ€˜anyโ€™: keep this sample if any images meet the condition. โ€˜allโ€™: keep this sample only if all images meet the condition.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.ImageCaptioningMapper(hf_img2seq: str = 'Salesforce/blip2-opt-2.7b', trust_remote_code: bool = False, caption_num: Annotated[int, Gt(gt=0)] = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: str | None = None, prompt_key: str | None = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate samples whose captions are generated based on another model and the figure.

__init__(hf_img2seq: str = 'Salesforce/blip2-opt-2.7b', trust_remote_code: bool = False, caption_num: Annotated[int, Gt(gt=0)] = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: str | None = None, prompt_key: str | None = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_img2seq โ€“ model name on huggingface to generate caption

  • caption_num โ€“ how many candidate captions to generate for each image

  • keep_candidate_mode โ€“

    retain strategy for the generated $caption_num$ candidates.

    โ€™random_anyโ€™: Retain the random one from generated captions

    โ€™similar_one_simhashโ€™: Retain the generated one that is most

    similar to the original caption

    โ€™allโ€™: Retain all generated captions by concatenation

Note

This is a batched_OP, whose input and output type are both list. Suppose there are $N$ list of input samples, whose batch size is $b$, and denote caption_num as $M$. The number of total samples after generation is $2Nb$ when keep_original_sample is True and $Nb$ when keep_original_sample is False. For โ€˜random_anyโ€™ and โ€˜similar_one_simhashโ€™ mode, itโ€™s $(1+M)Nb$ for โ€˜allโ€™ mode when keep_original_sample is True and $MNb$ when keep_original_sample is False.

Parameters:
  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only generated captions in the final datasets and the original captions will be removed. Itโ€™s True in default.

  • prompt โ€“ a string prompt to guide the generation of blip2 model for all samples globally. Itโ€™s None in default, which means no prompt provided.

  • prompt_key โ€“ the key name of fields in samples to store prompts for each sample. Itโ€™s used for set different prompts for different samples. If itโ€™s none, use prompt in parameter โ€œpromptโ€. Itโ€™s None in default.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples, rank=None)[source]#

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_oneโ€™ mode, and $(1+M)Nb$ for โ€˜allโ€™ mode.

Parameters:

samples

Returns:

class data_juicer.ops.mapper.ImageDiffusionMapper(hf_diffusion: str = 'CompVis/stable-diffusion-v1-4', trust_remote_code: bool = False, torch_dtype: str = 'fp32', revision: str = 'main', strength: Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0), Le(le=1)])] = 0.8, guidance_scale: float = 7.5, aug_num: Annotated[int, Gt(gt=0)] = 1, keep_original_sample: bool = True, caption_key: str | None = None, hf_img2seq: str = 'Salesforce/blip2-opt-2.7b', save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Generate image by diffusion model

__init__(hf_diffusion: str = 'CompVis/stable-diffusion-v1-4', trust_remote_code: bool = False, torch_dtype: str = 'fp32', revision: str = 'main', strength: Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0), Le(le=1)])] = 0.8, guidance_scale: float = 7.5, aug_num: Annotated[int, Gt(gt=0)] = 1, keep_original_sample: bool = True, caption_key: str | None = None, hf_img2seq: str = 'Salesforce/blip2-opt-2.7b', save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_diffusion โ€“ diffusion model name on huggingface to generate the image.

  • torch_dtype โ€“ the floating point type used to load the diffusion model. Can be one of [โ€˜fp32โ€™, โ€˜fp16โ€™, โ€˜bf16โ€™]

  • revision โ€“ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier allowed by Git.

  • strength โ€“ Indicates extent to transform the reference image. Must be between 0 and 1. image is used as a starting point and more noise is added the higher the strength. The number of denoising steps depends on the amount of noise initially added. When strength is 1, added noise is maximum and the denoising process runs for the full number of iterations specified in num_inference_steps. A value of 1 essentially ignores image.

  • guidance_scale โ€“ A higher guidance scale value encourages the model to generate images closely linked to the text prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1.

  • aug_num โ€“ The image number to be produced by stable-diffusion model.

  • keep_candidate_mode โ€“

    retain strategy for the generated $caption_num$ candidates.

    โ€™random_anyโ€™: Retain the random one from generated captions

    โ€™similar_one_simhashโ€™: Retain the generated one that is most

    similar to the original caption

    โ€™allโ€™: Retain all generated captions by concatenation

Note

This is a batched_OP, whose input and output type are both list. Suppose there are $N$ list of input samples, whose batch size is $b$, and denote caption_num as $M$. The number of total samples after generation is $2Nb$ when keep_original_sample is True and $Nb$ when keep_original_sample is False. For โ€˜random_anyโ€™ and โ€˜similar_one_simhashโ€™ mode, itโ€™s $(1+M)Nb$ for โ€˜allโ€™ mode when keep_original_sample is True and $MNb$ when keep_original_sample is False.

Parameters:
  • caption_key โ€“ the key name of fields in samples to store captions for each images. It can be a string if there is only one image in each sample. Otherwise, it should be a list. If itโ€™s none, ImageDiffusionMapper will produce captions for each images.

  • hf_img2seq โ€“ model name on huggingface to generate caption if caption_key is None.

  • save_dir โ€“ The directory where generated image files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

process_batched(samples, rank=None, context=False)[source]#

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$.

Parameters:

samples

Returns:

class data_juicer.ops.mapper.ImageFaceBlurMapper(cv_classifier: str = '', blur_type: str = 'gaussian', radius: Annotated[float, Ge(ge=0)] = 2, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to blur faces detected in images.

__init__(cv_classifier: str = '', blur_type: str = 'gaussian', radius: Annotated[float, Ge(ge=0)] = 2, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • cv_classifier โ€“ OpenCV classifier path for face detection. By default, we will use โ€˜haarcascade_frontalface_alt.xmlโ€™.

  • blur_type โ€“ Type of blur kernel, including [โ€˜meanโ€™, โ€˜boxโ€™, โ€˜gaussianโ€™].

  • radius โ€“ Radius of blur kernel.

  • save_dir โ€“ The directory where generated image files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ImageRemoveBackgroundMapper(alpha_matting: bool = False, alpha_matting_foreground_threshold: int = 240, alpha_matting_background_threshold: int = 10, alpha_matting_erode_size: int = 10, bgcolor: Tuple[int, int, int, int] | None = None, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove background of images

__init__(alpha_matting: bool = False, alpha_matting_foreground_threshold: int = 240, alpha_matting_background_threshold: int = 10, alpha_matting_erode_size: int = 10, bgcolor: Tuple[int, int, int, int] | None = None, save_dir: str = None, *args, **kwargs)[source]#

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_threshold (int, optional):

Background threshold for alpha matting. Defaults to 10.

alpha_matting_erode_size (int, optional):

Erosion size for alpha matting. Defaults to 10.

bgcolor (Optional[Tuple[int, int, int, int]], optional):

Background color for the cutout image. Defaults to None.

save_dir: The directory where generated image files will be stored.

If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

*args (Optional[Any]): Additional positional arguments. **kwargs (Optional[Any]): Additional keyword arguments.

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ImageSegmentMapper(imgsz=1024, conf=0.05, iou=0.5, model_path='FastSAM-x.pt', *args, **kwargs)[source]#

Bases: Mapper

Perform segment-anything on images and return the bounding boxes.

__init__(imgsz=1024, conf=0.05, iou=0.5, model_path='FastSAM-x.pt', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • imgsz โ€“ resolution for image resizing

  • conf โ€“ confidence score threshold

  • iou โ€“ IoU (Intersection over Union) score threshold

  • model_path โ€“ the path to the FastSAM model. Model name should be one of [โ€˜FastSAM-x.ptโ€™, โ€˜FastSAM-s.ptโ€™].

process_single(sample, rank=None, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.ImageTaggingMapper(tag_field_name: str = 'image_tags', *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate image tags.

__init__(tag_field_name: str = 'image_tags', *args, **kwargs)[source]#

Initialization method. :param tag_field_name: the field name to store the tags. Itโ€™s

โ€œimage_tagsโ€ in default.

Parameters:
  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, rank=None, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.MllmMapper(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)[source]#

Bases: Mapper

Mapper to use MLLMs for visual question answering tasks. Recommended model list: [

llava-hf/llava-v1.6-vicuna-7b-hf, Qwen/Qwen2-VL-7B-Instruct,

]

__init__(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)[source]#

Initialization method. :param hf_model: hugginface model id. :param max_new_tokens: the maximum number of new tokens

generated by the model.

Parameters:
  • temperature โ€“ used to control the randomness of generated text. The higher the temperature, the more random and creative the generated text will be.

  • top_p โ€“ randomly select the next word from the group of words whose cumulative probability reaches p.

  • num_beams โ€“ the larger the beam search size, the higher the quality of the generated text.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample=None, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.NlpaugEnMapper(sequential: bool = False, aug_num: Annotated[int, Gt(gt=0)] = 1, keep_original_sample: bool = True, delete_random_word: bool = False, swap_random_word: bool = False, spelling_error_word: bool = False, split_random_word: bool = False, keyboard_error_char: bool = False, ocr_error_char: bool = False, delete_random_char: bool = False, swap_random_char: bool = False, insert_random_char: bool = False, *args, **kwargs)[source]#

Bases: Mapper

Mapper to simply augment samples in English based on nlpaug library.

__init__(sequential: bool = False, aug_num: Annotated[int, Gt(gt=0)] = 1, keep_original_sample: bool = True, delete_random_word: bool = False, swap_random_word: bool = False, spelling_error_word: bool = False, split_random_word: bool = False, keyboard_error_char: bool = False, ocr_error_char: bool = False, delete_random_char: bool = False, swap_random_char: bool = False, insert_random_char: bool = False, *args, **kwargs)[source]#

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.

Parameters:
  • sequential โ€“ whether combine all augmentation methods to a sequence. If itโ€™s True, a sample will be augmented by all opened augmentation methods sequentially. If itโ€™s False, each opened augmentation method would generate its augmented samples independently.

  • aug_num โ€“ number of augmented samples to be generated. If sequential is True, there will be total aug_num augmented samples generated. If itโ€™s False, there will be (aug_num * #opened_aug_method) augmented samples generated.

  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only generated texts in the final datasets and the original texts will be removed. Itโ€™s True in default.

  • delete_random_word โ€“ whether to open the augmentation method of deleting random words from the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œI LLMโ€

  • swap_random_word โ€“ whether to open the augmentation method of swapping random contiguous words in the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œLove I LLMโ€

  • spelling_error_word โ€“ whether to open the augmentation method of simulating the spelling error for words in the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œAi love LLMโ€

  • split_random_word โ€“ whether to open the augmentation method of splitting words randomly with whitespaces in the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œI love LL Mโ€

  • keyboard_error_char โ€“ whether to open the augmentation method of simulating the keyboard error for characters in the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œI ;ov4 LLMโ€

  • ocr_error_char โ€“ whether to open the augmentation method of simulating the OCR error for characters in the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œI 10ve LLMโ€

  • delete_random_char โ€“ whether to open the augmentation method of deleting random characters from the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œI oe LLMโ€

  • swap_random_char โ€“ whether to open the augmentation method of swapping random contiguous characters in the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œI ovle LLMโ€

  • insert_random_char โ€“ whether to open the augmentation method of inserting random characters into the original texts. e.g. โ€œI love LLMโ€ โ€“> โ€œI ^lKove LLMโ€

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.NlpcdaZhMapper(sequential: bool = False, aug_num: Annotated[int, Gt(gt=0)] = 1, keep_original_sample: bool = True, replace_similar_word: bool = False, replace_homophone_char: bool = False, delete_random_char: bool = False, swap_random_char: bool = False, replace_equivalent_num: bool = False, *args, **kwargs)[source]#

Bases: Mapper

Mapper to simply augment samples in Chinese based on nlpcda library.

__init__(sequential: bool = False, aug_num: Annotated[int, Gt(gt=0)] = 1, keep_original_sample: bool = True, replace_similar_word: bool = False, replace_homophone_char: bool = False, delete_random_char: bool = False, swap_random_char: bool = False, replace_equivalent_num: bool = False, *args, **kwargs)[source]#

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. Notice: some augmentation method might not work for some special texts, so there might be no augmented texts generated.

Parameters:
  • sequential โ€“ whether combine all augmentation methods to a sequence. If itโ€™s True, a sample will be augmented by all opened augmentation methods sequentially. If itโ€™s False, each opened augmentation method would generate its augmented samples independently.

  • aug_num โ€“ number of augmented samples to be generated. If sequential is True, there will be total aug_num augmented samples generated. If itโ€™s False, there will be (aug_num * #opened_aug_method) augmented samples generated.

  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only generated texts in the final datasets and the original texts will be removed. Itโ€™s True in default.

  • replace_similar_word โ€“ whether to open the augmentation method of replacing random words with their similar words in the original texts. e.g. โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบๆ–นๆณ•โ€ โ€“> โ€œ่ฟ™่พนไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบๆ–นๆณ•โ€

  • replace_homophone_char โ€“ whether to open the augmentation method of replacing random characters with their homophones in the original texts. e.g. โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบๆ–นๆณ•โ€ โ€“> โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆฟ–ๆฎๅขžๅผบๆ–นๆณ•โ€

  • delete_random_char โ€“ whether to open the augmentation method of deleting random characters from the original texts. e.g. โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบๆ–นๆณ•โ€ โ€“> โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบโ€

  • swap_random_char โ€“ whether to open the augmentation method of swapping random contiguous characters in the original texts. e.g. โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบๆ–นๆณ•โ€ โ€“> โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅผบๅขžๆ–นๆณ•โ€

  • replace_equivalent_num โ€“ whether to open the augmentation method of replacing random numbers with their equivalent representations in the original texts. Notice: Only for numbers for now. e.g. โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰5็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบๆ–นๆณ•โ€ โ€“> โ€œ่ฟ™้‡Œไธ€ๅ…ฑๆœ‰ไผ็งไธๅŒ็š„ๆ•ฐๆฎๅขžๅผบๆ–นๆณ•โ€

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.OptimizeQAMapper(hf_model: str = 'Qwen/Qwen2.5-7B-Instruct', *, system_prompt: str | None = None, input_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Bases: Mapper

Mapper to optimize question-answer pairs.

DEFAULT_SYSTEM_PROMPT = '่ฏทไผ˜ๅŒ–่พ“ๅ…ฅ็š„้—ฎ็ญ”ๅฏน๏ผŒไฝฟใ€้—ฎ้ข˜ใ€‘ๅ’Œใ€ๅ›ž็ญ”ใ€‘้ƒฝๆ›ดๅŠ ่ฏฆ็ป†ใ€ๅ‡†็กฎใ€‚ๅฟ…้กปๆŒ‰็…งไปฅไธ‹ๆ ‡่ฎฐๆ ผๅผ๏ผŒ็›ดๆŽฅ่พ“ๅ‡บไผ˜ๅŒ–ๅŽ็š„้—ฎ็ญ”ๅฏน๏ผš\nใ€้—ฎ้ข˜ใ€‘\nไผ˜ๅŒ–ๅŽ็š„้—ฎ้ข˜\nใ€ๅ›ž็ญ”ใ€‘\nไผ˜ๅŒ–ๅŽ็š„ๅ›ž็ญ”'#
DEFAULT_INPUT_TEMPLATE = 'ไปฅไธ‹ๆ˜ฏๅŽŸๅง‹้—ฎ็ญ”ๅฏน๏ผš\n{}'#
DEFAULT_QA_PAIR_TEMPLATE = 'ใ€้—ฎ้ข˜ใ€‘\n{}\nใ€ๅ›ž็ญ”ใ€‘\n{}'#
DEFAULT_OUTPUT_PATTERN = '.*?ใ€้—ฎ้ข˜ใ€‘\\s*(.*?)\\s*ใ€ๅ›ž็ญ”ใ€‘\\s*(.*)'#
__init__(hf_model: str = 'Qwen/Qwen2.5-7B-Instruct', *, system_prompt: str | None = None, input_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_model โ€“ Hugging Face model ID.

  • system_prompt โ€“ System prompt for guiding the optimization task.

  • input_template โ€“ Template for building the input for the model. Please make sure the template contains one placeholder โ€˜{}โ€™, which corresponds to the question and answer pair generated by param qa_pair_template.

  • qa_pair_template โ€“ Template for formatting the question and answer pair. Please make sure the template contains two โ€˜{}โ€™ to format question and answer.

  • output_pattern โ€“ Regular expression pattern to extract question and answer from model response.

  • enable_vllm โ€“ Whether to use VLLM for inference acceleration.

  • model_params โ€“ Parameters for initializing the model.

  • sampling_params โ€“ Sampling parameters for text generation (e.g., {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}).

  • kwargs โ€“ Extra keyword arguments.

build_input(sample)[source]#
parse_output(raw_output)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.OptimizeQueryMapper(hf_model: str = 'Qwen/Qwen2.5-7B-Instruct', *, system_prompt: str | None = None, input_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Bases: OptimizeQAMapper

Mapper to optimize query in question-answer pairs.

DEFAULT_SYSTEM_PROMPT = 'ไผ˜ๅŒ–้—ฎ็ญ”ๅฏนไธญ็š„ใ€้—ฎ้ข˜ใ€‘๏ผŒๅฐ†ๅ…ถๆ›ดๅŠ ่ฏฆ็ป†ๅ…ทไฝ“๏ผŒไฝ†ไปๅฏไปฅ็”ฑๅŽŸ็ญ”ๆกˆๅ›ž็ญ”ใ€‚ๅช่พ“ๅ‡บไผ˜ๅŒ–ๅŽ็š„ใ€้—ฎ้ข˜ใ€‘๏ผŒไธ่ฆ่พ“ๅ‡บๅคšไฝ™ๅ†…ๅฎนใ€‚'#
parse_output(raw_output)[source]#
class data_juicer.ops.mapper.OptimizeResponseMapper(hf_model: str = 'Qwen/Qwen2.5-7B-Instruct', *, system_prompt: str | None = None, input_template: str | None = None, qa_pair_template: str | None = None, output_pattern: str | None = None, enable_vllm: bool = False, model_params: Dict | None = None, sampling_params: Dict | None = None, **kwargs)[source]#

Bases: OptimizeQAMapper

Mapper to optimize response in question-answer pairs.

DEFAULT_SYSTEM_PROMPT = '่ฏทไผ˜ๅŒ–้—ฎ็ญ”ๅฏนไธญ็š„ๅ›ž็ญ”๏ผŒๅฐ†ๅ…ถๆ›ดๅŠ ่ฏฆ็ป†ๅ…ทไฝ“๏ผŒไฝ†ไปๅฏไปฅๅ›ž็ญ”ๅŽŸ้—ฎ้ข˜ใ€‚ๅช่พ“ๅ‡บไผ˜ๅŒ–ๅŽ็š„ๅ›ž็ญ”๏ผŒไธ่ฆ่พ“ๅ‡บๅคšไฝ™ๅ†…ๅฎนใ€‚'#
parse_output(raw_output)[source]#
class data_juicer.ops.mapper.PairPreferenceMapper(api_model: str = 'gpt-4o', *, api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, output_pattern: str | None = None, rejected_key: str = 'rejected_response', reason_key: str = 'reason', try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

Mapper to construct paired preference samples.

DEFAULT_SYSTEM_PROMPT = 'ไฝ ็š„ไปปๅŠกๆ˜ฏๆ นๆฎๅ‚่€ƒไฟกๆฏไฟฎๆ”น้—ฎ็ญ”ๅฏนไธญ็š„ๅ›ž็ญ”๏ผŒๅœจ่ฏญ่จ€้ฃŽๆ ผใ€ไบ‹ๅฎžๆ€งใ€ไบบ็‰ฉ่บซไปฝใ€็ซ‹ๅœบ็ญ‰ไปปไธ€ๆ–น้ขไธŽๅŽŸๅ›ž็ญ”็›ธๅใ€‚ๅฟ…้กปๆŒ‰็…งไปฅไธ‹ๆ ‡่ฎฐๆ ผๅผ่พ“ๅ‡บ๏ผŒไธ่ฆ่พ“ๅ‡บๅ…ถไป–ๅคšไฝ™ๅ†…ๅฎนใ€‚\nใ€ๅ›ž็ญ”ใ€‘\n็”Ÿๆˆ็š„ๆ–ฐๅ›ž็ญ”\nใ€ๅŽŸๅ› ใ€‘\n็”Ÿๆˆ่ฏฅๅ›ž็ญ”็š„ๅŽŸๅ› '#
DEFAULT_INPUT_TEMPLATE = 'ใ€ๅ‚่€ƒไฟกๆฏใ€‘\n{reference}\n\nไปฅไธ‹ๆ˜ฏๅŽŸๅง‹้—ฎ็ญ”ๅฏน๏ผš\nใ€้—ฎ้ข˜ใ€‘\n{query}\nใ€ๅ›ž็ญ”ใ€‘\n{response}'#
DEFAULT_OUTPUT_PATTERN = '.*?ใ€ๅ›ž็ญ”ใ€‘\\s*(.*?)\\s*ใ€ๅŽŸๅ› ใ€‘\\s*(.*)'#
__init__(api_model: str = 'gpt-4o', *, api_endpoint: str | None = None, response_path: str | None = None, system_prompt: str | None = None, input_template: str | None = None, output_pattern: str | None = None, rejected_key: str = 'rejected_response', reason_key: str = 'reason', try_num: Annotated[int, Gt(gt=0)] = 3, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method.

Parameters:
  • api_model โ€“ API model name.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt โ€“ System prompt for guiding the generation task.

  • input_template โ€“ Template for building the model input. It must contain placeholders โ€˜{query}โ€™ and โ€˜{response}โ€™, and can optionally include โ€˜{reference}โ€™.

  • output_pattern โ€“ Regular expression for parsing model output.

  • rejected_key โ€“ The field name in the sample to store the generated rejected response. Defaults to โ€˜rejected_responseโ€™.

  • reason_key โ€“ The field name in the sample to store the reason for generating the response. Defaults to โ€˜reasonโ€™.

  • try_num โ€“ The number of retries for the API call in case of response parsing failure. Defaults to 3.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

build_input(sample)[source]#
parse_output(raw_output)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.PunctuationNormalizationMapper(*args, **kwargs)[source]#

Bases: Mapper

Mapper to normalize unicode punctuations to English punctuations in text samples.

__init__(*args, **kwargs)[source]#

Initialization method.

Parameters:
  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.PythonFileMapper(file_path: str = '', function_name: str = 'process_single', batched: bool = False, **kwargs)[source]#

Bases: Mapper

Mapper for executing Python function defined in a file.

__init__(file_path: str = '', function_name: str = 'process_single', batched: bool = False, **kwargs)[source]#

Initialization method.

Parameters:
  • file_path โ€“ The path to the Python file containing the function to be executed.

  • function_name โ€“ The name of the function defined in the file to be executed.

  • batched โ€“ A boolean indicating whether to process input data in batches.

  • kwargs โ€“ Additional keyword arguments passed to the parent class.

process_single(sample)[source]#

Invoke the loaded function with the provided sample.

process_batched(samples)[source]#

Invoke the loaded function with the provided samples.

class data_juicer.ops.mapper.PythonLambdaMapper(lambda_str: str = '', batched: bool = False, **kwargs)[source]#

Bases: Mapper

Mapper for executing Python lambda function on data samples.

__init__(lambda_str: str = '', batched: bool = False, **kwargs)[source]#

Initialization method.

Parameters:
  • lambda_str โ€“ A string representation of the lambda function to be executed on data samples. If empty, the identity function is used.

  • batched โ€“ A boolean indicating whether to process input data in batches.

  • kwargs โ€“ Additional keyword arguments passed to the parent class.

process_single(sample)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

process_batched(samples)[source]#
class data_juicer.ops.mapper.QuerySentimentDetectionMapper(hf_model: str = 'mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis', zh_to_en_hf_model: str | None = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, *, label_key: str = 'query_sentiment_label', score_key: str = 'query_sentiment_label_score', **kwargs)[source]#

Bases: Mapper

Mapper to predict userโ€™s sentiment label (โ€˜negativeโ€™, โ€˜neutralโ€™ and โ€˜positiveโ€™) in query. Input from query_key. Output label and corresponding score for the query, which is store in โ€˜query_sentiment_labelโ€™ and โ€˜query_sentiment_label_scoreโ€™ in Data-Juicer meta field.

__init__(hf_model: str = 'mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis', zh_to_en_hf_model: str | None = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, *, label_key: str = 'query_sentiment_label', score_key: str = 'query_sentiment_label_score', **kwargs)[source]#

Initialization method.

Parameters:
  • hf_model โ€“ Huggingface model ID to predict sentiment label.

  • zh_to_en_hf_model โ€“ Translation model from Chinese to English. If not None, translate the query from Chinese to English.

  • model_params โ€“ model param for hf_model.

  • zh_to_en_model_params โ€“ model param for zh_to_hf_model.

  • label_key โ€“ The key name in the meta field to store the output label. It is โ€˜query_sentiment_labelโ€™ in default.

  • score_key โ€“ The key name in the meta field to store the corresponding label score. It is โ€˜query_sentiment_label_scoreโ€™ in default.

  • kwargs โ€“ Extra keyword arguments.

process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.QueryIntentDetectionMapper(hf_model: str = 'bespin-global/klue-roberta-small-3i4k-intent-classification', zh_to_en_hf_model: str | None = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, *, label_key: str = 'query_intent_label', score_key: str = 'query_intent_label_score', **kwargs)[source]#

Bases: Mapper

Mapper to predict userโ€™s Intent label in query. Input from query_key. Output intent label and corresponding score for the query.

__init__(hf_model: str = 'bespin-global/klue-roberta-small-3i4k-intent-classification', zh_to_en_hf_model: str | None = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, *, label_key: str = 'query_intent_label', score_key: str = 'query_intent_label_score', **kwargs)[source]#

Initialization method.

Parameters:
  • hf_model โ€“ Huggingface model ID to predict intent label.

  • zh_to_en_hf_model โ€“ Translation model from Chinese to English. If not None, translate the query from Chinese to English.

  • model_params โ€“ model param for hf_model.

  • zh_to_en_model_params โ€“ model param for zh_to_hf_model.

  • label_key โ€“ The key name in the meta field to store the output label. It is โ€˜query_intent_labelโ€™ in default.

  • score_key โ€“ The key name in the meta field to store the corresponding label score. It is โ€˜query_intent_label_scoreโ€™ in default.

  • kwargs โ€“ Extra keyword arguments.

process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.QueryTopicDetectionMapper(hf_model: str = 'dstefa/roberta-base_topic_classification_nyt_news', zh_to_en_hf_model: str | None = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, *, label_key: str = 'query_topic_label', score_key: str = 'query_topic_label_score', **kwargs)[source]#

Bases: Mapper

Mapper to predict userโ€™s topic label in query. Input from query_key. Output topic label and corresponding score for the query, which is store in โ€˜query_topic_labelโ€™ and โ€˜query_topic_label_scoreโ€™ in Data-Juicer meta field.

__init__(hf_model: str = 'dstefa/roberta-base_topic_classification_nyt_news', zh_to_en_hf_model: str | None = 'Helsinki-NLP/opus-mt-zh-en', model_params: Dict = {}, zh_to_en_model_params: Dict = {}, *, label_key: str = 'query_topic_label', score_key: str = 'query_topic_label_score', **kwargs)[source]#

Initialization method.

Parameters:
  • hf_model โ€“ Huggingface model ID to predict topic label.

  • zh_to_en_hf_model โ€“ Translation model from Chinese to English. If not None, translate the query from Chinese to English.

  • model_params โ€“ model param for hf_model.

  • zh_to_en_model_params โ€“ model param for zh_to_hf_model.

  • label_key โ€“ The key name in the meta field to store the output label. It is โ€˜query_topic_labelโ€™ in default.

  • score_key โ€“ The key name in the meta field to store the corresponding label score. It is โ€˜query_topic_label_scoreโ€™ in default.

  • kwargs โ€“ Extra keyword arguments.

process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.RelationIdentityMapper(api_model: str = 'gpt-4o', source_entity: str = None, target_entity: str = None, *, output_key: str = 'role_relation', api_endpoint: str | None = None, response_path: str | None = None, system_prompt_template: str | None = None, input_template: str | None = None, output_pattern_template: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Bases: Mapper

identify relation between two entity in the text.

DEFAULT_SYSTEM_PROMPT_TEMPLATE = '็ป™ๅฎšๅ…ณไบŽ{entity1}ๅ’Œ{entity2}็š„ๆ–‡ๆœฌไฟกๆฏใ€‚ๅˆคๆ–ญ{entity1}ๅ’Œ{entity2}ไน‹้—ด็š„ๅ…ณ็ณปใ€‚\n่ฆๆฑ‚๏ผš\n- ๅ…ณ็ณป็”จไธ€ไธชๆˆ–ๅคšไธช่ฏ่ฏญ่กจ็คบ๏ผŒๅฟ…่ฆๆ—ถๅฏไปฅๅŠ ไธ€ไธชๅฝขๅฎน่ฏๆฅๆ่ฟฐ่ฟ™ๆฎตๅ…ณ็ณป\n- ่พ“ๅ‡บๅ…ณ็ณปๆ—ถไธ่ฆๅ‚ๆ‚ไปปไฝ•ๆ ‡็‚น็ฌฆๅท\n- ้œ€่ฆไฝ ่ฟ›่กŒๅˆ็†็š„ๆŽจ็†ๆ‰่ƒฝๅพ—ๅ‡บ็ป“่ฎบ\n- ๅฆ‚ๆžœไธคไธชไบบ็‰ฉ่บซไปฝๆ˜ฏๅŒไธ€ไธชไบบ๏ผŒ่พ“ๅ‡บๅ…ณ็ณปไธบ๏ผšๅฆไธ€ไธช่บซไปฝ\n- ่พ“ๅ‡บๆ ผๅผไธบ๏ผš\nๅˆ†ๆžๆŽจ็†๏ผš...\nๆ‰€ไปฅ{entity2}ๆ˜ฏ{entity1}็š„๏ผš...\n- ๆณจๆ„่พ“ๅ‡บ็š„ๆ˜ฏ{entity2}ๆ˜ฏ{entity1}็š„ไป€ไนˆๅ…ณ็ณป๏ผŒ่€Œไธๆ˜ฏ{entity1}ๆ˜ฏ{entity2}็š„ไป€ไนˆๅ…ณ็ณป'#
DEFAULT_INPUT_TEMPLATE = 'ๅ…ณไบŽ{entity1}ๅ’Œ{entity2}็š„ๆ–‡ๆœฌไฟกๆฏ๏ผš\n```\n{text}\n```\n'#
DEFAULT_OUTPUT_PATTERN_TEMPLATE = '\n        \\s*ๅˆ†ๆžๆŽจ็†๏ผš\\s*(.*?)\\s*\n        \\s*ๆ‰€ไปฅ{entity2}ๆ˜ฏ{entity1}็š„๏ผš\\s*(.*?)\\Z\n    '#
__init__(api_model: str = 'gpt-4o', source_entity: str = None, target_entity: str = None, *, output_key: str = 'role_relation', api_endpoint: str | None = None, response_path: str | None = None, system_prompt_template: str | None = None, input_template: str | None = None, output_pattern_template: str | None = None, try_num: Annotated[int, Gt(gt=0)] = 3, drop_text: bool = False, model_params: Dict = {}, sampling_params: Dict = {}, **kwargs)[source]#

Initialization method. :param api_model: API model name. :param source_entity: The source entity of the relation to be

identified.

Parameters:
  • target_entity โ€“ The target entity of the relation to be identified.

  • output_key โ€“ The output key in the meta field in the samples. It is โ€˜role_relationโ€™ in default.

  • api_endpoint โ€“ URL endpoint for the API.

  • response_path โ€“ Path to extract content from the API response. Defaults to โ€˜choices.0.message.contentโ€™.

  • system_prompt_template โ€“ System prompt template for the task.

  • input_template โ€“ Template for building the model input.

  • output_pattern_template โ€“ Regular expression template for parsing model output.

  • try_num โ€“ The number of retry attempts when there is an API call error or output parsing error.

  • drop_text โ€“ If drop the text in the output.

  • model_params โ€“ Parameters for initializing the API model.

  • sampling_params โ€“ Extra parameters passed to the API call. e.g {โ€˜temperatureโ€™: 0.9, โ€˜top_pโ€™: 0.95}

  • kwargs โ€“ Extra keyword arguments.

parse_output(raw_output)[source]#
process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.RemoveBibliographyMapper(*args, **kwargs)[source]#

Bases: Mapper

Mapper to remove bibliography at the end of documents in Latex samples.

__init__(*args, **kwargs)[source]#

Initialization method.

Parameters:
  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveCommentsMapper(doc_type: str | List[str] = 'tex', inline: bool = True, multiline: bool = True, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove comments in different kinds of documents.

Only support โ€˜texโ€™ for now.

__init__(doc_type: str | List[str] = 'tex', inline: bool = True, multiline: bool = True, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • doc_type โ€“ Type of document to remove comments.

  • inline โ€“ Whether to remove inline comments.

  • multiline โ€“ Whether to remove multiline comments.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveHeaderMapper(drop_no_head: bool = True, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove headers at the beginning of documents in Latex samples.

__init__(drop_no_head: bool = True, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • drop_no_head โ€“ whether to drop sample texts without headers.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveLongWordsMapper(min_len: int = 1, max_len: int = 9223372036854775807, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove long words within a specific range.

__init__(min_len: int = 1, max_len: int = 9223372036854775807, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • min_len โ€“ The min mapper word length in this op, words will be filtered if their length is below this parameter.

  • max_len โ€“ The max mapper word length in this op, words will be filtered if their length exceeds this parameter.

  • args โ€“ extra args

  • kwargs โ€“ extra args

should_keep_long_word(word)[source]#
process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveNonChineseCharacterlMapper(keep_alphabet: bool = True, keep_number: bool = True, keep_punc: bool = True, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove non chinese Character in text samples.

__init__(keep_alphabet: bool = True, keep_number: bool = True, keep_punc: bool = True, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • keep_alphabet โ€“ whether to keep alphabet

  • keep_number โ€“ whether to keep number

  • keep_punc โ€“ whether to keep punctuation

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveRepeatSentencesMapper(lowercase: bool = False, ignore_special_character: bool = True, min_repeat_sentence_length: int = 2, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove repeat sentences in text samples.

__init__(lowercase: bool = False, ignore_special_character: bool = True, min_repeat_sentence_length: int = 2, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • lowercase โ€“ Whether to convert sample text to lower case

  • ignore_special_character โ€“ Whether to ignore special characters when judging repeated sentences. Special characters are all characters except Chinese characters, letters and numbers.

  • min_repeat_sentence_length โ€“ Sentences shorter than this length will not be deduplicated. If ignore_special_character is set to True, then special characters are not included in this length.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveSpecificCharsMapper(chars_to_remove: str | List[str] = 'โ—†โ—โ– โ–บโ–ผโ–ฒโ–ดโˆ†โ–ปโ–ทโ–โ™กโ–ก', *args, **kwargs)[source]#

Bases: Mapper

Mapper to clean specific chars in text samples.

__init__(chars_to_remove: str | List[str] = 'โ—†โ—โ– โ–บโ–ผโ–ฒโ–ดโˆ†โ–ปโ–ทโ–โ™กโ–ก', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • chars_to_remove โ€“ a list or a string including all characters that need to be removed from text.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveTableTextMapper(min_col: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=2), Le(le=20)])] = 2, max_col: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=2), Le(le=20)])] = 20, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove table texts from text samples.

Regular expression is used to remove tables in the range of column number of tables.

__init__(min_col: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=2), Le(le=20)])] = 2, max_col: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=2), Le(le=20)])] = 20, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • min_col โ€“ The min number of columns of table to remove.

  • max_col โ€“ The max number of columns of table to remove.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.RemoveWordsWithIncorrectSubstringsMapper(lang: str = 'en', tokenization: bool = False, substrings: List[str] | None = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to remove words with incorrect substrings.

__init__(lang: str = 'en', tokenization: bool = False, substrings: List[str] | None = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • lang โ€“ sample in which language

  • tokenization โ€“ whether to use model to tokenize documents

  • substrings โ€“ The incorrect substrings in words.

  • args โ€“ extra args

  • kwargs โ€“ extra args

should_keep_word_with_incorrect_substrings(word, substrings)[source]#
process_batched(samples)[source]#
class data_juicer.ops.mapper.ReplaceContentMapper(pattern: str | List[str] | None = None, repl: str | List[str] = '', *args, **kwargs)[source]#

Bases: Mapper

Mapper to replace all content in the text that matches a specific regular expression pattern with a designated replacement string.

__init__(pattern: str | List[str] | None = None, repl: str | List[str] = '', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • pattern โ€“ regular expression pattern(s) to search for within text

  • repl โ€“ replacement string(s), default is empty string

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.SDXLPrompt2PromptMapper(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_second=None, output_dir='/home/runner/.cache/data_juicer/assets', *args, **kwargs)[source]#

Bases: Mapper

Generate pairs of similar images by the SDXL model

__init__(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_second=None, output_dir='/home/runner/.cache/data_juicer/assets', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_diffusion โ€“ diffusion model name on huggingface to generate the image.

  • torch_dtype โ€“ the floating point type used to load the diffusion model.

  • num_inference_steps โ€“ The larger the value, the better the

image generation quality; however, this also increases the time required for generation. :param guidance_scale: A higher guidance scale value encourages the

model to generate images closely linked to the text prompt at the expense of lower image quality. Guidance scale is enabled when

Parameters:
  • text_key โ€“ the key name used to store the first caption in the caption pair.

  • text_key_second โ€“ the key name used to store the second caption in the caption pair.

  • output_dir โ€“ the storage location of the generated images.

process_single(sample, rank=None, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.SentenceAugmentationMapper(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_key=None, text_key_second=None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to augment sentences. The purpose of this operation is to enhance sentences. If the input text is at the document level, the enhancement effect may not be optimal. Therefore, please consider the length of the input text carefully.

Recommended model list: [

lmsys/vicuna-13b-v1.5 Qwen/Qwen2-7B-Instruct

]

__init__(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_key=None, text_key_second=None, *args, **kwargs)[source]#

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.

Parameters:
  • temperature โ€“ used to control the randomness of generated text. The higher the temperature, the more random and creative the generated text will be.

  • top_p โ€“ randomly select the next word from the group of words whose cumulative probability reaches p.

  • num_beams โ€“ the larger the beam search size, the higher the quality of the generated text.

  • text_key โ€“ the key name used to store the first sentence in the text pair. (optional, defalut=โ€™textโ€™)

  • text_key_second โ€“ the key name used to store the second sentence in the text pair.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample=None, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.SentenceSplitMapper(lang: str = 'en', *args, **kwargs)[source]#

Bases: Mapper

Mapper to split text samples to sentences.

__init__(lang: str = 'en', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • lang โ€“ split sentence of text in which language.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#
class data_juicer.ops.mapper.TextChunkMapper(max_len: Annotated[int, Gt(gt=0)] | None = None, split_pattern: str | None = '\\n\\n', overlap_len: Annotated[int, Ge(ge=0)] = 0, tokenizer: str | None = None, trust_remote_code: bool = False, *args, **kwargs)[source]#

Bases: Mapper

Split input text to chunks.

__init__(max_len: Annotated[int, Gt(gt=0)] | None = None, split_pattern: str | None = '\\n\\n', overlap_len: Annotated[int, Ge(ge=0)] = 0, tokenizer: str | None = None, trust_remote_code: bool = False, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • max_len โ€“ Split text into multi texts with this max len if not None.

  • split_pattern โ€“ Make sure split in this pattern if it is not None and force cut if the length exceeds max_len.

  • overlap_len โ€“ Overlap length of the split texts if not split in the split pattern.

  • tokenizer โ€“ The tokenizer name of Hugging Face tokenizers. The text length will be calculate as the token num if it is offered. Otherwise, the text length equals to string length. Support tiktoken tokenizer (such as gpt-4o), dashscope tokenizer ( such as qwen2.5-72b-instruct) and huggingface tokenizer.

  • args โ€“ extra args

  • kwargs โ€“ extra args

Trust_remote_code:

for loading huggingface model

recursively_chunk(text)[source]#
get_text_chunks(text, rank=None)[source]#
process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.VideoCaptioningFromAudioMapper(keep_original_sample: bool = True, *args, **kwargs)[source]#

Bases: Mapper

Mapper to caption a video according to its audio streams based on Qwen-Audio model.

__init__(keep_original_sample: bool = True, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • 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.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.VideoCaptioningFromFramesMapper(hf_img2seq: str = 'Salesforce/blip2-opt-2.7b', trust_remote_code: bool = False, caption_num: Annotated[int, Gt(gt=0)] = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: str | None = None, prompt_key: str | None = None, frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, horizontal_flip: bool = False, vertical_flip: bool = False, *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate samples whose captions are generated based on an image-to-text model and sampled video frames. Captions from different frames will be concatenated to a single string.

__init__(hf_img2seq: str = 'Salesforce/blip2-opt-2.7b', trust_remote_code: bool = False, caption_num: Annotated[int, Gt(gt=0)] = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: str | None = None, prompt_key: str | None = None, frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, horizontal_flip: bool = False, vertical_flip: bool = False, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_img2seq โ€“ model name on huggingface to generate caption

  • caption_num โ€“ how many candidate captions to generate for each video

  • keep_candidate_mode โ€“

    retain strategy for the generated $caption_num$ candidates.

    โ€™random_anyโ€™: Retain the random one from generated captions

    โ€™similar_one_simhashโ€™: Retain the generated one that is most

    similar to the original caption

    โ€™allโ€™: Retain all generated captions by concatenation

Note

This is a batched_OP, whose input and output type are both list. Suppose there are $N$ list of input samples, whose batch size is $b$, and denote caption_num as $M$. The number of total samples after generation is $2Nb$ when keep_original_sample is True and $Nb$ when keep_original_sample is False. For โ€˜random_anyโ€™ and โ€˜similar_one_simhashโ€™ mode, itโ€™s $(1+M)Nb$ for โ€˜allโ€™ mode when keep_original_sample is True and $MNb$ when keep_original_sample is False.

Parameters:
  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only generated captions in the final datasets and the original captions will be removed. Itโ€™s True in default.

  • prompt โ€“ a string prompt to guide the generation of image-to-text model for all samples globally. Itโ€™s None in default, which means no prompt provided.

  • prompt_key โ€“ the key name of fields in samples to store prompts for each sample. Itโ€™s used for set different prompts for different samples. If itโ€™s none, use prompt in parameter โ€œpromptโ€. Itโ€™s None in default.

  • 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 video) and the latter one extract specified number of frames uniformly from the video. Default: โ€œall_keyframesโ€.

  • frame_num โ€“ the number of frames to be extracted uniformly from the video. Only works when frame_sampling_method is โ€œuniformโ€. If itโ€™s 1, only the middle frame will be extracted. If itโ€™s 2, only the first and the last frames will be extracted. If itโ€™s larger than 2, in addition to the first and the last frames, other frames will be extracted uniformly within the video duration.

  • horizontal_flip โ€“ flip frame video horizontally (left to right).

  • vertical_flip โ€“ flip frame video vertically (top to bottom).

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples, rank=None, context=False)[source]#
Parameters:

samples

Returns:

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 $2Nb$ for โ€˜random_anyโ€™ and โ€˜similar_oneโ€™ mode, and $(1+M)Nb$ for โ€˜allโ€™ mode.

class data_juicer.ops.mapper.VideoCaptioningFromSummarizerMapper(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, consider_video_tags_from_audio: bool = True, consider_video_tags_from_frames: bool = True, vid_cap_from_vid_args: Dict | None = None, vid_cap_from_frm_args: Dict | None = None, vid_tag_from_aud_args: Dict | None = None, vid_tag_from_frm_args: Dict | None = None, keep_tag_num: Annotated[int, Gt(gt=0)] = 5, keep_original_sample: bool = True, *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate video captions by summarizing several kinds of generated texts (captions from video/audio/frames, tags from audio/frames, โ€ฆ)

__init__(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, consider_video_tags_from_audio: bool = True, consider_video_tags_from_frames: bool = True, vid_cap_from_vid_args: Dict | None = None, vid_cap_from_frm_args: Dict | None = None, vid_tag_from_aud_args: Dict | None = None, vid_tag_from_frm_args: Dict | None = None, keep_tag_num: Annotated[int, Gt(gt=0)] = 5, keep_original_sample: bool = True, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_summarizer โ€“ the summarizer model used to summarize texts generated by other methods.

  • consider_video_caption_from_video โ€“ whether to consider the video caption generated from video directly in the summarization process. Default: True.

  • consider_video_caption_from_audio โ€“ whether to consider the video caption generated from audio streams in the video in the summarization process. Default: True.

  • consider_video_caption_from_frames โ€“ whether to consider the video caption generated from sampled frames from the video in the summarization process. Default: True.

  • consider_video_tags_from_audio โ€“ whether to consider the video tags generated from audio streams in the video in the summarization process. Default: True.

  • consider_video_tags_from_frames โ€“ whether to consider the video tags generated from sampled frames from the video in the summarization process. Default: True.

  • vid_cap_from_vid_args โ€“ the arg dict for video captioning from video directly with keys are the arg names and values are the arg values. Default: None.

  • vid_cap_from_frm_args โ€“ the arg dict for video captioning from sampled frames from the video with keys are the arg names and values are the arg values. Default: None.

  • vid_tag_from_aud_args โ€“ the arg dict for video tagging from audio streams in the video with keys are the arg names and values are the arg values. Default: None.

  • vid_tag_from_frm_args โ€“ the arg dict for video tagging from sampled frames from the video with keys are the arg names and values are the arg values. Default: None.

  • keep_tag_num โ€“ max number N of tags from sampled frames to keep. Too many tags might bring negative influence to summarized text, so we consider to only keep the N most frequent tags. Default: 5.

  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only summarized captions in the final datasets and the original captions will be removed. Itโ€™s True in default.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples, rank=None)[source]#
class data_juicer.ops.mapper.VideoCaptioningFromVideoMapper(hf_video_blip: str = 'kpyu/video-blip-opt-2.7b-ego4d', trust_remote_code: bool = False, caption_num: Annotated[int, Gt(gt=0)] = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: str | None = None, prompt_key: str | None = None, frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, horizontal_flip: bool = False, vertical_flip: bool = False, *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate samples whose captions are generated based on a video-to-text model and sampled video frame.

__init__(hf_video_blip: str = 'kpyu/video-blip-opt-2.7b-ego4d', trust_remote_code: bool = False, caption_num: Annotated[int, Gt(gt=0)] = 1, keep_candidate_mode: str = 'random_any', keep_original_sample: bool = True, prompt: str | None = None, prompt_key: str | None = None, frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, horizontal_flip: bool = False, vertical_flip: bool = False, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_video_blip โ€“ video-blip model name on huggingface to generate caption

  • caption_num โ€“ how many candidate captions to generate for each video

  • keep_candidate_mode โ€“

    retain strategy for the generated $caption_num$ candidates.

    โ€™random_anyโ€™: Retain the random one from generated captions

    โ€™similar_one_simhashโ€™: Retain the generated one that is most

    similar to the original caption

    โ€™allโ€™: Retain all generated captions by concatenation

Note

This is a batched_OP, whose input and output type are both list. Suppose there are $N$ list of input samples, whose batch size is $b$, and denote caption_num as $M$. The number of total samples after generation is $2Nb$ when keep_original_sample is True and $Nb$ when keep_original_sample is False. For โ€˜random_anyโ€™ and โ€˜similar_one_simhashโ€™ mode, itโ€™s $(1+M)Nb$ for โ€˜allโ€™ mode when keep_original_sample is True and $MNb$ when keep_original_sample is False.

Parameters:
  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only generated captions in the final datasets and the original captions will be removed. Itโ€™s True in default.

  • prompt โ€“ a string prompt to guide the generation of video-blip model for all samples globally. Itโ€™s None in default, which means no prompt provided.

  • prompt_key โ€“ the key name of fields in samples to store prompts for each sample. Itโ€™s used for set different prompts for different samples. If itโ€™s none, use prompt in parameter โ€œpromptโ€. Itโ€™s None in default.

  • 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 video) and the latter one extract specified number of frames uniformly from the video. Default: โ€œall_keyframesโ€.

  • frame_num โ€“ the number of frames to be extracted uniformly from the video. Only works when frame_sampling_method is โ€œuniformโ€. If itโ€™s 1, only the middle frame will be extracted. If itโ€™s 2, only the first and the last frames will be extracted. If itโ€™s larger than 2, in addition to the first and the last frames, other frames will be extracted uniformly within the video duration.

  • horizontal_flip โ€“ flip frame video horizontally (left to right).

  • vertical_flip โ€“ flip frame video vertically (top to bottom).

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples, rank=None, context=False)[source]#
Parameters:

samples

Returns:

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 $2Nb$ for โ€˜random_anyโ€™ and โ€˜similar_oneโ€™ mode, and $(1+M)Nb$ for โ€˜allโ€™ mode.

class data_juicer.ops.mapper.VideoExtractFramesMapper(frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, duration: float = 0, frame_dir: str = None, frame_key='video_frames', *args, **kwargs)[source]#

Bases: Mapper

Mapper to extract frames from video files according to specified methods. Extracted Frames Data Format:

The data format for the extracted frames is a dictionary mapping video key to extracted frames directory where the extracted frames are saved. The dictionary follows the structure: {

โ€œvideo_key_1โ€: โ€œ/${frame_dir}/video_key_1_filename/โ€, โ€œvideo_key_2โ€: โ€œ/${frame_dir}/video_key_2_filename/โ€, โ€ฆ

}

__init__(frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, duration: float = 0, frame_dir: str = None, frame_key='video_frames', *args, **kwargs)[source]#

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 video) and the latter one extract specified number of frames uniformly from the video. If โ€œdurationโ€ > 0, frame_sampling_method acts on every segment. Default: โ€œall_keyframesโ€.

Parameters:
  • frame_num โ€“ the number of frames to be extracted uniformly from the video. Only works when frame_sampling_method is โ€œuniformโ€. If itโ€™s 1, only the middle frame will be extracted. If itโ€™s 2, only the first and the last frames will be extracted. If itโ€™s larger than 2, in addition to the first and the last frames, other frames will be extracted uniformly within the video duration. If โ€œdurationโ€ > 0, frame_num is the number of frames per segment.

  • duration โ€“ The duration of each segment in seconds. If 0, frames are extracted from the entire video. If duration > 0, the video is segmented into multiple segments based on duration, and frames are extracted from each segment.

  • frame_dir โ€“ Output directory to save extracted frames. If None, a default directory based on the video file path is used.

  • frame_key โ€“ The name of field to save generated frames info.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoFFmpegWrappedMapper(filter_name: str | None = None, filter_kwargs: Dict | None = None, global_args: List[str] | None = None, capture_stderr: bool = True, overwrite_output: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Simple wrapper for FFmpeg video filters.

__init__(filter_name: str | None = None, filter_kwargs: Dict | None = None, global_args: List[str] | None = None, capture_stderr: bool = True, overwrite_output: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • filter_name โ€“ ffmpeg video filter name.

  • filter_kwargs โ€“ keyword-arguments passed to ffmpeg filter.

  • global_args โ€“ list-arguments passed to ffmpeg command-line.

  • capture_stderr โ€“ whether to capture stderr.

  • overwrite_output โ€“ whether to overwrite output file.

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoFaceBlurMapper(cv_classifier: str = '', blur_type: str = 'gaussian', radius: float = 2, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to blur faces detected in videos.

__init__(cv_classifier: str = '', blur_type: str = 'gaussian', radius: float = 2, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • cv_classifier โ€“ OpenCV classifier path for face detection. By default, we will use โ€˜haarcascade_frontalface_alt.xmlโ€™.

  • blur_type โ€“ Type of blur kernel, including [โ€˜meanโ€™, โ€˜boxโ€™, โ€˜gaussianโ€™].

  • radius โ€“ Radius of blur kernel.

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoRemoveWatermarkMapper(roi_strings: List[str] = ['0,0,0.1,0.1'], roi_type: str = 'ratio', roi_key: str | None = None, frame_num: Annotated[int, Gt(gt=0)] = 10, min_frame_threshold: Annotated[int, Gt(gt=0)] = 7, detection_method: str = 'pixel_value', save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Remove the watermarks in videos given regions.

__init__(roi_strings: List[str] = ['0,0,0.1,0.1'], roi_type: str = 'ratio', roi_key: str | None = None, frame_num: Annotated[int, Gt(gt=0)] = 10, min_frame_threshold: Annotated[int, Gt(gt=0)] = 7, detection_method: str = 'pixel_value', save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • 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]โ€.

  • roi_type โ€“ the roi string type. 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.

  • roi_key โ€“ the key name of fields in samples to store roi_strings for each sample. Itโ€™s used for set different rois for different samples. If itโ€™s none, use rois in parameter โ€œroi_stringsโ€. Itโ€™s None in default.

  • frame_num โ€“ the number of frames to be extracted uniformly from the video to detect the pixels of watermark.

  • min_frame_threshold โ€“ a coordination is considered as the location of a watermark pixel when it is that in no less min_frame_threshold frames.

  • detection_method โ€“ the method to detect the pixels of watermark. If it is โ€˜pixel_valueโ€™, we consider the distribution of pixel value in each frame. If it is โ€˜pixel_diversityโ€™, we will consider the pixel diversity in different frames. The min_frame_threshold is useless and frame_num must be greater than 1 in โ€˜pixel_diversityโ€™ mode.

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoResizeAspectRatioMapper(min_ratio: str = '9/21', max_ratio: str = '21/9', strategy: str = 'increase', save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to resize videos by aspect ratio. AspectRatio = W / H.

STRATEGY = ['decrease', 'increase']#
__init__(min_ratio: str = '9/21', max_ratio: str = '21/9', strategy: str = 'increase', save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • 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โ€.

  • max_ratio โ€“ The maximum aspect ratio to enforce videos with an aspect ratio above max_ratio will be resized to match this maximum ratio. The ratio should be provided as a string in the format โ€œ21:9โ€ or โ€œ21/9โ€.

  • strategy โ€“ The resizing strategy to apply when adjusting the video dimensions. It can be either โ€˜decreaseโ€™ to reduce the dimension or โ€˜increaseโ€™ to enlarge it. Accepted values are [โ€˜decreaseโ€™, โ€˜increaseโ€™].

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoResizeResolutionMapper(min_width: int = 1, max_width: int = 9223372036854775807, min_height: int = 1, max_height: int = 9223372036854775807, force_original_aspect_ratio: str = 'disable', force_divisible_by: Annotated[int, Gt(gt=0)] = 2, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to resize videos resolution. We leave the super resolution with deep learning for future works.

__init__(min_width: int = 1, max_width: int = 9223372036854775807, min_height: int = 1, max_height: int = 9223372036854775807, force_original_aspect_ratio: str = 'disable', force_divisible_by: Annotated[int, Gt(gt=0)] = 2, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • min_width โ€“ Videos with width less than โ€˜min_widthโ€™ will be mapped to videos with equal or bigger width.

  • max_width โ€“ Videos with width more than โ€˜max_widthโ€™ will be mapped to videos with equal of smaller width.

  • min_height โ€“ Videos with height less than โ€˜min_heightโ€™ will be mapped to videos with equal or bigger height.

  • max_height โ€“ Videos with height more than โ€˜max_heightโ€™ will be mapped to videos with equal or smaller height.

  • force_original_aspect_ratio โ€“ Enable decreasing or increasing output video width or height if necessary to keep the original aspect ratio, including [โ€˜disableโ€™, โ€˜decreaseโ€™, โ€˜increaseโ€™].

  • force_divisible_by โ€“ Ensures that both the output dimensions, width and height, are divisible by the given integer when used together with force_original_aspect_ratio, must be a positive even number.

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoSplitByDurationMapper(split_duration: float = 10, min_last_split_duration: float = 0, keep_original_sample: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to split video by duration.

__init__(split_duration: float = 10, min_last_split_duration: float = 0, keep_original_sample: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • split_duration โ€“ duration of each video split in seconds.

  • 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.

  • keep_original_sample โ€“ whether to keep the original sample. If itโ€™s set to False, there will be only cut sample in the final datasets and the original sample will be removed. Itโ€™s True in default.

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

split_videos_by_duration(video_key, container)[source]#
process_batched(samples)[source]#
class data_juicer.ops.mapper.VideoSplitByKeyFrameMapper(keep_original_sample: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to split video by key frame.

__init__(keep_original_sample: bool = True, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • 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.

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

get_split_key_frame(video_key, container)[source]#
process_batched(samples)[source]#
class data_juicer.ops.mapper.VideoSplitBySceneMapper(detector: str = 'ContentDetector', threshold: Annotated[float, Ge(ge=0)] = 27.0, min_scene_len: Annotated[int, Ge(ge=0)] = 15, show_progress: bool = False, save_dir: str = None, *args, **kwargs)[source]#

Bases: Mapper

Mapper to cut videos into scene clips.

avaliable_detectors = {'AdaptiveDetector': ['window_width', 'min_content_val', 'weights', 'luma_only', 'kernel_size', 'video_manager', 'min_delta_hsv'], 'ContentDetector': ['weights', 'luma_only', 'kernel_size'], 'ThresholdDetector': ['fade_bias', 'add_final_scene', 'method', 'block_size']}#
__init__(detector: str = 'ContentDetector', threshold: Annotated[float, Ge(ge=0)] = 27.0, min_scene_len: Annotated[int, Ge(ge=0)] = 15, show_progress: bool = False, save_dir: str = None, *args, **kwargs)[source]#

Initialization method.

Parameters:
  • detector โ€“ Algorithm from scenedetect.detectors. Should be one of [โ€˜ContentDetectorโ€™, โ€˜ThresholdDetectorโ€™, โ€˜AdaptiveDetector`].

  • threshold โ€“ Threshold passed to the detector.

  • min_scene_len โ€“ Minimum length of any scene.

  • show_progress โ€“ Whether to show progress from scenedetect.

  • save_dir โ€“ The directory where generated video files will be stored. If not specified, outputs will be saved in the same directory as their corresponding input files. This path can alternatively be defined by setting the DJ_PRODUCED_DATA_DIR environment variable.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoTaggingFromAudioMapper(hf_ast: str = 'MIT/ast-finetuned-audioset-10-10-0.4593', trust_remote_code: bool = False, tag_field_name: str = 'video_audio_tags', *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate video tags from audio streams extracted by video using the Audio Spectrogram Transformer.

__init__(hf_ast: str = 'MIT/ast-finetuned-audioset-10-10-0.4593', trust_remote_code: bool = False, tag_field_name: str = 'video_audio_tags', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • hf_ast โ€“ path to the HF model to tag from audios.

  • trust_remote_code โ€“ whether to trust the remote code of HF models

  • tag_field_name โ€“ the field name to store the tags. Itโ€™s โ€œvideo_audio_tagsโ€ in default.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, rank=None)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.VideoTaggingFromFramesMapper(frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, tag_field_name: str = 'video_frame_tags', *args, **kwargs)[source]#

Bases: Mapper

Mapper to generate video tags from frames extract by video.

__init__(frame_sampling_method: str = 'all_keyframes', frame_num: Annotated[int, Gt(gt=0)] = 3, tag_field_name: str = 'video_frame_tags', *args, **kwargs)[source]#

Initialization method.

Parameters:
  • 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 video) and the latter one extract specified number of frames uniformly from the video. Default: โ€œall_keyframesโ€.

  • frame_num โ€“ the number of frames to be extracted uniformly from the video. Only works when frame_sampling_method is โ€œuniformโ€. If itโ€™s 1, only the middle frame will be extracted. If itโ€™s 2, only the first and the last frames will be extracted. If itโ€™s larger than 2, in addition to the first and the last frames, other frames will be extracted uniformly within the video duration.

  • tag_field_name โ€“ the field name to store the tags. Itโ€™s โ€œvideo_frame_tagsโ€ in default.

  • args โ€“ extra args

  • kwargs โ€“ extra args

process_single(sample, rank=None, context=False)[source]#

For sample level, sample โ€“> sample

Parameters:

sample โ€“ sample to process

Returns:

processed sample

class data_juicer.ops.mapper.WhitespaceNormalizationMapper(*args, **kwargs)[source]#

Bases: Mapper

Mapper to normalize different kinds of whitespaces to whitespace โ€˜ โ€˜ (0x20) in text samples.

Different kinds of whitespaces can be found here: https://en.wikipedia.org/wiki/Whitespace_character

__init__(*args, **kwargs)[source]#

Initialization method.

Parameters:
  • args โ€“ extra args

  • kwargs โ€“ extra args

process_batched(samples)[source]#