code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _create_tasks_batch(self, tasks_data: List[Dict],
sample_ids: List[Any]) -> List[int]:
"""Mock implementation that returns fake task IDs"""
task_ids = []
for i, (task_data, sample_id_list) in enumerate(zip(tasks_data, sample_ids)):
task_id = i + 1000 #... | Mock implementation that returns fake task IDs | _create_tasks_batch | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def _process_annotation_result(self, annotation: Dict, sample: Dict) -> Dict:
"""Mock implementation that adds annotation to the sample"""
sample_copy = sample.copy()
sample_copy["annotation_result"] = annotation.get("result", {})
return sample_copy | Mock implementation that adds annotation to the sample | _process_annotation_result | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def _check_annotation_status(self, task_ids):
"""Mock implementation for checking annotation status"""
has_changes = False
completed_tasks = {}
for task_id in task_ids:
if task_id in self.mock_annotations and task_id not in self.processed_annotations:
has_cha... | Mock implementation for checking annotation status | _check_annotation_status | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def add_mock_annotation(self, task_id, annotation_data):
"""Helper method to add mock annotations for testing"""
self.mock_annotations[task_id] = {
"id": f"annotation_{task_id}",
"result": annotation_data
} | Helper method to add mock annotations for testing | add_mock_annotation | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_event_handlers_registration(self):
"""Test that event handlers are properly registered"""
mapper = MockAnnotationMapper()
# Check that all event handlers are registered
self.assertIn(ANNOTATION_EVENTS['TASK_CREATED'], mapper.event_handlers)
self.assertIn(ANNOTAT... | Test that event handlers are properly registered | test_event_handlers_registration | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_process_batched_without_waiting(self):
"""Test processing a batch of samples without waiting for annotations"""
mapper = MockAnnotationMapper(wait_for_annotations=False)
# Process the samples
result = mapper.process_batched(self.samples_dict)
# Verify r... | Test processing a batch of samples without waiting for annotations | test_process_batched_without_waiting | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_process_batched_with_waiting(self):
"""Test processing a batch of samples and waiting for annotations"""
mapper = MockAnnotationMapper(wait_for_annotations=True)
# Add mock annotations for all tasks that will be created
for i in range(5):
task_id = 1000 + i ... | Test processing a batch of samples and waiting for annotations | test_process_batched_with_waiting | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_process_batched_with_custom_samples_per_task(self):
"""Test processing with multiple samples per task"""
mapper = MockAnnotationMapper(samples_per_task=2)
# Process the samples
result = mapper.process_batched(self.samples_dict)
# Verify results
... | Test processing with multiple samples per task | test_process_batched_with_custom_samples_per_task | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_wait_for_batch_annotations_timeout(self):
"""Test waiting for annotations with a timeout"""
# Create a mapper with a very short timeout
mapper = MockAnnotationMapper(wait_for_annotations=True, timeout=0.1, poll_interval=0.01)
# Create a task but don't add annotations
... | Test waiting for annotations with a timeout | test_wait_for_batch_annotations_timeout | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_process_uses_existing_ids(self):
"""Test that the mapper uses existing IDs in samples instead of generating new ones"""
# First pass: process without waiting for annotations
mapper = MockAnnotationMapper(wait_for_annotations=False)
# Create samples with predefined IDs
... | Test that the mapper uses existing IDs in samples instead of generating new ones | test_process_uses_existing_ids | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_samples_per_task_enforcement(self):
"""Test that samples_per_task is always 1 for Label Studio"""
# Try to create with samples_per_task=2
mapper = MockLabelStudioAnnotationMapper(samples_per_task=2)
# It should be reset to 1
self.assertEqual(mapper.samples_per_t... | Test that samples_per_task is always 1 for Label Studio | test_samples_per_task_enforcement | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def test_process_batched(self):
"""Test processing a batch of samples with Label Studio mapper"""
mapper = MockLabelStudioAnnotationMapper(wait_for_annotations=True)
# Add mock annotations for all tasks that will be created
for i in range(len(self.samples)):
task_id ... | Test processing a batch of samples with Label Studio mapper | test_process_batched | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_annotation_mapper.py | Apache-2.0 |
def _get_task_annotation(self, task_id: int) -> Optional[Dict]:
"""Get annotation for a task if available with preference processing"""
annotation = self.mock_annotations.get(task_id)
# Process the annotation if available to extract preference
if annotation and 'chosen' in annotation:
... | Get annotation for a task if available with preference processing | _get_task_annotation | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def _process_annotation_result(self, annotation: Dict,
sample: Dict) -> Dict:
"""Process human preference annotation result and update the sample
Args:
annotation: The annotation result from the annotation platform
sample: The original sample t... | Process human preference annotation result and update the sample
Args:
annotation: The annotation result from the annotation platform
sample: The original sample that was annotated
Returns:
Dict: The updated sample with preference results
| _process_annotation_result | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def test_format_task(self):
"""Test task formatting for human preference"""
mapper = MockHumanPreferenceAnnotationMapper()
# Format a task from the first sample
formatted_task = mapper._format_task([self.samples[0]])
# Verify the formatting
self.assertIn('data', formatt... | Test task formatting for human preference | test_format_task | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def test_process_annotation_result_left_preference(self):
"""Test processing annotation result when left option is preferred"""
mapper = MockHumanPreferenceAnnotationMapper()
# Create a sample
sample = self.samples[0].copy()
# Create an annotation with preference for the left o... | Test processing annotation result when left option is preferred | test_process_annotation_result_left_preference | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def test_process_annotation_result_right_preference(self):
"""Test processing annotation result when right option is preferred"""
mapper = MockHumanPreferenceAnnotationMapper()
# Create a sample
sample = self.samples[0].copy()
# Create an annotation with preference for the righ... | Test processing annotation result when right option is preferred | test_process_annotation_result_right_preference | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def test_process_batched(self):
"""Test processing a batch of samples with HumanPreferenceAnnotationMapper"""
mapper = MockHumanPreferenceAnnotationMapper(wait_for_annotations=True)
# Add mock annotations for all tasks that will be created
for i in range(len(self.samples)):
... | Test processing a batch of samples with HumanPreferenceAnnotationMapper | test_process_batched | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def test_custom_keys(self):
"""Test using custom keys for answers and prompt"""
# Create a sample with custom keys
custom_sample = {
"question": "Which explanation is better?",
"response_a": "Explanation A",
"response_b": "Explanation B",
"id": "cu... | Test using custom keys for answers and prompt | test_custom_keys | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def test_process_uses_existing_ids(self):
"""Test that the Human Preference mapper uses existing IDs in samples instead of generating new ones"""
# First pass: process without waiting for annotations
mapper = MockHumanPreferenceAnnotationMapper(
wait_for_annotations=False)
#... | Test that the Human Preference mapper uses existing IDs in samples instead of generating new ones | test_process_uses_existing_ids | python | modelscope/data-juicer | tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | https://github.com/modelscope/data-juicer/blob/master/tests/ops/mapper/annotation/test_human_preference_annotation_mapper.py | Apache-2.0 |
def run_in_subprocess(cmd):
"""Run command in subprocess and capture all output."""
try:
# Create a temporary file for logging
with tempfile.NamedTemporaryFile(mode='w+', suffix='.log') as log_file:
# Redirect both stdout and stderr to the log file
process = subprocess.Po... | Run command in subprocess and capture all output. | run_in_subprocess | python | modelscope/data-juicer | tests/tools/test_process_data.py | https://github.com/modelscope/data-juicer/blob/master/tests/tools/test_process_data.py | Apache-2.0 |
def create_test_pyproject(self, content):
"""Helper function to create a temporary pyproject.toml file."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.toml', delete=False) as f:
f.write(content)
return f.name | Helper function to create a temporary pyproject.toml file. | create_test_pyproject | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def create_test_uv_lock(self, content):
"""Create a temporary uv.lock file with the given content."""
temp_dir = Path(tempfile.mkdtemp())
lock_path = temp_dir / 'uv.lock'
with open(lock_path, 'w') as f:
f.write(content)
return lock_path | Create a temporary uv.lock file with the given content. | create_test_uv_lock | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_get_all_dependencies(self, mock_get_toml_file_path, mock_get_uv_lock_path):
"""Test getting all dependencies from pyproject.toml."""
# Mock get_uv_lock_path to return a non-existent path
mock_get_uv_lock_path.return_value = Path('/nonexistent/path/uv.lock')
mock_get_toml_file_pa... | Test getting all dependencies from pyproject.toml. | test_get_all_dependencies | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_get_dependencies_from_uv_lock(self, mock_get_uv_lock_path):
"""Test getting dependencies from uv.lock."""
mock_get_uv_lock_path.return_value = self.uv_lock_path
deps = LazyLoader.get_all_dependencies()
# Check that we got the exact versions from uv.lock
... | Test getting dependencies from uv.lock. | test_get_dependencies_from_uv_lock | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_uv_lock_not_found_fallback(self, mock_get_uv_lock_path):
"""Test fallback to pyproject.toml when uv.lock is not found."""
# Make get_uv_lock_path raise FileNotFoundError
mock_get_uv_lock_path.side_effect = FileNotFoundError
with patch('data_juicer.utils.lazy_loader.get_... | Test fallback to pyproject.toml when uv.lock is not found. | test_uv_lock_not_found_fallback | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_uv_lock_empty_fallback(self, mock_get_uv_lock_path):
"""Test fallback to pyproject.toml when uv.lock is empty."""
# Create an empty uv.lock
empty_lock = self.create_test_uv_lock("")
mock_get_uv_lock_path.return_value = empty_lock
with patch('data_juicer.utils.la... | Test fallback to pyproject.toml when uv.lock is empty. | test_uv_lock_empty_fallback | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_uv_lock_invalid_json(self, mock_get_uv_lock_path):
"""Test handling of invalid uv.lock JSON."""
# Create an invalid uv.lock
invalid_lock = self.create_test_uv_lock("invalid json content")
mock_get_uv_lock_path.return_value = invalid_lock
with patch('data_juicer.... | Test handling of invalid uv.lock JSON. | test_uv_lock_invalid_json | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_uv_lock_missing_packages_key(self, mock_get_uv_lock_path):
"""Test handling of uv.lock with missing packages key."""
# Create uv.lock without packages key
invalid_lock = self.create_test_uv_lock("")
mock_get_uv_lock_path.return_value = invalid_lock
with patch('d... | Test handling of uv.lock with missing packages key. | test_uv_lock_missing_packages_key | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_get_all_dependencies_not_found(self):
"""Test behavior when pyproject.toml is not found."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path', side_effect=FileNotFoundError), \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path', side_effect=FileNotFoundError):
... | Test behavior when pyproject.toml is not found. | test_get_all_dependencies_not_found | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_get_all_dependencies_parse_error(self):
"""Test behavior when uv.lock is missing and pyproject.toml is invalid."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.toml') as f:
f.write('invalid toml content')
f.flush()
with patch('data_juicer.... | Test behavior when uv.lock is missing and pyproject.toml is invalid. | test_get_all_dependencies_parse_error | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_get_all_dependencies_empty_sections(self):
"""Test behavior when pyproject.toml has empty dependency sections."""
empty_content = """
[project]
dependencies = []
[project.optional-dependencies]
"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.toml') as f:
f.write(emp... | Test behavior when pyproject.toml has empty dependency sections. | test_get_all_dependencies_empty_sections | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_get_all_dependencies_missing_sections(self):
"""Test behavior when pyproject.toml is missing dependency sections."""
minimal_content = """
[project]
name = "data-juicer"
version = "0.1.0"
"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.toml') as f:
f.write(minimal_co... | Test behavior when pyproject.toml is missing dependency sections. | test_get_all_dependencies_missing_sections | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_with_version(self):
"""Test package installation with version from dependencies."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv_lock, \
patch('... | Test package installation with version from dependencies. | test_install_package_with_version | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_with_complex_version(self):
"""Test package installation with complex version constraints."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv_lock, \
... | Test package installation with complex version constraints. | test_install_package_with_complex_version | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_without_version(self):
"""Test package installation for packages without version in dependencies."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv_lock, \
... | Test package installation for packages without version in dependencies. | test_install_package_without_version | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_with_github_url(self):
"""Test package installation with GitHub URL."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv_lock, \
patch('subprocess.c... | Test package installation with GitHub URL. | test_install_package_with_github_url | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_with_cached_dependencies(self):
"""Test that package installation uses cached dependencies."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv_lock, \
... | Test that package installation uses cached dependencies. | test_install_package_with_cached_dependencies | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_with_optional_dependency(self):
"""Test installing a package from optional dependencies."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv_lock, \
... | Test installing a package from optional dependencies. | test_install_package_with_optional_dependency | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_with_version_override(self):
"""Test that package URL overrides version from dependencies."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv_lock, \
... | Test that package URL overrides version from dependencies. | test_install_package_with_version_override | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_with_version_constraint(self):
"""Test package installation when version constraint is found in dependencies."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_get_uv... | Test package installation when version constraint is found in dependencies. | test_install_package_with_version_constraint | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_install_package_without_version_constraint(self):
"""Test package installation when no version constraint is found in dependencies."""
with patch('data_juicer.utils.lazy_loader.get_toml_file_path') as mock_get_path, \
patch('data_juicer.utils.lazy_loader.get_uv_lock_path') as mock_... | Test package installation when no version constraint is found in dependencies. | test_install_package_without_version_constraint | python | modelscope/data-juicer | tests/utils/test_lazy_loader.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_lazy_loader.py | Apache-2.0 |
def test_prepare_fasttext_model_force_download(self):
"""Test FastText model with force download."""
# First remove the model file if it exists
from data_juicer.utils.cache_utils import DATA_JUICER_MODELS_CACHE
from data_juicer.utils.model_utils import prepare_fasttext_model
... | Test FastText model with force download. | test_prepare_fasttext_model_force_download | python | modelscope/data-juicer | tests/utils/test_model_utils.py | https://github.com/modelscope/data-juicer/blob/master/tests/utils/test_model_utils.py | Apache-2.0 |
def split_jsonl(file_path: str, max_size: float, output_dir: str):
"""Split a jsonl file into multiple sub files more efficiently.
Args:
file_path (`str`): path of the original jsonl file
max_size (`float`): max size of each sub file (in MB)
output_dir (`str`): directory to save the sub... | Split a jsonl file into multiple sub files more efficiently.
Args:
file_path (`str`): path of the original jsonl file
max_size (`float`): max size of each sub file (in MB)
output_dir (`str`): directory to save the sub files
Yields:
str: path of each newly created sub file
| split_jsonl | python | modelscope/data-juicer | tools/data_resplit.py | https://github.com/modelscope/data-juicer/blob/master/tools/data_resplit.py | Apache-2.0 |
def get_jsonl_file_names(dataset_dir_path: str) -> List[str]:
"""Load all jsonl files in a directory.
Args:
dataset_dir_path (`str`): path of the directory containing jsonl files
or the path of a single jsonl file
Returns:
List[str]: list of jsonl file paths
"""
if os.path.... | Load all jsonl files in a directory.
Args:
dataset_dir_path (`str`): path of the directory containing jsonl files
or the path of a single jsonl file
Returns:
List[str]: list of jsonl file paths
| get_jsonl_file_names | python | modelscope/data-juicer | tools/data_resplit.py | https://github.com/modelscope/data-juicer/blob/master/tools/data_resplit.py | Apache-2.0 |
def is_local_import(module_name: str) -> bool:
"""Check if a module name is a relative or local import."""
logger.info(f'Checking if {module_name} is a relative or local import')
return (module_name.startswith('data_juicer') or # local imports
module_name.startswith('__')) # special imports | Check if a module name is a relative or local import. | is_local_import | python | modelscope/data-juicer | tools/dj_install.py | https://github.com/modelscope/data-juicer/blob/master/tools/dj_install.py | Apache-2.0 |
def get_imports_from_file(file_path: Path) -> Set[str]:
"""Extract all imports from a Python file."""
imports = set()
try:
with open(file_path, 'r', encoding='utf-8') as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, ast.Import):
... | Extract all imports from a Python file. | get_imports_from_file | python | modelscope/data-juicer | tools/dj_install.py | https://github.com/modelscope/data-juicer/blob/master/tools/dj_install.py | Apache-2.0 |
def find_lazy_loaders(file_path: Path) -> List[Tuple[str, str]]:
"""Find all LazyLoader instances in a file and their package names."""
lazy_loaders = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if ... | Find all LazyLoader instances in a file and their package names. | find_lazy_loaders | python | modelscope/data-juicer | tools/dj_install.py | https://github.com/modelscope/data-juicer/blob/master/tools/dj_install.py | Apache-2.0 |
def get_operator_imports(op_name: str) -> Set[str]:
"""Get all imports needed by an operator."""
# Try to find the operator file in all op subdirectories
op_dirs = [
'filter', 'mapper', 'deduplicator', 'selector', 'aggregrator',
'grouper'
]
op_paths = []
for op_dir in op_dirs:
... | Get all imports needed by an operator. | get_operator_imports | python | modelscope/data-juicer | tools/dj_install.py | https://github.com/modelscope/data-juicer/blob/master/tools/dj_install.py | Apache-2.0 |
def run_command(command, check=True):
"""Run a shell command and return its output"""
logger.info(f"Running: {' '.join(command)}")
result = subprocess.run(command,
check=check,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,... | Run a shell command and return its output | run_command | python | modelscope/data-juicer | tools/generate_smtp_cert.py | https://github.com/modelscope/data-juicer/blob/master/tools/generate_smtp_cert.py | Apache-2.0 |
def generate_certificates(output_dir, common_name, days=365, key_size=2048):
"""Generate client certificate and key for SMTP authentication"""
# Create output directory if it doesn't exist
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
key_file = output_path / 'smtp_c... | Generate client certificate and key for SMTP authentication | generate_certificates | python | modelscope/data-juicer | tools/generate_smtp_cert.py | https://github.com/modelscope/data-juicer/blob/master/tools/generate_smtp_cert.py | Apache-2.0 |
def print_config_example(cert_file, key_file):
"""Print example configuration for using the generated certificates"""
print('\n' + '=' * 80)
print('Certificate Generation Complete!')
print('=' * 80)
print('\nTo use these certificates with Data Juicer, you can:')
print('\n1. Set environment var... | Print example configuration for using the generated certificates | print_config_example | python | modelscope/data-juicer | tools/generate_smtp_cert.py | https://github.com/modelscope/data-juicer/blob/master/tools/generate_smtp_cert.py | Apache-2.0 |
def main():
"""Main entry point for the script"""
parser = argparse.ArgumentParser(
description='Generate SMTP client certificates for secure email '
'authentication')
parser.add_argument('--output',
'-o',
default=os.path.expanduser('~/.data_ju... | Main entry point for the script | main | python | modelscope/data-juicer | tools/generate_smtp_cert.py | https://github.com/modelscope/data-juicer/blob/master/tools/generate_smtp_cert.py | Apache-2.0 |
def read_pyproject_toml():
"""Read and parse pyproject.toml file."""
pyproject_path = Path(__file__).parent.parent / 'pyproject.toml'
if not pyproject_path.exists():
raise FileNotFoundError(
f'pyproject.toml not found at {pyproject_path}')
with open(pyproject_path, 'rb') as f:
... | Read and parse pyproject.toml file. | read_pyproject_toml | python | modelscope/data-juicer | tools/generate_uv_lock.py | https://github.com/modelscope/data-juicer/blob/master/tools/generate_uv_lock.py | Apache-2.0 |
def check_uv_installed():
"""Check if uv is installed and available in PATH."""
try:
subprocess.run(['uv', '--version'], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
raise RuntimeError(
'uv is not installed or not in PATH. Please ins... | Check if uv is installed and available in PATH. | check_uv_installed | python | modelscope/data-juicer | tools/generate_uv_lock.py | https://github.com/modelscope/data-juicer/blob/master/tools/generate_uv_lock.py | Apache-2.0 |
def generate_uv_lock():
"""Generate uv.lock file excluding sandbox dependencies."""
# Check prerequisites
check_uv_installed()
# Read pyproject.toml
pyproject = read_pyproject_toml()
pyproject_path = Path(__file__).parent.parent / 'pyproject.toml'
# Backup original pyproject.toml
backu... | Generate uv.lock file excluding sandbox dependencies. | generate_uv_lock | python | modelscope/data-juicer | tools/generate_uv_lock.py | https://github.com/modelscope/data-juicer/blob/master/tools/generate_uv_lock.py | Apache-2.0 |
def init_sandbox_configs(args=None):
"""
initialize the jsonargparse parser and parse configs from one of:
1. POSIX-style commands line args;
2. config files in yaml (json and jsonnet supersets);
3. environment variables
4. hard-coded defaults
:param args: list of params, e.... |
initialize the jsonargparse parser and parse configs from one of:
1. POSIX-style commands line args;
2. config files in yaml (json and jsonnet supersets);
3. environment variables
4. hard-coded defaults
:param args: list of params, e.g., ['--conifg', 'cfg.yaml'], default None.
... | init_sandbox_configs | python | modelscope/data-juicer | tools/sandbox_starter.py | https://github.com/modelscope/data-juicer/blob/master/tools/sandbox_starter.py | Apache-2.0 |
def specify_jobs_configs(cfg):
"""
Specify job configs by their dict objects or config file path strings.
:param cfg: the original config
:return: a dict of different configs.
"""
def configs_to_job_list(cfgs):
job_cfgs = []
if cfgs:
job_cfgs = [specify_job_configs(... |
Specify job configs by their dict objects or config file path strings.
:param cfg: the original config
:return: a dict of different configs.
| specify_jobs_configs | python | modelscope/data-juicer | tools/sandbox_starter.py | https://github.com/modelscope/data-juicer/blob/master/tools/sandbox_starter.py | Apache-2.0 |
def recursive_print(name, val, spaces=0):
"""
Recursively print the structure of a checkpoint. This function is taken
from `convert_megatron_gpt2_checkpoint.py`
Args:
name (str): the name of the current tensor parameter
val (Tuple(int)): the shape of the current tensor parameter
... |
Recursively print the structure of a checkpoint. This function is taken
from `convert_megatron_gpt2_checkpoint.py`
Args:
name (str): the name of the current tensor parameter
val (Tuple(int)): the shape of the current tensor parameter
spaces (int): the number of spaces to print befo... | recursive_print | python | modelscope/data-juicer | tools/converter/convert_gpt_to_transformers.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/convert_gpt_to_transformers.py | Apache-2.0 |
def megatron_to_transformers_fix_query_key_value_ordering(
param, checkpoint_version, num_splits, num_heads, hidden_size):
"""
Permutes layout of param tensor to
[num_splits * num_heads * hidden_size, :] for compatibility with later
versions of NVIDIA Megatron-LM. The inverse operation is perfor... |
Permutes layout of param tensor to
[num_splits * num_heads * hidden_size, :] for compatibility with later
versions of NVIDIA Megatron-LM. The inverse operation is performed inside
Megatron-LM to read checkpoints:
https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209
If ... | megatron_to_transformers_fix_query_key_value_ordering | python | modelscope/data-juicer | tools/converter/convert_gpt_to_transformers.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/convert_gpt_to_transformers.py | Apache-2.0 |
def transformers_to_megatron_fix_query_key_value_ordering(
param, checkpoint_version, num_splits, num_heads, hidden_size):
"""
Permutes layout of param tensor to the one compatible with respective
NVIDIA Megatron-LM checkpoint versions. Input is
[num_splits * num_heads * hidden_size, :] and outp... |
Permutes layout of param tensor to the one compatible with respective
NVIDIA Megatron-LM checkpoint versions. Input is
[num_splits * num_heads * hidden_size, :] and output is
[num_heads * hidden_size * num_splits, :] for version 1.0 and
[num_heads * num_splits * hidden_size, :] for version 2.0 and ... | transformers_to_megatron_fix_query_key_value_ordering | python | modelscope/data-juicer | tools/converter/convert_gpt_to_transformers.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/convert_gpt_to_transformers.py | Apache-2.0 |
def merge_transformers_sharded_states(path, num_checkpoints):
"""
Merge sharded checkpoints from transformers into a single checkpoint.
Args:
path (str): the path to the sharded checkpoints
num_checkpoints (int): the number of checkpoints to merge
"""
state_dict = {}
for i in ra... |
Merge sharded checkpoints from transformers into a single checkpoint.
Args:
path (str): the path to the sharded checkpoints
num_checkpoints (int): the number of checkpoints to merge
| merge_transformers_sharded_states | python | modelscope/data-juicer | tools/converter/convert_gpt_to_transformers.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/convert_gpt_to_transformers.py | Apache-2.0 |
def get_megatron_sharded_states(args, tp_size, pp_size, pp_rank):
"""
Get sharded checkpoints from NVIDIA Megatron-LM checkpoint based on the
provided tensor parallel size, pipeline parallel size and pipeline parallel
rank.
Args:
args (argparse.Namespace): the arguments to the script
... |
Get sharded checkpoints from NVIDIA Megatron-LM checkpoint based on the
provided tensor parallel size, pipeline parallel size and pipeline parallel
rank.
Args:
args (argparse.Namespace): the arguments to the script
tp_size (int): the tensor parallel size
pp_size (int): the pipe... | get_megatron_sharded_states | python | modelscope/data-juicer | tools/converter/convert_gpt_to_transformers.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/convert_gpt_to_transformers.py | Apache-2.0 |
def convert_checkpoint_from_megatron_to_transformers(args):
"""
Convert NVIDIA Megatron-LM checkpoint to HuggingFace Transformers
checkpoint. This handles Megatron checkpoints with different tensor
parallelism and pipeline parallelism sizes. It saves the converted
checkpoint into shards using Huggin... |
Convert NVIDIA Megatron-LM checkpoint to HuggingFace Transformers
checkpoint. This handles Megatron checkpoints with different tensor
parallelism and pipeline parallelism sizes. It saves the converted
checkpoint into shards using HuggingFace Transformers checkpoint sharding
functionality. This grea... | convert_checkpoint_from_megatron_to_transformers | python | modelscope/data-juicer | tools/converter/convert_gpt_to_transformers.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/convert_gpt_to_transformers.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
lab... |
Args:
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `... | forward | python | modelscope/data-juicer | tools/converter/modeling_megatron_llama.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/modeling_megatron_llama.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
lab... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`confi... | forward | python | modelscope/data-juicer | tools/converter/modeling_megatron_llama.py | https://github.com/modelscope/data-juicer/blob/master/tools/converter/modeling_megatron_llama.py | Apache-2.0 |
def generate_edges(nodes: List[int]) -> List[Tuple[int, int]]:
"""
Generate edges from a cluster. Instead of generating N^2 edges,
we only need all nodes align to a single node,
since we will be running connected components on the edges later.
Parameters
----------
nodes : List[int]
... |
Generate edges from a cluster. Instead of generating N^2 edges,
we only need all nodes align to a single node,
since we will be running connected components on the edges later.
Parameters
----------
nodes : List[int]
The list of nodes in the cluster.
Returns
-------
List[T... | generate_edges | python | modelscope/data-juicer | tools/distributed_deduplication/dedup_utils.py | https://github.com/modelscope/data-juicer/blob/master/tools/distributed_deduplication/dedup_utils.py | Apache-2.0 |
def find_components(edges):
"""
Star-Graph-Connected-Components (SGCC) algorithm
"""
a = edges
while True:
b = a.flatMap(large_star_map).groupByKey().flatMap(
large_star_reduce).distinct().cache()
a = b.map(small_star_map).groupByKey().flatMap(
small_star_red... |
Star-Graph-Connected-Components (SGCC) algorithm
| find_components | python | modelscope/data-juicer | tools/distributed_deduplication/dedup_utils.py | https://github.com/modelscope/data-juicer/blob/master/tools/distributed_deduplication/dedup_utils.py | Apache-2.0 |
def dedup_dataset(dataset_path: str,
result_path: str,
tokenizer: Optional[str] = None,
num_features: int = 1047576,
num_hashtables: int = 10,
text_key: str = 'text',
master_url: Optional[str] = None):
"""
... |
Perform fuzzy text deduplication on the given dataset.
:param dataset_path: the path to the dataset to perform deduplication,
The suffix of the path should be one of the json, jsonl, parquet.
:param result_path: the path to store the predicted result dataset.
:param tokenizer: what tokenizer to... | dedup_dataset | python | modelscope/data-juicer | tools/distributed_deduplication/spark_dedup.py | https://github.com/modelscope/data-juicer/blob/master/tools/distributed_deduplication/spark_dedup.py | Apache-2.0 |
def convert_absolute_path_to_relative_path(
dj_ds_path: str,
absolute_dirs: list[str],
path_keys: list[str],
target_dj_ds_path: str = None,
target_mt_dir: str = None,
):
"""
Convert the absolute paths or relative paths in Data-Juicer dataset.
:param dj_ds_path: path to the input Data-Ju... |
Convert the absolute paths or relative paths in Data-Juicer dataset.
:param dj_ds_path: path to the input Data-Juicer dataset with absolute
paths to multimodal data.
:param absolute_dirs: all possible absolute dirs in the absolute paths.
A list param to support multi sources of multimodal ... | convert_absolute_path_to_relative_path | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/absolute_path_to_relative_path.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/absolute_path_to_relative_path.py | Apache-2.0 |
def main(
dj_ds_path: str,
target_internvid_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
sent_separator: str = ' ',
):
"""
Convert a Data-Juicer-format dataset to a InternVid-like dataset.
:param dj_ds_path: path to the input ... |
Convert a Data-Juicer-format dataset to a InternVid-like dataset.
:param dj_ds_path: path to the input dataset in Data-Juicer format.
:param target_internvid_ds_path: path to store the converted dataset in
InternVid format.
:param eoc_special_token: the special token for "end of a chunk". It's... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_internvid.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_internvid.py | Apache-2.0 |
def main(
dj_ds_path: str,
target_llava_ds_path: str,
keep_only_first_image: bool = True,
eoc_special_token: str = SpecialTokens.eoc,
image_special_token: str = '<image>',
sent_separator: str = '\n',
restore_questions: bool = False,
original_llava_ds_path: str = None,
):
"""
Conv... |
Convert a Data-Juicer-format dataset to a LLaVA-like dataset.
:param dj_ds_path: path to the input dataset in Data-Juicer format.
:param target_llava_ds_path: path to store the converted dataset in LLaVA
format.
:param keep_only_first_image: whether to only keep the image token in the
... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_llava.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_llava.py | Apache-2.0 |
def main(
dj_ds_path: str,
target_mmc4_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
image_special_token: str = SpecialTokens.image,
sent_separator: str = ' ',
keep_dj_fields: bool = False,
):
"""
Convert a Data-Juicer-format dataset to an MMC4-like format. Notice: if
the... |
Convert a Data-Juicer-format dataset to an MMC4-like format. Notice: if
the similarity matrix is included in the dataset, it might not be able to
be restored to the original correlation and could be with wrong shape due
to some images or text sentences might be removed. So this tool will do
nothing... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_mmc4.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_mmc4.py | Apache-2.0 |
def main(
dj_ds_path: str,
target_msr_vtt_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
sent_separator: str = ' ',
):
"""
Convert a Data-Juicer-format dataset to a MSR-VTT-like dataset.
:param dj_ds_path: path to the input data... |
Convert a Data-Juicer-format dataset to a MSR-VTT-like dataset.
:param dj_ds_path: path to the input dataset in Data-Juicer format.
:param target_msr_vtt_ds_path: path to store the converted dataset in
MSR-VTT format.
:param eoc_special_token: the special token for "end of a chunk". It's used
... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_msrvtt.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_msrvtt.py | Apache-2.0 |
def main(
dj_ds_path: str,
target_video_chatgpt_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
sent_separator: str = ' ',
):
"""
Convert a Data-Juicer-format dataset to a Video-ChatGPT-like dataset.
:param dj_ds_path: path to th... |
Convert a Data-Juicer-format dataset to a Video-ChatGPT-like dataset.
:param dj_ds_path: path to the input dataset in Data-Juicer format.
:param target_video_chatgpt_ds_path: path to store the converted dataset in
Video-ChatGPT format.
:param eoc_special_token: the special token for "end of a ... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_video_chatgpt.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_video_chatgpt.py | Apache-2.0 |
def main(
dj_ds_path: str,
target_wavcaps_ds_path: str,
target_field: str = 'caption',
eoc_special_token: str = SpecialTokens.eoc,
audio_special_token: str = SpecialTokens.audio,
remove_eoc_at_last: bool = True,
remove_target_field_token: bool = False,
sent_separator: str = '\n',
):
... |
Convert a Data-Juicer-format dataset to a WavCaps-like dataset.
:param dj_ds_path: path to the input dataset in Data-Juicer format.
:param target_wavcaps_ds_path: path to store the converted dataset in
WavCaps format.
:param target_field: the field used to describe audio in the WavCaps-like
... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_wavcaps.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_wavcaps.py | Apache-2.0 |
def main(
dj_ds_path: str,
target_youku_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
sent_separator: str = ' ',
subset_type: str = 'classification',
):
"""
Convert a Data-Juicer-format dataset to a Youku-mPLUG-like dataset.
... |
Convert a Data-Juicer-format dataset to a Youku-mPLUG-like dataset.
:param dj_ds_path: path to the input dataset in Data-Juicer format.
:param target_youku_ds_path: path to store the converted dataset in
Youku-mPLUG format.
:param eoc_special_token: the special token for "end of a chunk". It's... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_youku.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/data_juicer_format_to_target_format/dj_to_youku.py | Apache-2.0 |
def main(
internvid_ds_path: str,
target_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
add_eoc_at_last: bool = True,
sent_separator: str = ' ',
video_special_token_insert_pos: str = 'before',
cut_videos: bool = True,
cut_vid... |
Convert an InternVid-like dataset to the Data-Juicer format.
:param internvid_ds_path: path to the input InternVid-like dataset.
:param target_ds_path: path to store the converted dataset in Data-Juicer
format.
:param eoc_special_token: the special token for "end of a chunk". It's used
... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/internvid_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/internvid_to_dj.py | Apache-2.0 |
def main(
mmc4_ds_path: str,
target_ds_path: str,
image_dir: str = None,
eoc_special_token: str = SpecialTokens.eoc,
image_special_token: str = SpecialTokens.image,
image_special_token_insert_pos: str = 'before',
add_eoc_at_last: bool = True,
sent_separator: str = ' ',
keep_other_fie... |
Convert a MMC4-like dataset to the Data-Juicer format.
:param mmc4_ds_path: path to the input MMC4-like dataset.
:param target_ds_path: path to store the converted dataset in Data-Juicer
format.
:param image_dir: directory to store images. If it's None, it means the
"image_name" for ea... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/mmc4_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/mmc4_to_dj.py | Apache-2.0 |
def main(
msr_vtt_ds_path: str,
target_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
add_eoc_at_last: bool = True,
sent_separator: str = ' ',
video_special_token_insert_pos: str = 'before',
keep_other_fields: bool = True,
):
... |
Convert an MSR-VTT-like dataset to the Data-Juicer format.
:param msr_vtt_ds_path: path to the input MSR-VTT-like dataset.
:param target_ds_path: path to store the converted dataset in Data-Juicer
format.
:param eoc_special_token: the special token for "end of a chunk". It's used
to sp... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/msrvtt_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/msrvtt_to_dj.py | Apache-2.0 |
def main(
video_chatgpt_ds_path: str,
target_ds_dj_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
add_eoc_at_last: bool = True,
sent_separator: str = ' ',
video_special_token_insert_pos: str = 'before',
keep_other_fields: bool = Tru... |
Convert a Video_Chatgpt-like dataset to the Data-Juicer format.
:param video_chatgpt_ds_path: path to the input Video_Chatgpt-like dataset.
:param target_ds_dj_path: path to store the converted dataset in
Data-Juicer format.
:param eoc_special_token: the special token for "end of a chunk". It'... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/video_chatgpt_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/video_chatgpt_to_dj.py | Apache-2.0 |
def main(
wavcaps_json_path: str,
wavcaps_audio_path: str,
target_ds_path: str,
str_id: bool = True,
target_field: str = 'caption',
eoc_special_token: str = SpecialTokens.eoc,
audio_special_token: str = SpecialTokens.audio,
add_eoc_at_last: bool = True,
add_target_field_token: bool =... |
Convert a WavCaps-like dataset to the Data-Juicer format.
:param wavcaps_json_path: path to the json files of WavCaps-like dataset.
:param wavcaps_audio_path: path to the audio files of WavCaps-like dataset.
:param target_ds_path: path to store the converted dataset in Data-Juicer
format.
... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/wavcaps_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/wavcaps_to_dj.py | Apache-2.0 |
def main(
youku_ds_path: str,
target_ds_path: str,
eoc_special_token: str = SpecialTokens.eoc,
video_special_token: str = SpecialTokens.video,
add_eoc_at_last: bool = True,
sent_separator: str = ' ',
video_special_token_insert_pos: str = 'before',
subset_type: str = 'classification',
... |
Convert a Youku-mPLUG-like dataset to the Data-Juicer format.
:param youku_ds_path: path to the input Youku-mPLUG-like dataset.
:param target_ds_path: path to store the converted dataset in Data-Juicer
format.
:param eoc_special_token: the special token for "end of a chunk". It's used
... | main | python | modelscope/data-juicer | tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/youku_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/multimodal/source_format_to_data_juicer_format/youku_to_dj.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
input_key: str = 'input',
output_key: str = 'output',
):
"""
Convert a Data-Juicer dataset to the Alpaca-like format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
... |
Convert a Data-Juicer dataset to the Alpaca-like format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param input_key: the field key to store the query sentence from human.
:param output_key: the field key to store the res... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_alpaca.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_alpaca.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
conversations_key: str = 'conversations',
from_key: str = 'from',
value_key: str = 'value',
human_role: str = 'user',
assistant_role: str = 'assistant',
system_role: str = 'system',
instruction_role: str = 'instruction',
):
"""
Co... |
Convert a Data-Juicer dataset to the LLaMA-Factory ShareGPT-like format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param conversations_key: the field key to store conversions.
:param from_key: the field key to store the... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_llama_factory_sharegpt.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_llama_factory_sharegpt.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
messages_key: str = 'messages',
role_key: str = 'role',
content_key: str = 'content',
human_role: str = 'user',
assistant_role: str = 'assistant',
system_role: str = 'system',
instruction_role: str = 'instruction',
):
"""
Convert ... |
Convert a Data-Juicer query-response dataset to the ModelScope-Swift
Message format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param messages_key: the field key to store messages.
:param role_key: the field key to s... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_messages.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_messages.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
conversation_key: str = 'conversation',
human_key: str = 'human',
assistant_key: str = 'assistant',
system_key: str = 'system',
instruction_key: str = 'instruction',
):
"""
Convert a Data-Juicer query-response dataset to the ModelScope-Sw... |
Convert a Data-Juicer query-response dataset to the ModelScope-Swift
ShareGPT-like format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param conversation_key: the field key to store conversions.
:param human_key: the ... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_ms_swift_sharegpt.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/data_juicer_format_to_target_format/dj_to_ms_swift_sharegpt.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
input_key: str = 'input',
output_key: str = 'output',
multimodal_keys: Union[str, List[str]] = None,
):
"""
Convert an Alpaca-like dataset to the Data-Juicer query-response format.
:param src_ds_path: the path to the source dataset.
:par... |
Convert an Alpaca-like dataset to the Data-Juicer query-response format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param input_key: the field key to store the query sentence from human.
:param output_key: the field key ... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/alpaca_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/alpaca_to_dj.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
conversations_key: str = 'conversations',
from_key: str = 'from',
value_key: str = 'value',
system_role: str = 'system',
instruction_role: str = 'instruction',
multimodal_keys: Union[str, List[str]] = None,
):
"""
Convert a LLaMA-Fact... |
Convert a LLaMA-Factory ShareGPT-like dataset to the Data-Juicer
query-response format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param conversations_key: the field key to store conversions.
:param from_key: the fie... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/llama_factory_sharegpt_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/llama_factory_sharegpt_to_dj.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
messages_key: str = 'messages',
role_key: str = 'role',
content_key: str = 'content',
system_role: str = 'system',
instruction_role: str = 'instruction',
multimodal_keys: Union[str, List[str]] = None,
):
"""
Convert a Messages-like da... |
Convert a Messages-like dataset to the Data-Juicer query-response format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param messages_key: the field key to store messages.
:param role_key: the field key to store the senten... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/messages_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/messages_to_dj.py | Apache-2.0 |
def main(
src_ds_path: str,
tgt_ds_path: str,
conversation_key: str = 'conversation',
human_key: str = 'human',
assistant_key: str = 'assistant',
system_key: str = 'system',
instruction_key: str = 'instruction',
multimodal_keys: Union[str, List[str]] = None,
):
"""
Convert a Mode... |
Convert a ModelScope-Swift ShareGPT-like dataset to the Data-Juicer
query-response format.
:param src_ds_path: the path to the source dataset.
:param tgt_ds_path: the path to store the converted target dataset.
:param conversation_key: the field key to store conversions.
:param human_key: the ... | main | python | modelscope/data-juicer | tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/ms_swift_sharegpt_to_dj.py | https://github.com/modelscope/data-juicer/blob/master/tools/fmt_conversion/post_tuning_dialog/source_format_to_data_juicer_format/ms_swift_sharegpt_to_dj.py | Apache-2.0 |
def obj_quality_score(dj_cfg):
"""
HPO loop: cfg --> data --> data score --> cfg --> data --> ...
:param dj_cfg: specified data recipe (as a search point)
:return: a data score, after
1. processing data according to the dj_cfg;
2. applying a quality classifier
"""
if dj_cf... |
HPO loop: cfg --> data --> data score --> cfg --> data --> ...
:param dj_cfg: specified data recipe (as a search point)
:return: a data score, after
1. processing data according to the dj_cfg;
2. applying a quality classifier
| obj_quality_score | python | modelscope/data-juicer | tools/hpo/objects.py | https://github.com/modelscope/data-juicer/blob/master/tools/hpo/objects.py | Apache-2.0 |
def setup_logging(data_dir):
"""Setup logging to both file and console"""
# Create logs directory
logs_dir = os.path.join(os.path.abspath(data_dir), 'logs')
os.makedirs(logs_dir, exist_ok=True)
# Create log file path
log_file = os.path.join(logs_dir, 'label_studio_service.log')
# Create lo... | Setup logging to both file and console | setup_logging | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
def check_docker_installed():
"""Check if Docker is installed and running"""
try:
result = subprocess.run(['docker', 'info'],
capture_output=True,
text=True,
check=False)
if result.returncode == 0:
... | Check if Docker is installed and running | check_docker_installed | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
def pull_docker_image(image):
"""Pull the Label Studio Docker image"""
logger.info(f'Pulling Docker image: {image}...')
result = subprocess.run(['docker', 'pull', image], check=False)
return result.returncode == 0 | Pull the Label Studio Docker image | pull_docker_image | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
def check_container_exists(container_name):
"""Check if a container with the given name exists"""
try:
result = subprocess.run([
'docker', 'ps', '-a', '--filter', f'name={container_name}',
'--format', '{{.Names}}'
],
capture_output=True,
... | Check if a container with the given name exists | check_container_exists | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
def check_container_running(container_name):
"""Check if a container is currently running"""
try:
result = subprocess.run([
'docker', 'ps', '--filter', f'name={container_name}', '--format',
'{{.Names}}'
],
capture_output=True,
... | Check if a container is currently running | check_container_running | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
def stop_container(container_name, remove_volumes=False):
"""Stop and remove the Label Studio container"""
if check_container_exists(container_name):
logger.info(f'Stopping container: {container_name}...')
subprocess.run(['docker', 'stop', container_name], check=False)
logger.info(f'Remo... | Stop and remove the Label Studio container | stop_container | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
def kill_container(container_name):
"""Force kill the Label Studio container"""
if check_container_running(container_name):
logger.info(f'Force killing container: {container_name}...')
subprocess.run(['docker', 'kill', container_name], check=False)
logger.info(f'Removing container: {cont... | Force kill the Label Studio container | kill_container | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
def get_container_error_message(container_name):
"""Get detailed error information from a container that has exited"""
inspect_cmd = ['docker', 'inspect', container_name]
inspect_result = subprocess.run(inspect_cmd,
capture_output=True,
... | Get detailed error information from a container that has exited | get_container_error_message | python | modelscope/data-juicer | tools/humanops/label_studio_service.py | https://github.com/modelscope/data-juicer/blob/master/tools/humanops/label_studio_service.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.