task_id
stringlengths
15
15
repo
stringlengths
11
23
file_path
stringlengths
16
49
function_name
stringlengths
4
33
qualified_name
stringlengths
4
37
function_type
stringclasses
2 values
class_name
stringclasses
8 values
prompt
stringlengths
198
10.1k
signature
stringlengths
11
792
docstring
stringlengths
0
549
canonical_solution
stringlengths
106
2.37k
full_function
stringlengths
129
2.67k
tests
stringlengths
563
4.68M
setup
stringlengths
201
225
metadata
stringlengths
74
78
validation
stringlengths
36
72
original_task_id
stringlengths
15
15
full_context
stringlengths
422
16.4k
repo_patch/0001
Comfy-Org/ComfyUI
comfy_execution/jobs.py
normalize_output_item
normalize_output_item
function
null
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
def normalize_output_item(item): """Normalize a single output list item for the jobs API. Returns the normalized item, or None to exclude it. String items with 3D extensions become {filename, type, subfolder} dicts. """
Normalize a single output list item for the jobs API. Returns the normalized item, or None to exclude it. String items with 3D extensions become {filename, type, subfolder} dicts.
if item is None: return None if isinstance(item, str): if has_3d_extension(item): return {'filename': item, 'type': 'output', 'subfolder': '', 'mediaType': '3d'} return None if isinstance(item, dict): return item return None
def normalize_output_item(item): """Normalize a single output list item for the jobs API. Returns the normalized item, or None to exclude it. String items with 3D extensions become {filename, type, subfolder} dicts. """ if item is None: return None if isinstance(item, str): if h...
[{"test_file": "tests/execution/test_jobs.py", "test_function": "TestNormalizeOutputItem.test_none_returns_none", "test_content": "\"\"\"Unit tests for comfy_execution/jobs.py\"\"\"\n\nfrom comfy_execution.jobs import (\n JobStatus,\n is_previewable,\n normalize_queue_item,\n normalize_history_item,\n no...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 9, "file_lines": 390, "has_docstring": true, "num_tests": 6}
{"status": "passed", "tests_run": 6}
repo_patch/0001
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
repo_patch/0002
Comfy-Org/ComfyUI
comfy_execution/jobs.py
normalize_queue_item
normalize_queue_item
function
null
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
def normalize_queue_item(item: tuple, status: str) -> dict: """Convert queue item tuple to unified job dict. Expects item with sensitive data already removed (5 elements). """
Convert queue item tuple to unified job dict. Expects item with sensitive data already removed (5 elements).
priority, prompt_id, _, extra_data, _ = item create_time, workflow_id = _extract_job_metadata(extra_data) return prune_dict({ 'id': prompt_id, 'status': status, 'priority': priority, 'create_time': create_time, 'outputs_count': 0, 'workflow_id': workflow_id, ...
def normalize_queue_item(item: tuple, status: str) -> dict: """Convert queue item tuple to unified job dict. Expects item with sensitive data already removed (5 elements). """ priority, prompt_id, _, extra_data, _ = item create_time, workflow_id = _extract_job_metadata(extra_data) return prune...
[{"test_file": "tests/execution/test_jobs.py", "test_function": "TestNormalizeQueueItem.test_basic_normalization", "test_content": "\"\"\"Unit tests for comfy_execution/jobs.py\"\"\"\n\nfrom comfy_execution.jobs import (\n JobStatus,\n is_previewable,\n normalize_queue_item,\n normalize_history_item,\n n...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 10, "file_lines": 390, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0002
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
repo_patch/0003
Comfy-Org/ComfyUI
comfy_api/feature_flags.py
get_connection_feature
get_connection_feature
function
null
""" Feature flags module for ComfyUI WebSocket protocol negotiation. This module handles capability negotiation between frontend and backend, allowing graceful protocol evolution while maintaining backward compatibility. """ from typing import Any from comfy.cli_args import args # Default server capabilities SERVER...
def get_connection_feature( sockets_metadata: dict[str, dict[str, Any]], sid: str, feature_name: str, default: Any = False ) -> Any: """ Get a feature flag value for a specific connection. Args: sockets_metadata: Dictionary of socket metadata sid: Session ID of the connectio...
Get a feature flag value for a specific connection. Args: sockets_metadata: Dictionary of socket metadata sid: Session ID of the connection feature_name: Name of the feature to check default: Default value if feature not found Returns: Feature value or default if not found
if sid not in sockets_metadata: return default return sockets_metadata[sid].get("feature_flags", {}).get(feature_name, default)
def get_connection_feature( sockets_metadata: dict[str, dict[str, Any]], sid: str, feature_name: str, default: Any = False ) -> Any: """ Get a feature flag value for a specific connection. Args: sockets_metadata: Dictionary of socket metadata sid: Session ID of the connectio...
[{"test_file": "tests-unit/feature_flags_test.py", "test_function": "TestFeatureFlags.test_get_connection_feature_with_missing_sid", "test_content": "\"\"\"Tests for feature flags functionality.\"\"\"\n\nfrom comfy_api.feature_flags import (\n get_connection_feature,\n supports_feature,\n get_server_features,\...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 3, "file_lines": 72, "has_docstring": true, "num_tests": 5}
{"status": "passed", "tests_run": 5}
repo_patch/0003
""" Feature flags module for ComfyUI WebSocket protocol negotiation. This module handles capability negotiation between frontend and backend, allowing graceful protocol evolution while maintaining backward compatibility. """ from typing import Any from comfy.cli_args import args # Default server capabilities SERVER...
repo_patch/0004
Comfy-Org/ComfyUI
comfy_execution/jobs.py
apply_sorting
apply_sorting
function
null
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
def apply_sorting(jobs: list[dict], sort_by: str, sort_order: str) -> list[dict]: """Sort jobs list by specified field and order."""
Sort jobs list by specified field and order.
reverse = (sort_order == 'desc') if sort_by == 'execution_duration': def get_sort_key(job): start = job.get('execution_start_time', 0) end = job.get('execution_end_time', 0) return end - start if end and start else 0 else: def get_sort_key(job): ...
def apply_sorting(jobs: list[dict], sort_by: str, sort_order: str) -> list[dict]: """Sort jobs list by specified field and order.""" reverse = (sort_order == 'desc') if sort_by == 'execution_duration': def get_sort_key(job): start = job.get('execution_start_time', 0) end = j...
[{"test_file": "tests/execution/test_jobs.py", "test_function": "TestApplySorting.test_sort_by_create_time_desc", "test_content": "\"\"\"Unit tests for comfy_execution/jobs.py\"\"\"\n\nfrom comfy_execution.jobs import (\n JobStatus,\n is_previewable,\n normalize_queue_item,\n normalize_history_item,\n no...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 10, "file_lines": 390, "has_docstring": true, "num_tests": 4}
{"status": "passed", "tests_run": 4}
repo_patch/0004
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
repo_patch/0005
Comfy-Org/ComfyUI
comfy_execution/jobs.py
get_outputs_summary
get_outputs_summary
function
null
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
def get_outputs_summary(outputs: dict) -> tuple[int, Optional[dict]]: """ Count outputs and find preview in a single pass. Returns (outputs_count, preview_output). Preview priority (matching frontend): 1. type="output" with previewable media 2. Any previewable media """
Count outputs and find preview in a single pass. Returns (outputs_count, preview_output). Preview priority (matching frontend): 1. type="output" with previewable media 2. Any previewable media
count = 0 preview_output = None fallback_preview = None for node_id, node_outputs in outputs.items(): if not isinstance(node_outputs, dict): continue for media_type, items in node_outputs.items(): # 'animated' is a boolean flag, not actual output items ...
def get_outputs_summary(outputs: dict) -> tuple[int, Optional[dict]]: """ Count outputs and find preview in a single pass. Returns (outputs_count, preview_output). Preview priority (matching frontend): 1. type="output" with previewable media 2. Any previewable media """ count = 0 pr...
[{"test_file": "tests/execution/test_jobs.py", "test_function": "TestGetOutputsSummary.test_empty_outputs", "test_content": "\"\"\"Unit tests for comfy_execution/jobs.py\"\"\"\n\nfrom comfy_execution.jobs import (\n JobStatus,\n is_previewable,\n normalize_queue_item,\n normalize_history_item,\n normaliz...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 49, "file_lines": 390, "has_docstring": true, "num_tests": 13}
{"status": "passed", "tests_run": 13}
repo_patch/0005
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
repo_patch/0006
Comfy-Org/ComfyUI
comfy_execution/jobs.py
normalize_outputs
normalize_outputs
function
null
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
def normalize_outputs(outputs: dict) -> dict: """Normalize raw node outputs for the jobs API. Transforms string 3D filenames into file output dicts and removes None items. All other items (non-3D strings, dicts, etc.) are preserved as-is. """
Normalize raw node outputs for the jobs API. Transforms string 3D filenames into file output dicts and removes None items. All other items (non-3D strings, dicts, etc.) are preserved as-is.
normalized = {} for node_id, node_outputs in outputs.items(): if not isinstance(node_outputs, dict): normalized[node_id] = node_outputs continue normalized_node = {} for media_type, items in node_outputs.items(): if media_type == 'animated' or not isin...
def normalize_outputs(outputs: dict) -> dict: """Normalize raw node outputs for the jobs API. Transforms string 3D filenames into file output dicts and removes None items. All other items (non-3D strings, dicts, etc.) are preserved as-is. """ normalized = {} for node_id, node_outputs in out...
[{"test_file": "tests/execution/test_jobs.py", "test_function": "TestNormalizeOutputs.test_empty_outputs", "test_content": "\"\"\"Unit tests for comfy_execution/jobs.py\"\"\"\n\nfrom comfy_execution.jobs import (\n JobStatus,\n is_previewable,\n normalize_queue_item,\n normalize_history_item,\n normalize...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 19, "file_lines": 390, "has_docstring": true, "num_tests": 6}
{"status": "passed", "tests_run": 6}
repo_patch/0006
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
repo_patch/0007
Comfy-Org/ComfyUI
comfy_execution/jobs.py
is_previewable
is_previewable
function
null
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
def is_previewable(media_type: str, item: dict) -> bool: """ Check if an output item is previewable. Matches frontend logic in ComfyUI_frontend/src/stores/queueStore.ts Maintains backwards compatibility with existing logic. Priority: 1. media_type is 'images', 'video', 'audio', or '3d' 2. f...
Check if an output item is previewable. Matches frontend logic in ComfyUI_frontend/src/stores/queueStore.ts Maintains backwards compatibility with existing logic. Priority: 1. media_type is 'images', 'video', 'audio', or '3d' 2. format field starts with 'video/' or 'audio/' 3. filename has a 3D extension (.obj, .fbx, ...
if media_type in PREVIEWABLE_MEDIA_TYPES: return True # Check format field (MIME type). # Maintains backwards compatibility with how custom node outputs are handled in the frontend. fmt = item.get('format', '') if fmt and (fmt.startswith('video/') or fmt.startswith('audio/')): retur...
def is_previewable(media_type: str, item: dict) -> bool: """ Check if an output item is previewable. Matches frontend logic in ComfyUI_frontend/src/stores/queueStore.ts Maintains backwards compatibility with existing logic. Priority: 1. media_type is 'images', 'video', 'audio', or '3d' 2. f...
[{"test_file": "tests/execution/test_jobs.py", "test_function": "TestIsPreviewable.test_previewable_media_types", "test_content": "\"\"\"Unit tests for comfy_execution/jobs.py\"\"\"\n\nfrom comfy_execution.jobs import (\n JobStatus,\n is_previewable,\n normalize_queue_item,\n normalize_history_item,\n no...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 12, "file_lines": 390, "has_docstring": true, "num_tests": 7}
{"status": "passed", "tests_run": 7}
repo_patch/0007
""" Job utilities for the /api/jobs endpoint. Provides normalization and helper functions for job status tracking. """ from typing import Optional from comfy_api.internal import prune_dict class JobStatus: """Job status constants.""" PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED = 'compl...
repo_patch/0008
Comfy-Org/ComfyUI
middleware/cache_middleware.py
cache_control
cache_control
function
null
"""Cache control middleware for ComfyUI server""" from aiohttp import web from typing import Callable, Awaitable # Time in seconds ONE_HOUR: int = 3600 ONE_DAY: int = 86400 IMG_EXTENSIONS = ( ".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp", ) @web.middle...
async def cache_control( request: web.Request, handler: Callable[[web.Request], Awaitable[web.Response]] ) -> web.Response: """Cache control middleware that sets appropriate cache headers based on file type and response status"""
Cache control middleware that sets appropriate cache headers based on file type and response status
response: web.Response = await handler(request) path_filename = request.path.rsplit("/", 1)[-1] is_entry_point = path_filename.startswith("index") and path_filename.endswith( ".json" ) if request.path.endswith(".js") or request.path.endswith(".css") or is_entry_point: response.head...
async def cache_control( request: web.Request, handler: Callable[[web.Request], Awaitable[web.Response]] ) -> web.Response: """Cache control middleware that sets appropriate cache headers based on file type and response status""" response: web.Response = await handler(request) path_filename = request.p...
[{"test_file": "tests-unit/server_test/test_cache_control.py", "test_function": "TestCacheControl.test_cache_control_scenarios", "test_content": "\"\"\"Tests for server cache control middleware\"\"\"\n\nimport pytest\nfrom aiohttp import web\nfrom aiohttp.test_utils import make_mocked_request\nfrom typing import Dict, ...
{"repo_url": "https://github.com/Comfy-Org/ComfyUI", "install_cmd": "pip install -e .", "commit_sha": "dff0a4a15887383c90a031e3fd48ebc41f6928e7", "frozen_requirements": "frozen_requirements/Comfy-Org_ComfyUI.txt"}
{"body_lines": 22, "file_lines": 54, "has_docstring": true, "num_tests": 9}
{"status": "passed", "tests_run": 9}
repo_patch/0008
"""Cache control middleware for ComfyUI server""" from aiohttp import web from typing import Callable, Awaitable # Time in seconds ONE_HOUR: int = 3600 ONE_DAY: int = 86400 IMG_EXTENSIONS = ( ".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp", ) @web.middle...
repo_patch/0009
docling-project/docling
docling/datamodel/asr_model_specs.py
_get_whisper_base_model
_get_whisper_base_model
function
null
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
def _get_whisper_base_model(): """ Get the best Whisper Base model for the current hardware. Automatically selects MLX Whisper Base for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Base. """ # Check if MPS is available (Apple Silicon)
Get the best Whisper Base model for the current hardware. Automatically selects MLX Whisper Base for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Base.
try: import torch has_mps = torch.backends.mps.is_built() and torch.backends.mps.is_available() except ImportError: has_mps = False # Check if mlx-whisper is available try: import mlx_whisper # type: ignore has_mlx_whisper = True except ImportError: ...
def _get_whisper_base_model(): """ Get the best Whisper Base model for the current hardware. Automatically selects MLX Whisper Base for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Base. """ # Check if MPS is available (Apple Silicon) try: import torch ...
[{"test_file": "tests/test_asr_mlx_whisper.py", "test_function": "TestMlxWhisperIntegration.test_model_selectors_mlx_and_native_paths", "test_content": "\"\"\"\nTest MLX Whisper integration for Apple Silicon ASR pipeline.\n\"\"\"\n\nimport sys\nfrom pathlib import Path\nfrom unittest.mock import Mock, patch\n\nimport p...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 34, "file_lines": 495, "has_docstring": true, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0009
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
repo_patch/0010
docling-project/docling
docling/datamodel/asr_model_specs.py
_get_whisper_tiny_model
_get_whisper_tiny_model
function
null
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
def _get_whisper_tiny_model(): """ Get the best Whisper Tiny model for the current hardware. Automatically selects MLX Whisper Tiny for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Tiny. """ # Check if MPS is available (Apple Silicon)
Get the best Whisper Tiny model for the current hardware. Automatically selects MLX Whisper Tiny for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Tiny.
try: import torch has_mps = torch.backends.mps.is_built() and torch.backends.mps.is_available() except ImportError: has_mps = False # Check if mlx-whisper is available try: import mlx_whisper # type: ignore has_mlx_whisper = True except ImportError: ...
def _get_whisper_tiny_model(): """ Get the best Whisper Tiny model for the current hardware. Automatically selects MLX Whisper Tiny for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Tiny. """ # Check if MPS is available (Apple Silicon) try: import torch ...
[{"test_file": "tests/test_asr_mlx_whisper.py", "test_function": "TestMlxWhisperIntegration.test_model_selectors_mlx_and_native_paths", "test_content": "\"\"\"\nTest MLX Whisper integration for Apple Silicon ASR pipeline.\n\"\"\"\n\nimport sys\nfrom pathlib import Path\nfrom unittest.mock import Mock, patch\n\nimport p...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 34, "file_lines": 495, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0010
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
repo_patch/0011
docling-project/docling
docling/datamodel/asr_model_specs.py
_get_whisper_medium_model
_get_whisper_medium_model
function
null
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
def _get_whisper_medium_model(): """ Get the best Whisper Medium model for the current hardware. Automatically selects MLX Whisper Medium for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Medium. """ # Check if MPS is available (Apple Silicon)
Get the best Whisper Medium model for the current hardware. Automatically selects MLX Whisper Medium for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Medium.
try: import torch has_mps = torch.backends.mps.is_built() and torch.backends.mps.is_available() except ImportError: has_mps = False # Check if mlx-whisper is available try: import mlx_whisper # type: ignore has_mlx_whisper = True except ImportError: ...
def _get_whisper_medium_model(): """ Get the best Whisper Medium model for the current hardware. Automatically selects MLX Whisper Medium for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Medium. """ # Check if MPS is available (Apple Silicon) try: import ...
[{"test_file": "tests/test_asr_mlx_whisper.py", "test_function": "TestMlxWhisperIntegration.test_model_selectors_mlx_and_native_paths", "test_content": "\"\"\"\nTest MLX Whisper integration for Apple Silicon ASR pipeline.\n\"\"\"\n\nimport sys\nfrom pathlib import Path\nfrom unittest.mock import Mock, patch\n\nimport p...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 34, "file_lines": 495, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0011
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
repo_patch/0012
docling-project/docling
docling/backend/mets_gbs_backend.py
unload
MetsGbsPageBackend.unload
method
MetsGbsPageBackend
"""Backend for GBS Google Books schema.""" import logging import tarfile from collections.abc import Iterable from dataclasses import dataclass from enum import Enum from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union from docling_core.types.doc im...
def unload(self) -> None:
if hasattr(self, "_im"): delattr(self, "_im") if hasattr(self, "_dpage"): delattr(self, "_dpage")
def unload(self) -> None: if hasattr(self, "_im"): delattr(self, "_im") if hasattr(self, "_dpage"): delattr(self, "_dpage")
[{"test_file": "tests/test_backend_mets_gbs.py", "test_function": "test_process_pages", "test_content": "from pathlib import Path\n\nimport pytest\n\nfrom docling.backend.mets_gbs_backend import MetsGbsDocumentBackend, MetsGbsPageBackend\nfrom docling.datamodel.base_models import BoundingBox, InputFormat\nfrom docling....
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 4, "file_lines": 400, "has_docstring": false, "num_tests": 4}
{"status": "passed", "tests_run": 4}
repo_patch/0012
"""Backend for GBS Google Books schema.""" import logging import tarfile from collections.abc import Iterable from dataclasses import dataclass from enum import Enum from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union from docling_core.types.doc im...
repo_patch/0013
docling-project/docling
docling/datamodel/asr_model_specs.py
_get_whisper_small_model
_get_whisper_small_model
function
null
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
def _get_whisper_small_model(): """ Get the best Whisper Small model for the current hardware. Automatically selects MLX Whisper Small for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Small. """ # Check if MPS is available (Apple Silicon)
Get the best Whisper Small model for the current hardware. Automatically selects MLX Whisper Small for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Small.
try: import torch has_mps = torch.backends.mps.is_built() and torch.backends.mps.is_available() except ImportError: has_mps = False # Check if mlx-whisper is available try: import mlx_whisper # type: ignore has_mlx_whisper = True except ImportError: ...
def _get_whisper_small_model(): """ Get the best Whisper Small model for the current hardware. Automatically selects MLX Whisper Small for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Small. """ # Check if MPS is available (Apple Silicon) try: import torc...
[{"test_file": "tests/test_asr_mlx_whisper.py", "test_function": "TestMlxWhisperIntegration.test_model_selectors_mlx_and_native_paths", "test_content": "\"\"\"\nTest MLX Whisper integration for Apple Silicon ASR pipeline.\n\"\"\"\n\nimport sys\nfrom pathlib import Path\nfrom unittest.mock import Mock, patch\n\nimport p...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 34, "file_lines": 495, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0013
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
repo_patch/0014
docling-project/docling
docling/datamodel/asr_model_specs.py
_get_whisper_large_model
_get_whisper_large_model
function
null
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
def _get_whisper_large_model(): """ Get the best Whisper Large model for the current hardware. Automatically selects MLX Whisper Large for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Large. """ # Check if MPS is available (Apple Silicon)
Get the best Whisper Large model for the current hardware. Automatically selects MLX Whisper Large for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Large.
try: import torch has_mps = torch.backends.mps.is_built() and torch.backends.mps.is_available() except ImportError: has_mps = False # Check if mlx-whisper is available try: import mlx_whisper # type: ignore has_mlx_whisper = True except ImportError: ...
def _get_whisper_large_model(): """ Get the best Whisper Large model for the current hardware. Automatically selects MLX Whisper Large for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Large. """ # Check if MPS is available (Apple Silicon) try: import torc...
[{"test_file": "tests/test_asr_mlx_whisper.py", "test_function": "TestMlxWhisperIntegration.test_model_selectors_mlx_and_native_paths", "test_content": "\"\"\"\nTest MLX Whisper integration for Apple Silicon ASR pipeline.\n\"\"\"\n\nimport sys\nfrom pathlib import Path\nfrom unittest.mock import Mock, patch\n\nimport p...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 34, "file_lines": 495, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0014
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
repo_patch/0015
docling-project/docling
docling/backend/mets_gbs_backend.py
get_text_in_rect
MetsGbsPageBackend.get_text_in_rect
method
MetsGbsPageBackend
"""Backend for GBS Google Books schema.""" import logging import tarfile from collections.abc import Iterable from dataclasses import dataclass from enum import Enum from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union from docling_core.types.doc im...
def get_text_in_rect(self, bbox: BoundingBox) -> str: # Find intersecting cells on the page
text_piece = "" page_size = self.get_size() scale = ( 1 # FIX - Replace with param in get_text_in_rect across backends (optional) ) for i, cell in enumerate(self._dpage.textline_cells): cell_bbox = ( cell.rect.to_bounding_box() ...
def get_text_in_rect(self, bbox: BoundingBox) -> str: # Find intersecting cells on the page text_piece = "" page_size = self.get_size() scale = ( 1 # FIX - Replace with param in get_text_in_rect across backends (optional) ) for i, cell in enumerate(self...
[{"test_file": "tests/test_backend_mets_gbs.py", "test_function": "test_get_text_from_rect", "test_content": "from pathlib import Path\n\nimport pytest\n\nfrom docling.backend.mets_gbs_backend import MetsGbsDocumentBackend, MetsGbsPageBackend\nfrom docling.datamodel.base_models import BoundingBox, InputFormat\nfrom doc...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 17, "file_lines": 400, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0015
"""Backend for GBS Google Books schema.""" import logging import tarfile from collections.abc import Iterable from dataclasses import dataclass from enum import Enum from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union from docling_core.types.doc im...
repo_patch/0016
docling-project/docling
docling/datamodel/asr_model_specs.py
_get_whisper_turbo_model
_get_whisper_turbo_model
function
null
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
def _get_whisper_turbo_model(): """ Get the best Whisper Turbo model for the current hardware. Automatically selects MLX Whisper Turbo for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Turbo. """ # Check if MPS is available (Apple Silicon)
Get the best Whisper Turbo model for the current hardware. Automatically selects MLX Whisper Turbo for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Turbo.
try: import torch has_mps = torch.backends.mps.is_built() and torch.backends.mps.is_available() except ImportError: has_mps = False # Check if mlx-whisper is available try: import mlx_whisper # type: ignore has_mlx_whisper = True except ImportError: ...
def _get_whisper_turbo_model(): """ Get the best Whisper Turbo model for the current hardware. Automatically selects MLX Whisper Turbo for Apple Silicon (MPS) if available, otherwise falls back to native Whisper Turbo. """ # Check if MPS is available (Apple Silicon) try: import torc...
[{"test_file": "tests/test_asr_mlx_whisper.py", "test_function": "TestMlxWhisperIntegration.test_model_selectors_mlx_and_native_paths", "test_content": "\"\"\"\nTest MLX Whisper integration for Apple Silicon ASR pipeline.\n\"\"\"\n\nimport sys\nfrom pathlib import Path\nfrom unittest.mock import Mock, patch\n\nimport p...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 34, "file_lines": 495, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0016
import logging from enum import Enum from pydantic import ( AnyUrl, ) from docling.datamodel.accelerator_options import AcceleratorDevice from docling.datamodel.pipeline_options_asr_model import ( # AsrResponseFormat, # ApiAsrOptions, InferenceAsrFramework, InlineAsrMlxWhisperOptions, InlineAs...
repo_patch/0017
docling-project/docling
docling/backend/mets_gbs_backend.py
get_page_image
MetsGbsPageBackend.get_page_image
method
MetsGbsPageBackend
"""Backend for GBS Google Books schema.""" import logging import tarfile from collections.abc import Iterable from dataclasses import dataclass from enum import Enum from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union from docling_core.types.doc im...
def get_page_image( self, scale: float = 1, cropbox: Optional[BoundingBox] = None ) -> Image.Image:
page_size = self.get_size() assert ( page_size.width == self._im.size[0] and page_size.height == self._im.size[1] ) if not cropbox: cropbox = BoundingBox( l=0, r=page_size.width, t=0, b=page_size.hei...
def get_page_image( self, scale: float = 1, cropbox: Optional[BoundingBox] = None ) -> Image.Image: page_size = self.get_size() assert ( page_size.width == self._im.size[0] and page_size.height == self._im.size[1] ) if not cropbox: cropbox = Bound...
[{"test_file": "tests/test_backend_mets_gbs.py", "test_function": "test_crop_page_image", "test_content": "from pathlib import Path\n\nimport pytest\n\nfrom docling.backend.mets_gbs_backend import MetsGbsDocumentBackend, MetsGbsPageBackend\nfrom docling.datamodel.base_models import BoundingBox, InputFormat\nfrom doclin...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 16, "file_lines": 400, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0017
"""Backend for GBS Google Books schema.""" import logging import tarfile from collections.abc import Iterable from dataclasses import dataclass from enum import Enum from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union from docling_core.types.doc im...
repo_patch/0018
docling-project/docling
docling/backend/image_backend.py
get_bitmap_rects
_ImagePageBackend.get_bitmap_rects
method
_ImagePageBackend
import logging from io import BytesIO from pathlib import Path from typing import Iterable, List, Optional, Union from docling_core.types.doc import BoundingBox, CoordOrigin from docling_core.types.doc.page import ( BoundingRectangle, PdfPageBoundaryType, PdfPageGeometry, SegmentedPdfPage, TextCell...
def get_bitmap_rects(self, scale: float = 1) -> Iterable[BoundingBox]: # For raw images, the entire page is a bitmap
assert self._image is not None page_size = self.get_size() full_page_bbox = BoundingBox( l=0.0, t=0.0, r=float(page_size.width), b=float(page_size.height), coord_origin=CoordOrigin.TOPLEFT, ) if scale != 1: f...
def get_bitmap_rects(self, scale: float = 1) -> Iterable[BoundingBox]: # For raw images, the entire page is a bitmap assert self._image is not None page_size = self.get_size() full_page_bbox = BoundingBox( l=0.0, t=0.0, r=float(page_size.width), ...
[{"test_file": "tests/test_backend_image_native.py", "test_function": "test_get_bitmap_rects", "test_content": "from io import BytesIO\nfrom pathlib import Path\n\nimport pytest\nfrom docling_core.types.doc import BoundingBox, CoordOrigin\nfrom PIL import Image\n\nfrom docling.backend.image_backend import ImageDocument...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 12, "file_lines": 189, "has_docstring": false, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0018
import logging from io import BytesIO from pathlib import Path from typing import Iterable, List, Optional, Union from docling_core.types.doc import BoundingBox, CoordOrigin from docling_core.types.doc.page import ( BoundingRectangle, PdfPageBoundaryType, PdfPageGeometry, SegmentedPdfPage, TextCell...
repo_patch/0019
docling-project/docling
docling/backend/image_backend.py
load_page
ImageDocumentBackend.load_page
method
ImageDocumentBackend
import logging from io import BytesIO from pathlib import Path from typing import Iterable, List, Optional, Union from docling_core.types.doc import BoundingBox, CoordOrigin from docling_core.types.doc.page import ( BoundingRectangle, PdfPageBoundaryType, PdfPageGeometry, SegmentedPdfPage, TextCell...
def load_page(self, page_no: int) -> _ImagePageBackend:
if not (0 <= page_no < len(self._frames)): raise IndexError(f"Page index out of range: {page_no}") return _ImagePageBackend(self._frames[page_no])
def load_page(self, page_no: int) -> _ImagePageBackend: if not (0 <= page_no < len(self._frames)): raise IndexError(f"Page index out of range: {page_no}") return _ImagePageBackend(self._frames[page_no])
[{"test_file": "tests/test_backend_image_native.py", "test_function": "test_get_size", "test_content": "from io import BytesIO\nfrom pathlib import Path\n\nimport pytest\nfrom docling_core.types.doc import BoundingBox, CoordOrigin\nfrom PIL import Image\n\nfrom docling.backend.image_backend import ImageDocumentBackend,...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 3, "file_lines": 189, "has_docstring": false, "num_tests": 9}
{"status": "passed", "tests_run": 9}
repo_patch/0019
import logging from io import BytesIO from pathlib import Path from typing import Iterable, List, Optional, Union from docling_core.types.doc import BoundingBox, CoordOrigin from docling_core.types.doc.page import ( BoundingRectangle, PdfPageBoundaryType, PdfPageGeometry, SegmentedPdfPage, TextCell...
repo_patch/0020
docling-project/docling
docling/backend/image_backend.py
get_page_image
_ImagePageBackend.get_page_image
method
_ImagePageBackend
import logging from io import BytesIO from pathlib import Path from typing import Iterable, List, Optional, Union from docling_core.types.doc import BoundingBox, CoordOrigin from docling_core.types.doc.page import ( BoundingRectangle, PdfPageBoundaryType, PdfPageGeometry, SegmentedPdfPage, TextCell...
def get_page_image( self, scale: float = 1, cropbox: Optional[BoundingBox] = None ) -> Image.Image:
assert self._image is not None img = self._image if cropbox is not None: # Expected cropbox comes in TOPLEFT coords in our pipeline if cropbox.coord_origin != CoordOrigin.TOPLEFT: # Convert to TOPLEFT relative to current image height cropb...
def get_page_image( self, scale: float = 1, cropbox: Optional[BoundingBox] = None ) -> Image.Image: assert self._image is not None img = self._image if cropbox is not None: # Expected cropbox comes in TOPLEFT coords in our pipeline if cropbox.coord_origin...
[{"test_file": "tests/test_backend_image_native.py", "test_function": "test_get_page_image_full", "test_content": "from io import BytesIO\nfrom pathlib import Path\n\nimport pytest\nfrom docling_core.types.doc import BoundingBox, CoordOrigin\nfrom PIL import Image\n\nfrom docling.backend.image_backend import ImageDocum...
{"repo_url": "https://github.com/docling-project/docling", "install_cmd": "pip install -e .", "commit_sha": "752f81b3dd451208fb59297ea5ef7917cb4fc891", "frozen_requirements": "frozen_requirements/docling-project_docling.txt"}
{"body_lines": 18, "file_lines": 189, "has_docstring": false, "num_tests": 4}
{"status": "passed", "tests_run": 4}
repo_patch/0020
import logging from io import BytesIO from pathlib import Path from typing import Iterable, List, Optional, Union from docling_core.types.doc import BoundingBox, CoordOrigin from docling_core.types.doc.page import ( BoundingRectangle, PdfPageBoundaryType, PdfPageGeometry, SegmentedPdfPage, TextCell...
repo_patch/0021
fastapi/fastapi
fastapi/_compat/shared.py
is_uploadfile_sequence_annotation
is_uploadfile_sequence_annotation
function
null
import types import typing import warnings from collections import deque from collections.abc import Mapping, Sequence from dataclasses import is_dataclass from typing import ( Annotated, Any, TypeGuard, TypeVar, Union, get_args, get_origin, ) from fastapi.types import UnionType from pydant...
def is_uploadfile_sequence_annotation(annotation: Any) -> bool:
origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_uploadfile_sequence_annotation(arg): at_least_one = True continue return at_least_one return field_annota...
def is_uploadfile_sequence_annotation(annotation: Any) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_uploadfile_sequence_annotation(arg): at_least_one = True ...
[{"test_file": "tests/test_compat.py", "test_function": "test_is_uploadfile_sequence_annotation", "test_content": "from fastapi import FastAPI, UploadFile\nfrom fastapi._compat import (\n Undefined,\n is_uploadfile_sequence_annotation,\n)\nfrom fastapi._compat.shared import is_bytes_sequence_annotation\nfrom fast...
{"repo_url": "https://github.com/fastapi/fastapi", "install_cmd": "pip install -e .", "commit_sha": "7a03018d6a880651d4fc2b5c79419eb233d7aee5", "frozen_requirements": "frozen_requirements/fastapi_fastapi.txt"}
{"body_lines": 12, "file_lines": 215, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0021
import types import typing import warnings from collections import deque from collections.abc import Mapping, Sequence from dataclasses import is_dataclass from typing import ( Annotated, Any, TypeGuard, TypeVar, Union, get_args, get_origin, ) from fastapi.types import UnionType from pydant...
repo_patch/0022
fastapi/fastapi
docs_src/generate_clients/tutorial002_py310.py
get_items
get_items
function
null
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float class ResponseMessage(BaseModel): message: str class User(BaseModel): username: str email: str @app.post("/items/", response_model=ResponseMessage, tags=["items"]) async ...
async def get_items():
return [ {"name": "Plumbus", "price": 3}, {"name": "Portal Gun", "price": 9001}, ]
async def get_items(): return [ {"name": "Plumbus", "price": 3}, {"name": "Portal Gun", "price": 9001}, ]
[{"test_file": "tests/test_tutorial/test_python_types/test_tutorial005.py", "test_function": "test_get_items", "test_content": "from docs_src.python_types.tutorial005_py310 import get_items\n\n\ndef test_get_items():\n res = get_items(\n \"item_a\",\n \"item_b\",\n \"item_c\",\n \"item_d\...
{"repo_url": "https://github.com/fastapi/fastapi", "install_cmd": "pip install -e .", "commit_sha": "7a03018d6a880651d4fc2b5c79419eb233d7aee5", "frozen_requirements": "frozen_requirements/fastapi_fastapi.txt"}
{"body_lines": 4, "file_lines": 37, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0022
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float class ResponseMessage(BaseModel): message: str class User(BaseModel): username: str email: str @app.post("/items/", response_model=ResponseMessage, tags=["items"]) async ...
repo_patch/0023
fastapi/fastapi
fastapi/_compat/v2.py
serialize_sequence_value
serialize_sequence_value
function
null
import re import warnings from collections.abc import Sequence from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from functools import lru_cache from typing import ( Annotated, Any, Literal, Union, cast, get_args, get_origin, ) from fastapi._compat ...
def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation if origin_type is Union or origin_type is UnionType: # Handle optional sequences union_args = get_args(field.field_info.annotation) for union_arg in union_args: if union_arg is type(None): ...
def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation if origin_type is Union or origin_type is UnionType: # Handle optional sequences union_args = get_args(field.field_info.annotation) ...
[{"test_file": "tests/test_compat.py", "test_function": "test_serialize_sequence_value_with_optional_list", "test_content": "from fastapi import FastAPI, UploadFile\nfrom fastapi._compat import (\n Undefined,\n is_uploadfile_sequence_annotation,\n)\nfrom fastapi._compat.shared import is_bytes_sequence_annotation\...
{"repo_url": "https://github.com/fastapi/fastapi", "install_cmd": "pip install -e .", "commit_sha": "7a03018d6a880651d4fc2b5c79419eb233d7aee5", "frozen_requirements": "frozen_requirements/fastapi_fastapi.txt"}
{"body_lines": 10, "file_lines": 481, "has_docstring": false, "num_tests": 3}
{"status": "passed", "tests_run": 3}
repo_patch/0023
import re import warnings from collections.abc import Sequence from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from functools import lru_cache from typing import ( Annotated, Any, Literal, Union, cast, get_args, get_origin, ) from fastapi._compat ...
repo_patch/0024
fastapi/fastapi
docs_src/generate_clients/tutorial001_py310.py
get_items
get_items
function
null
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float class ResponseMessage(BaseModel): message: str @app.post("/items/", response_model=ResponseMessage) async def create_item(item: Item): return {"message": "item received"} @ap...
async def get_items():
return [ {"name": "Plumbus", "price": 3}, {"name": "Portal Gun", "price": 9001}, ]
async def get_items(): return [ {"name": "Plumbus", "price": 3}, {"name": "Portal Gun", "price": 9001}, ]
[{"test_file": "tests/test_tutorial/test_python_types/test_tutorial005.py", "test_function": "test_get_items", "test_content": "from docs_src.python_types.tutorial005_py310 import get_items\n\n\ndef test_get_items():\n res = get_items(\n \"item_a\",\n \"item_b\",\n \"item_c\",\n \"item_d\...
{"repo_url": "https://github.com/fastapi/fastapi", "install_cmd": "pip install -e .", "commit_sha": "7a03018d6a880651d4fc2b5c79419eb233d7aee5", "frozen_requirements": "frozen_requirements/fastapi_fastapi.txt"}
{"body_lines": 4, "file_lines": 27, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0024
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float class ResponseMessage(BaseModel): message: str @app.post("/items/", response_model=ResponseMessage) async def create_item(item: Item): return {"message": "item received"} @ap...
repo_patch/0025
fastapi/fastapi
docs_src/generate_clients/tutorial003_py310.py
get_items
get_items
function
null
from fastapi import FastAPI from fastapi.routing import APIRoute from pydantic import BaseModel def custom_generate_unique_id(route: APIRoute): return f"{route.tags[0]}-{route.name}" app = FastAPI(generate_unique_id_function=custom_generate_unique_id) class Item(BaseModel): name: str price: float cl...
async def get_items():
return [ {"name": "Plumbus", "price": 3}, {"name": "Portal Gun", "price": 9001}, ]
async def get_items(): return [ {"name": "Plumbus", "price": 3}, {"name": "Portal Gun", "price": 9001}, ]
[{"test_file": "tests/test_tutorial/test_python_types/test_tutorial005.py", "test_function": "test_get_items", "test_content": "from docs_src.python_types.tutorial005_py310 import get_items\n\n\ndef test_get_items():\n res = get_items(\n \"item_a\",\n \"item_b\",\n \"item_c\",\n \"item_d\...
{"repo_url": "https://github.com/fastapi/fastapi", "install_cmd": "pip install -e .", "commit_sha": "7a03018d6a880651d4fc2b5c79419eb233d7aee5", "frozen_requirements": "frozen_requirements/fastapi_fastapi.txt"}
{"body_lines": 4, "file_lines": 43, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0025
from fastapi import FastAPI from fastapi.routing import APIRoute from pydantic import BaseModel def custom_generate_unique_id(route: APIRoute): return f"{route.tags[0]}-{route.name}" app = FastAPI(generate_unique_id_function=custom_generate_unique_id) class Item(BaseModel): name: str price: float cl...
repo_patch/0026
fastapi/fastapi
fastapi/_compat/shared.py
is_bytes_sequence_annotation
is_bytes_sequence_annotation
function
null
import types import typing import warnings from collections import deque from collections.abc import Mapping, Sequence from dataclasses import is_dataclass from typing import ( Annotated, Any, TypeGuard, TypeVar, Union, get_args, get_origin, ) from fastapi.types import UnionType from pydant...
def is_bytes_sequence_annotation(annotation: Any) -> bool:
origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_bytes_sequence_annotation(arg): at_least_one = True continue return at_least_one return field_annotation_...
def is_bytes_sequence_annotation(annotation: Any) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_bytes_sequence_annotation(arg): at_least_one = True contin...
[{"test_file": "tests/test_compat.py", "test_function": "test_is_bytes_sequence_annotation_union", "test_content": "from fastapi import FastAPI, UploadFile\nfrom fastapi._compat import (\n Undefined,\n is_uploadfile_sequence_annotation,\n)\nfrom fastapi._compat.shared import is_bytes_sequence_annotation\nfrom fas...
{"repo_url": "https://github.com/fastapi/fastapi", "install_cmd": "pip install -e .", "commit_sha": "7a03018d6a880651d4fc2b5c79419eb233d7aee5", "frozen_requirements": "frozen_requirements/fastapi_fastapi.txt"}
{"body_lines": 12, "file_lines": 215, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0026
import types import typing import warnings from collections import deque from collections.abc import Mapping, Sequence from dataclasses import is_dataclass from typing import ( Annotated, Any, TypeGuard, TypeVar, Union, get_args, get_origin, ) from fastapi.types import UnionType from pydant...
repo_patch/0027
freqtrade/freqtrade
freqtrade/strategy/strategy_validation.py
assert_df
StrategyResultValidator.assert_df
method
StrategyResultValidator
import logging from datetime import datetime from pandas import DataFrame from freqtrade.exceptions import StrategyError logger = logging.getLogger(__name__) class StrategyResultValidator: def __init__(self, dataframe: DataFrame, warn_only: bool = False): self._warn_only = warn_only self._leng...
def assert_df(self, dataframe: DataFrame): """ Ensure dataframe (length, last candle) was not modified, and has all elements we need. Raises a StrategyError if the dataframe does not match the expected values. If warn_only is set, it will log a warning instead of raising an error. ...
Ensure dataframe (length, last candle) was not modified, and has all elements we need. Raises a StrategyError if the dataframe does not match the expected values. If warn_only is set, it will log a warning instead of raising an error. :param dataframe: DataFrame to validate :raises StrategyError: If the dataframe does ...
message_template = "Dataframe returned from strategy has mismatching {}." message = "" if dataframe is None: message = "No dataframe returned (return statement missing?)." elif self._length != len(dataframe): message = message_template.format("length") eli...
def assert_df(self, dataframe: DataFrame): """ Ensure dataframe (length, last candle) was not modified, and has all elements we need. Raises a StrategyError if the dataframe does not match the expected values. If warn_only is set, it will log a warning instead of raising an error. ...
[{"test_file": "tests/strategy/test_interface.py", "test_function": "test_assert_df", "test_content": "# pragma pylint: disable=missing-docstring, C0103\nimport logging\nimport math\nfrom datetime import UTC, datetime, timedelta\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nimport pytest\nfrom panda...
{"repo_url": "https://github.com/freqtrade/freqtrade", "install_cmd": "pip install -e .", "commit_sha": "f92c66db565411401079ab80356b8d1c5a46db3f", "frozen_requirements": "frozen_requirements/freqtrade_freqtrade.txt"}
{"body_lines": 15, "file_lines": 43, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0027
import logging from datetime import datetime from pandas import DataFrame from freqtrade.exceptions import StrategyError logger = logging.getLogger(__name__) class StrategyResultValidator: def __init__(self, dataframe: DataFrame, warn_only: bool = False): self._warn_only = warn_only self._leng...
repo_patch/0028
freqtrade/freqtrade
freqtrade/data/btanalysis/historic_precision.py
get_tick_size_over_time
get_tick_size_over_time
function
null
from numpy import format_float_positional from pandas import DataFrame, Series def get_tick_size_over_time(candles: DataFrame) -> Series: """ Calculate the number of significant digits for candles over time. It's using the Monthly maximum of the number of significant digits for each month. :param cand...
def get_tick_size_over_time(candles: DataFrame) -> Series: """ Calculate the number of significant digits for candles over time. It's using the Monthly maximum of the number of significant digits for each month. :param candles: DataFrame with OHLCV data :return: Series with the average number of sig...
Calculate the number of significant digits for candles over time. It's using the Monthly maximum of the number of significant digits for each month. :param candles: DataFrame with OHLCV data :return: Series with the average number of significant digits for each month
for col in ["open", "high", "low", "close"]: candles[f"{col}_count"] = ( candles[col] .apply(format_float_positional, precision=14, unique=False, fractional=False, trim="-") .str.extract(r"\.(\d*[1-9])")[0] .str.len() ) candles["max_count"] = candl...
def get_tick_size_over_time(candles: DataFrame) -> Series: """ Calculate the number of significant digits for candles over time. It's using the Monthly maximum of the number of significant digits for each month. :param candles: DataFrame with OHLCV data :return: Series with the average number of sig...
[{"test_file": "tests/data/test_historic_precision.py", "test_function": "test_get_tick_size_over_time", "test_content": "# pragma pylint: disable=missing-docstring, C0103\n\nfrom datetime import UTC\n\nimport pandas as pd\nfrom numpy import nan\nfrom pandas import DataFrame, Timestamp\n\nfrom freqtrade.data.btanalysis...
{"repo_url": "https://github.com/freqtrade/freqtrade", "install_cmd": "pip install -e .", "commit_sha": "f92c66db565411401079ab80356b8d1c5a46db3f", "frozen_requirements": "frozen_requirements/freqtrade_freqtrade.txt"}
{"body_lines": 17, "file_lines": 32, "has_docstring": true, "num_tests": 4}
{"status": "passed", "tests_run": 4}
repo_patch/0028
from numpy import format_float_positional from pandas import DataFrame, Series def get_tick_size_over_time(candles: DataFrame) -> Series: """ Calculate the number of significant digits for candles over time. It's using the Monthly maximum of the number of significant digits for each month. :param cand...
repo_patch/0029
hiyouga/LlamaFactory
src/llamafactory/v1/plugins/model_plugins/peft.py
get_lora_model
get_lora_model
function
null
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def get_lora_model(model: HFModel, config: LoraConfigDict, is_train: bool = False) -> HFModel:
adapter_name_or_path = config.get("adapter_name_or_path") if adapter_name_or_path: return load_adapter(model, adapter_name_or_path, is_train) logger.info_rank0("Fine-tuning method: LoRA") target_modules = config.get("target_modules", "all") # Handle target modules if target_modules =...
def get_lora_model(model: HFModel, config: LoraConfigDict, is_train: bool = False) -> HFModel: adapter_name_or_path = config.get("adapter_name_or_path") if adapter_name_or_path: return load_adapter(model, adapter_name_or_path, is_train) logger.info_rank0("Fine-tuning method: LoRA") target_mod...
[{"test_file": "tests_v1/plugins/model_plugins/test_peft.py", "test_function": "test_get_lora_model", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a c...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 26, "file_lines": 344, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0029
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0030
hiyouga/LlamaFactory
src/llamafactory/v1/samplers/cli_sampler.py
generate
SyncSampler.generate
method
SyncSampler
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def generate(self, messages: list[Message], tools: str | None = None) -> Generator[str, None, None]: """Generate tokens synchronously. Args: messages: List of messages. tools: Tools string. Yields: Generated tokens. """
Generate tokens synchronously. Args: messages: List of messages. tools: Tools string. Yields: Generated tokens.
generator = super().generate(messages, tools) while True: try: token = asyncio.run_coroutine_threadsafe(generator.__anext__(), self._loop).result() yield token except StopAsyncIteration: break
def generate(self, messages: list[Message], tools: str | None = None) -> Generator[str, None, None]: """Generate tokens synchronously. Args: messages: List of messages. tools: Tools string. Yields: Generated tokens. """ generator = super(...
[{"test_file": "tests_v1/sampler/test_cli_sampler.py", "test_function": "test_sync_sampler", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of th...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 7, "file_lines": 126, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0030
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0031
hiyouga/LlamaFactory
src/llamafactory/v1/core/utils/rendering.py
render_messages
Renderer.render_messages
method
Renderer
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def render_messages( self, messages: list[Message], tools: str | None = None, is_generate: bool = False ) -> ModelInput: """Apply template to messages and convert them to model input. Args: messages (list[Message]): The messages to render. tools (str | None, optional...
Apply template to messages and convert them to model input. Args: messages (list[Message]): The messages to render. tools (str | None, optional): The tools to use. Defaults to None. is_generate (bool, optional): Whether to render for generation. Defaults to False. Returns: ModelInput: The rendered mod...
if self.template == "chatml": return render_chatml_messages(self.processor, messages, tools, is_generate) else: from ...plugins.model_plugins.rendering import RenderingPlugin return RenderingPlugin(self.template).render_messages(self.processor, messages, tools, is_ge...
def render_messages( self, messages: list[Message], tools: str | None = None, is_generate: bool = False ) -> ModelInput: """Apply template to messages and convert them to model input. Args: messages (list[Message]): The messages to render. tools (str | None, opti...
[{"test_file": "tests_v1/core/utils/test_rendering.py", "test_function": "test_chatml_rendering", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy ...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 5, "file_lines": 170, "has_docstring": true, "num_tests": 4}
{"status": "passed", "tests_run": 4}
repo_patch/0031
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0032
hiyouga/LlamaFactory
src/llamafactory/v1/plugins/model_plugins/peft.py
_find_all_linear_modules
_find_all_linear_modules
function
null
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def _find_all_linear_modules(model: HFModel) -> list[str]: r"""Find all available modules to apply LoRA."""
Find all available modules to apply LoRA.
forbidden_modules = {"lm_head", "output_layer", "output"} module_names = set() for name, module in model.named_modules(): if any(forbidden_module in name for forbidden_module in forbidden_modules): continue if "Linear" in module.__class__.__name__ and "Embedding" not in module._...
def _find_all_linear_modules(model: HFModel) -> list[str]: r"""Find all available modules to apply LoRA.""" forbidden_modules = {"lm_head", "output_layer", "output"} module_names = set() for name, module in model.named_modules(): if any(forbidden_module in name for forbidden_module in forbidden_...
[{"test_file": "tests_v1/plugins/model_plugins/test_peft.py", "test_function": "test_find_all_linear_modules", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may o...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 8, "file_lines": 344, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0032
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0033
hiyouga/LlamaFactory
src/llamafactory/v1/accelerator/helper.py
get_current_device
get_current_device
function
null
# Copyright 2025 Bytedance Ltd. and the LlamaFactory team. # # This code is inspired by the Bytedance's VeOmni library. # https://github.com/ByteDance-Seed/VeOmni/blob/v0.1.4/veomni/utils/dist_utils.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance w...
def get_current_device() -> torch.device: """Get current accelerator device."""
Get current accelerator device.
if get_current_accelerator().type == DeviceType.CPU: return torch.device(DeviceType.CPU.value) else: return torch.device(type=get_current_accelerator().type, index=torch.accelerator.current_device_index())
def get_current_device() -> torch.device: """Get current accelerator device.""" if get_current_accelerator().type == DeviceType.CPU: return torch.device(DeviceType.CPU.value) else: return torch.device(type=get_current_accelerator().type, index=torch.accelerator.current_device_index())
[{"test_file": "tests/model/model_utils/test_checkpointing.py", "test_function": "test_upcast_lmhead_output", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may ob...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 4, "file_lines": 236, "has_docstring": true, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0033
# Copyright 2025 Bytedance Ltd. and the LlamaFactory team. # # This code is inspired by the Bytedance's VeOmni library. # https://github.com/ByteDance-Seed/VeOmni/blob/v0.1.4/veomni/utils/dist_utils.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance w...
repo_patch/0034
hiyouga/LlamaFactory
src/llamafactory/v1/plugins/model_plugins/peft.py
merge_and_export_model
merge_and_export_model
function
null
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def merge_and_export_model(args: InputArgument = None):
model_args, _, _, _ = get_args(args) export_config = model_args.peft_config if export_config is None: raise ValueError("Please specify peft_config to merge and export model.") export_dir = export_config.get("export_dir") if export_dir is None: raise ValueError("Please specify expor...
def merge_and_export_model(args: InputArgument = None): model_args, _, _, _ = get_args(args) export_config = model_args.peft_config if export_config is None: raise ValueError("Please specify peft_config to merge and export model.") export_dir = export_config.get("export_dir") if export_dir...
[{"test_file": "tests_v1/plugins/model_plugins/test_peft.py", "test_function": "test_merge_and_export_model", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may ob...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 49, "file_lines": 344, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0034
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0035
hiyouga/LlamaFactory
src/llamafactory/v1/plugins/model_plugins/peft.py
load_adapter
load_adapter
function
null
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def load_adapter(model: HFModel, adapter_name_or_path: Union[list[str], str], is_train: bool) -> HFModel: r"""Loads adapter(s) into the model. Determine adapter usage based on mode: - Training: Load the single adapter for continued training. - Inference: Merge all adapters to clean up the model. - ...
Loads adapter(s) into the model. Determine adapter usage based on mode: - Training: Load the single adapter for continued training. - Inference: Merge all adapters to clean up the model. - Unmergeable: Keep the single adapter active without merging.
if not isinstance(adapter_name_or_path, list): adapter_name_or_path = [adapter_name_or_path] # TODO # Adapters fix for deepspeed and quant # Adapters fix for vision if is_train and len(adapter_name_or_path) > 1: raise ValueError( "When `adapter_name_or_path` is provided...
def load_adapter(model: HFModel, adapter_name_or_path: Union[list[str], str], is_train: bool) -> HFModel: r"""Loads adapter(s) into the model. Determine adapter usage based on mode: - Training: Load the single adapter for continued training. - Inference: Merge all adapters to clean up the model. - ...
[{"test_file": "tests_v1/plugins/model_plugins/test_peft.py", "test_function": "test_load_adapter_single_for_inference", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n#...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 29, "file_lines": 344, "has_docstring": true, "num_tests": 4}
{"status": "passed", "tests_run": 4}
repo_patch/0035
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0036
hiyouga/LlamaFactory
src/llamafactory/v1/core/utils/rendering.py
parse_message
Renderer.parse_message
method
Renderer
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def parse_message(self, generated_text: str) -> Message: """Parse a message in the template format. Args: generated_text (str): The generated text in the template format. Returns: Message: The parsed message. """
Parse a message in the template format. Args: generated_text (str): The generated text in the template format. Returns: Message: The parsed message.
if self.template == "chatml": return parse_chatml_message(generated_text) else: from ...plugins.model_plugins.rendering import RenderingPlugin return RenderingPlugin(self.template).parse_message(generated_text)
def parse_message(self, generated_text: str) -> Message: """Parse a message in the template format. Args: generated_text (str): The generated text in the template format. Returns: Message: The parsed message. """ if self.template == "chatml": ...
[{"test_file": "tests_v1/core/utils/test_rendering.py", "test_function": "test_chatml_parse", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of t...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 5, "file_lines": 170, "has_docstring": true, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0036
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0037
hiyouga/LlamaFactory
src/llamafactory/v1/core/utils/rendering.py
process_samples
Renderer.process_samples
method
Renderer
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
def process_samples(self, samples: list[Sample]) -> list[ModelInput]: """Process samples to model input. Args: samples (list[Sample]): The samples to process. Returns: list[ModelInput]: The processed model inputs. """
Process samples to model input. Args: samples (list[Sample]): The samples to process. Returns: list[ModelInput]: The processed model inputs.
model_inputs = [] for sample in samples: if "messages" in sample: model_input = self.render_messages(sample["messages"], sample.get("tools")) elif "chosen_messages" in sample and "rejected_messages" in sample: chosen_input = self.render_messages(sa...
def process_samples(self, samples: list[Sample]) -> list[ModelInput]: """Process samples to model input. Args: samples (list[Sample]): The samples to process. Returns: list[ModelInput]: The processed model inputs. """ model_inputs = [] for sa...
[{"test_file": "tests_v1/core/utils/test_rendering.py", "test_function": "test_process_sft_samples", "test_content": "# Copyright 2025 the LlamaFactory team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a co...
{"repo_url": "https://github.com/hiyouga/LlamaFactory", "install_cmd": "pip install -e .", "commit_sha": "c0245c43fc1fbb87ed6b2f2d28bdcceed5103946", "frozen_requirements": "frozen_requirements/hiyouga_LlamaFactory.txt"}
{"body_lines": 28, "file_lines": 170, "has_docstring": true, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0037
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
repo_patch/0038
infiniflow/ragflow
common/string_utils.py
remove_redundant_spaces
remove_redundant_spaces
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def remove_redundant_spaces(txt: str): """ Remove redundant spaces around punctuation marks while preserving meaningful spaces. This function performs two main operations: 1. Remove spaces after left-boundary characters (opening brackets, etc.) 2. Remove spaces before right-boundary characters (clo...
Remove redundant spaces around punctuation marks while preserving meaningful spaces. This function performs two main operations: 1. Remove spaces after left-boundary characters (opening brackets, etc.) 2. Remove spaces before right-boundary characters (closing brackets, punctuation, etc.) Args: txt (str): Input t...
txt = re.sub(r"([^a-z0-9.,\)>]) +([^ ])", r"\1\2", txt, flags=re.IGNORECASE) # Second pass: Remove spaces before right-boundary characters # Matches: [non-space] + [non-alphanumeric-and-specific-left-punctuation] # Removes spaces before characters like non-')', non-',', non-'.', and non-alphanumeric ch...
def remove_redundant_spaces(txt: str): """ Remove redundant spaces around punctuation marks while preserving meaningful spaces. This function performs two main operations: 1. Remove spaces after left-boundary characters (opening brackets, etc.) 2. Remove spaces before right-boundary characters (clo...
[{"test_file": "test/unit_test/common/test_string_utils.py", "test_function": "TestRemoveRedundantSpaces.test_remove_spaces_before_commas", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 7, "file_lines": 74, "has_docstring": true, "num_tests": 32}
{"status": "passed", "tests_run": 32}
repo_patch/0038
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0039
infiniflow/ragflow
rag/utils/raptor_utils.py
get_skip_reason
get_skip_reason
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def get_skip_reason( file_type: Optional[str] = None, parser_id: str = "", parser_config: Optional[dict] = None ) -> str: """ Get a human-readable reason why Raptor was skipped. Args: file_type: File extension parser_id: Parser ID being used parser_config...
Get a human-readable reason why Raptor was skipped. Args: file_type: File extension parser_id: Parser ID being used parser_config: Parser configuration dict Returns: Reason string, or empty string if Raptor should not be skipped
parser_config = parser_config or {} if is_structured_file_type(file_type): return f"Structured data file ({file_type}) - Raptor auto-disabled" if file_type and file_type.lower() in [".pdf", "pdf"]: if is_tabular_pdf(parser_id, parser_config): return f"Tabular PDF (parser={parse...
def get_skip_reason( file_type: Optional[str] = None, parser_id: str = "", parser_config: Optional[dict] = None ) -> str: """ Get a human-readable reason why Raptor was skipped. Args: file_type: File extension parser_id: Parser ID being used parser_config...
[{"test_file": "test/unit_test/utils/test_raptor_utils.py", "test_function": "TestGetSkipReason.test_excel_skip_reason", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in com...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 7, "file_lines": 145, "has_docstring": true, "num_tests": 11}
{"status": "passed", "tests_run": 11}
repo_patch/0039
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0040
infiniflow/ragflow
common/file_utils.py
get_project_base_directory
get_project_base_directory
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def get_project_base_directory(*args):
global PROJECT_BASE if PROJECT_BASE is None: PROJECT_BASE = os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, ) ) if args: return os.path.join(PROJECT_BASE, *args) return PROJECT_BASE
def get_project_base_directory(*args): global PROJECT_BASE if PROJECT_BASE is None: PROJECT_BASE = os.path.abspath( os.path.join( os.path.dirname(os.path.realpath(__file__)), os.pardir, ) ) if args: return os.path.join(PROJECT_...
[{"test_file": "test/unit_test/common/test_file_utils.py", "test_function": "TestGetProjectBaseDirectory.test_returns_project_base_when_no_args", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not us...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 11, "file_lines": 40, "has_docstring": false, "num_tests": 9}
{"status": "passed", "tests_run": 9}
repo_patch/0040
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0041
infiniflow/ragflow
common/string_utils.py
clean_markdown_block
clean_markdown_block
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def clean_markdown_block(text): """ Remove Markdown code block syntax from the beginning and end of text. This function cleans Markdown code blocks by removing: - Opening ```Markdown tags (with optional whitespace and newlines) - Closing ``` tags (with optional whitespace and newlines) Args: ...
Remove Markdown code block syntax from the beginning and end of text. This function cleans Markdown code blocks by removing: - Opening ```Markdown tags (with optional whitespace and newlines) - Closing ``` tags (with optional whitespace and newlines) Args: text (str): Input text that may be wrapped in Markdown co...
text = re.sub(r'^\s*```markdown\s*\n?', '', text) # Remove closing ``` tag with optional whitespace and newlines # Matches: optional newline + optional whitespace + ``` + optional whitespace at end text = re.sub(r'\n?\s*```\s*$', '', text) # Return text with surrounding whitespace removed retu...
def clean_markdown_block(text): """ Remove Markdown code block syntax from the beginning and end of text. This function cleans Markdown code blocks by removing: - Opening ```Markdown tags (with optional whitespace and newlines) - Closing ``` tags (with optional whitespace and newlines) Args: ...
[{"test_file": "test/unit_test/common/test_string_utils.py", "test_function": "TestCleanMarkdownBlock.test_standard_markdown_block", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file e...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 6, "file_lines": 74, "has_docstring": true, "num_tests": 18}
{"status": "passed", "tests_run": 18}
repo_patch/0041
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0042
infiniflow/ragflow
common/misc_utils.py
convert_bytes
convert_bytes
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def convert_bytes(size_in_bytes: int) -> str: """ Format size in bytes. """
Format size in bytes.
if size_in_bytes == 0: return "0 B" units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] i = 0 size = float(size_in_bytes) while size >= 1024 and i < len(units) - 1: size /= 1024 i += 1 if i == 0 or size >= 100: return f"{size:.0f} {units[i]}" elif size >= 10: ...
def convert_bytes(size_in_bytes: int) -> str: """ Format size in bytes. """ if size_in_bytes == 0: return "0 B" units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] i = 0 size = float(size_in_bytes) while size >= 1024 and i < len(units) - 1: size /= 1024 i += 1 if i...
[{"test_file": "test/unit_test/common/test_misc_utils.py", "test_function": "TestConvertBytes.test_zero_bytes", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance w...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 14, "file_lines": 134, "has_docstring": true, "num_tests": 10}
{"status": "passed", "tests_run": 10}
repo_patch/0042
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0043
infiniflow/ragflow
common/misc_utils.py
download_img
download_img
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def download_img(url):
if not url: return "" response = requests.get(url) return "data:" + \ response.headers.get('Content-Type', 'image/jpg') + ";" + \ "base64," + base64.b64encode(response.content).decode("utf-8")
def download_img(url): if not url: return "" response = requests.get(url) return "data:" + \ response.headers.get('Content-Type', 'image/jpg') + ";" + \ "base64," + base64.b64encode(response.content).decode("utf-8")
[{"test_file": "test/unit_test/common/test_misc_utils.py", "test_function": "TestDownloadImg.test_empty_url_returns_empty_string", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file exc...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 6, "file_lines": 134, "has_docstring": false, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0043
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0044
infiniflow/ragflow
rag/utils/raptor_utils.py
is_structured_file_type
is_structured_file_type
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def is_structured_file_type(file_type: Optional[str]) -> bool: """ Check if a file type is structured data (Excel, CSV, etc.) Args: file_type: File extension (e.g., ".xlsx", ".csv") Returns: True if file is structured data type """
Check if a file type is structured data (Excel, CSV, etc.) Args: file_type: File extension (e.g., ".xlsx", ".csv") Returns: True if file is structured data type
if not file_type: return False # Normalize to lowercase and ensure leading dot file_type = file_type.lower() if not file_type.startswith("."): file_type = f".{file_type}" return file_type in STRUCTURED_EXTENSIONS
def is_structured_file_type(file_type: Optional[str]) -> bool: """ Check if a file type is structured data (Excel, CSV, etc.) Args: file_type: File extension (e.g., ".xlsx", ".csv") Returns: True if file is structured data type """ if not file_type: return F...
[{"test_file": "test/unit_test/utils/test_raptor_utils.py", "test_function": "TestIsStructuredFileType.test_file_type_detection", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file exce...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 7, "file_lines": 145, "has_docstring": true, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0044
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0045
infiniflow/ragflow
common/float_utils.py
get_float
get_float
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def get_float(v): """ Convert a value to float, handling None and exceptions gracefully. Attempts to convert the input value to a float. If the value is None or cannot be converted to float, returns negative infinity as a default value. Args: v: The value to convert to float. Can be any ty...
Convert a value to float, handling None and exceptions gracefully. Attempts to convert the input value to a float. If the value is None or cannot be converted to float, returns negative infinity as a default value. Args: v: The value to convert to float. Can be any type that float() accepts, or None. Retu...
if v is None: return float("-inf") try: return float(v) except Exception: return float("-inf")
def get_float(v): """ Convert a value to float, handling None and exceptions gracefully. Attempts to convert the input value to a float. If the value is None or cannot be converted to float, returns negative infinity as a default value. Args: v: The value to convert to float. Can be any ty...
[{"test_file": "test/unit_test/common/test_float_utils.py", "test_function": "TestGetFloat.test_valid_float_string", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in complia...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 6, "file_lines": 59, "has_docstring": true, "num_tests": 9}
{"status": "passed", "tests_run": 9}
repo_patch/0045
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0046
infiniflow/ragflow
common/time_utils.py
date_string_to_timestamp
date_string_to_timestamp
function
null
# # Copyright 2024 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def date_string_to_timestamp(time_str, format_string="%Y-%m-%d %H:%M:%S"): """ Convert a date string to timestamp in milliseconds. Args: time_str: Date string to convert format_string: Format of the input date string (default: "%Y-%m-%d %H:%M:%S") Returns: int: Unix timestamp i...
Convert a date string to timestamp in milliseconds. Args: time_str: Date string to convert format_string: Format of the input date string (default: "%Y-%m-%d %H:%M:%S") Returns: int: Unix timestamp in milliseconds Example: >>> date_string_to_timestamp("2024-01-01 00:00:00") 1704067200000
time_array = time.strptime(time_str, format_string) time_stamp = int(time.mktime(time_array) * 1000) return time_stamp
def date_string_to_timestamp(time_str, format_string="%Y-%m-%d %H:%M:%S"): """ Convert a date string to timestamp in milliseconds. Args: time_str: Date string to convert format_string: Format of the input date string (default: "%Y-%m-%d %H:%M:%S") Returns: int: Unix timestamp i...
[{"test_file": "test/unit_test/common/test_time_utils.py", "test_function": "TestDateStringToTimestamp.test_basic_date_string_conversion", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this ...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 3, "file_lines": 155, "has_docstring": true, "num_tests": 13}
{"status": "passed", "tests_run": 13}
repo_patch/0046
# # Copyright 2024 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0047
infiniflow/ragflow
common/decorator.py
singleton
singleton
function
null
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
def singleton(cls, *args, **kw):
instances = {} def _singleton(): key = str(cls) + str(os.getpid()) if key not in instances: instances[key] = cls(*args, **kw) return instances[key] return _singleton
def singleton(cls, *args, **kw): instances = {} def _singleton(): key = str(cls) + str(os.getpid()) if key not in instances: instances[key] = cls(*args, **kw) return instances[key] return _singleton
[{"test_file": "test/unit_test/common/test_decorator.py", "test_function": "test_singleton_decorator_returns_callable", "test_content": "#\n# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in comp...
{"repo_url": "https://github.com/infiniflow/ragflow", "install_cmd": "pip install -e .", "commit_sha": "1c87f97dde78adc1d583b8bcc2f43502602db28e", "frozen_requirements": "frozen_requirements/infiniflow_ragflow.txt"}
{"body_lines": 7, "file_lines": 27, "has_docstring": false, "num_tests": 1}
{"status": "passed", "tests_run": 1}
repo_patch/0047
# # Copyright 2025 The InfiniFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
repo_patch/0048
mem0ai/mem0
mem0/llms/vllm.py
generate_response
VllmLLM.generate_response
method
VllmLLM
import json import os from typing import Dict, List, Optional, Union from openai import OpenAI from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.vllm import VllmConfig from mem0.llms.base import LLMBase from mem0.memory.utils import extract_json class VllmLLM(LLMBase): def __init__(self, c...
def generate_response( self, messages: List[Dict[str, str]], response_format=None, tools: Optional[List[Dict]] = None, tool_choice: str = "auto", **kwargs, ): """ Generate a response based on the given messages using vLLM. Args: me...
Generate a response based on the given messages using vLLM. Args: messages (list): List of message dicts containing 'role' and 'content'. response_format (str or object, optional): Format of the response. Defaults to "text". tools (list, optional): List of tools that the model can call. Defaults to None. ...
params = self._get_supported_params(messages=messages, **kwargs) params.update( { "model": self.config.model, "messages": messages, } ) if tools: params["tools"] = tools params["tool_choice"] = tool_choice ...
def generate_response( self, messages: List[Dict[str, str]], response_format=None, tools: Optional[List[Dict]] = None, tool_choice: str = "auto", **kwargs, ): """ Generate a response based on the given messages using vLLM. Args: ...
[{"test_file": "tests/llms/test_vllm.py", "test_function": "test_generate_response_without_tools", "test_content": "from unittest.mock import MagicMock, Mock, patch\n\nimport pytest\n\nfrom mem0 import AsyncMemory, Memory\nfrom mem0.configs.llms.base import BaseLlmConfig\nfrom mem0.llms.vllm import VllmLLM\n\n\n@pytest...
{"repo_url": "https://github.com/mem0ai/mem0", "install_cmd": "pip install -e .", "commit_sha": "a0d8a02b948271a2b369f7d65f28805189a22970", "frozen_requirements": "frozen_requirements/mem0ai_mem0.txt"}
{"body_lines": 12, "file_lines": 108, "has_docstring": true, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0048
import json import os from typing import Dict, List, Optional, Union from openai import OpenAI from mem0.configs.llms.base import BaseLlmConfig from mem0.configs.llms.vllm import VllmConfig from mem0.llms.base import LLMBase from mem0.memory.utils import extract_json class VllmLLM(LLMBase): def __init__(self, c...
repo_patch/0049
scrapy/scrapy
scrapy/core/downloader/handlers/_httpx.py
download_request
HttpxDownloadHandler.download_request
method
HttpxDownloadHandler
"""``httpx``-based HTTP(S) download handler. Currently not recommended for production use.""" from __future__ import annotations import ipaddress import logging import ssl from http.cookiejar import Cookie, CookieJar from io import BytesIO from typing import TYPE_CHECKING, Any, NoReturn, TypedDict import httpx from...
async def download_request(self, request: Request) -> Response:
self._warn_unsupported_meta(request.meta) timeout: float = request.meta.get( "download_timeout", self._DEFAULT_CONNECT_TIMEOUT ) try: async with self._get_httpx_response(request, timeout) as httpx_response: return await self._read_response(httpx_...
async def download_request(self, request: Request) -> Response: self._warn_unsupported_meta(request.meta) timeout: float = request.meta.get( "download_timeout", self._DEFAULT_CONNECT_TIMEOUT ) try: async with self._get_httpx_response(request, timeout) as htt...
[{"test_file": "tests/test_downloader_handler_httpx.py", "test_function": "TestHttp11.test_unsupported_bindaddress", "test_content": "\"\"\"Tests for scrapy.core.downloader.handlers._httpx.HttpxDownloadHandler.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any\n\nimport pytest\n\nfrom...
{"repo_url": "https://github.com/scrapy/scrapy", "install_cmd": "pip install -e .", "commit_sha": "e02ad08672a5946f659acf4874c4a315e7886346", "frozen_requirements": "frozen_requirements/scrapy_scrapy.txt"}
{"body_lines": 21, "file_lines": 270, "has_docstring": false, "num_tests": 2}
{"status": "passed", "tests_run": 2}
repo_patch/0049
"""``httpx``-based HTTP(S) download handler. Currently not recommended for production use.""" from __future__ import annotations import ipaddress import logging import ssl from http.cookiejar import Cookie, CookieJar from io import BytesIO from typing import TYPE_CHECKING, Any, NoReturn, TypedDict import httpx from...
repo_patch/0050
scrapy/scrapy
tests/utils/cmdline.py
call
call
function
null
from __future__ import annotations import subprocess import sys from typing import Any import pytest from scrapy.utils.test import get_testenv def call(*args: str, **popen_kwargs: Any) -> int:
def call(*args: str, **popen_kwargs: Any) -> int:
args = (sys.executable, "-m", "scrapy.cmdline", *args) return subprocess.call( args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=get_testenv(), **popen_kwargs, )
def call(*args: str, **popen_kwargs: Any) -> int: args = (sys.executable, "-m", "scrapy.cmdline", *args) return subprocess.call( args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=get_testenv(), **popen_kwargs, )
[{"test_file": "tests/test_command_parse.py", "test_function": "TestParseCommand.test_crawlspider_not_exists_with_not_matched_url", "test_content": "from __future__ import annotations\n\nimport argparse\nimport re\nfrom typing import TYPE_CHECKING\n\nimport pytest\n\nfrom scrapy.commands import parse\nfrom scrapy.setti...
{"repo_url": "https://github.com/scrapy/scrapy", "install_cmd": "pip install -e .", "commit_sha": "e02ad08672a5946f659acf4874c4a315e7886346", "frozen_requirements": "frozen_requirements/scrapy_scrapy.txt"}
{"body_lines": 8, "file_lines": 39, "has_docstring": false, "num_tests": 20}
{"status": "partial_pass", "note": "environment-specific test failures"}
repo_patch/0050
from __future__ import annotations import subprocess import sys from typing import Any import pytest from scrapy.utils.test import get_testenv def call(*args: str, **popen_kwargs: Any) -> int: # TODO: Implement this function def proc(*args: str, **popen_kwargs: Any) -> tuple[int, str, str]: args = (sys.e...
repo_patch/0051
scrapy/scrapy
tests/utils/cmdline.py
proc
proc
function
null
from __future__ import annotations import subprocess import sys from typing import Any import pytest from scrapy.utils.test import get_testenv def call(*args: str, **popen_kwargs: Any) -> int: args = (sys.executable, "-m", "scrapy.cmdline", *args) return subprocess.call( args, stdout=subpro...
def proc(*args: str, **popen_kwargs: Any) -> tuple[int, str, str]:
args = (sys.executable, "-m", "scrapy.cmdline", *args) try: p = subprocess.run( args, check=False, capture_output=True, encoding="utf-8", timeout=15, env=get_testenv(), **popen_kwargs, ) except subprocess.Tim...
def proc(*args: str, **popen_kwargs: Any) -> tuple[int, str, str]: args = (sys.executable, "-m", "scrapy.cmdline", *args) try: p = subprocess.run( args, check=False, capture_output=True, encoding="utf-8", timeout=15, env=get_testenv...
[{"test_file": "tests/test_command_parse.py", "test_function": "TestParseCommand.test_spider_arguments", "test_content": "from __future__ import annotations\n\nimport argparse\nimport re\nfrom typing import TYPE_CHECKING\n\nimport pytest\n\nfrom scrapy.commands import parse\nfrom scrapy.settings import Settings\nfrom t...
{"repo_url": "https://github.com/scrapy/scrapy", "install_cmd": "pip install -e .", "commit_sha": "e02ad08672a5946f659acf4874c4a315e7886346", "frozen_requirements": "frozen_requirements/scrapy_scrapy.txt"}
{"body_lines": 14, "file_lines": 39, "has_docstring": false, "num_tests": 50}
{"status": "partial_pass", "note": "environment-specific test failures"}
repo_patch/0051
from __future__ import annotations import subprocess import sys from typing import Any import pytest from scrapy.utils.test import get_testenv def call(*args: str, **popen_kwargs: Any) -> int: args = (sys.executable, "-m", "scrapy.cmdline", *args) return subprocess.call( args, stdout=subpro...
repo_patch/0052
Textualize/textual
src/textual/highlight.py
guess_language
guess_language
function
null
from __future__ import annotations import os from typing import Tuple from pygments.lexer import Lexer from pygments.lexers import get_lexer_by_name, guess_lexer_for_filename from pygments.token import Token from pygments.util import ClassNotFound from textual.content import Content, Span TokenType = Tuple[str, ......
def guess_language(code: str, path: str | None) -> str: """Guess the language based on the code and path. The result may be used in the [highlight][textual.highlight.highlight] function. Args: code: The code to guess from. path: A path to the code. Returns: The language, suitab...
Guess the language based on the code and path. The result may be used in the [highlight][textual.highlight.highlight] function. Args: code: The code to guess from. path: A path to the code. Returns: The language, suitable for use with Pygments.
if path and os.path.splitext(path)[-1] == ".tcss": # A special case for TCSS files which aren't known outside of Textual return "scss" lexer: Lexer | None = None lexer_name = "default" if code: if path: try: lexer = guess_lexer_for_filename(path, code...
def guess_language(code: str, path: str | None) -> str: """Guess the language based on the code and path. The result may be used in the [highlight][textual.highlight.highlight] function. Args: code: The code to guess from. path: A path to the code. Returns: The language, suitab...
[{"test_file": "tests/test_highlight.py", "test_function": "test_guess_language", "test_content": "import pytest\n\nfrom textual.content import Span\nfrom textual.highlight import guess_language, highlight\n\n\ndef test_highlight() -> None:\n \"\"\"Test simple application of highlight.\"\"\"\n import_this = highl...
{"repo_url": "https://github.com/Textualize/textual", "install_cmd": "pip install -e .", "commit_sha": "431dc7d32c64948d0197851654729262f8ed35be", "frozen_requirements": "frozen_requirements/Textualize_textual.txt"}
{"body_lines": 31, "file_lines": 161, "has_docstring": true, "num_tests": 1}
{"status": "validated", "tests_run": "docker"}
repo_patch/0052
from __future__ import annotations import os from typing import Tuple from pygments.lexer import Lexer from pygments.lexers import get_lexer_by_name, guess_lexer_for_filename from pygments.token import Token from pygments.util import ClassNotFound from textual.content import Content, Span TokenType = Tuple[str, ......
repo_patch/0053
Textualize/rich
rich/_unicode_data/__init__.py
load
load
function
null
from __future__ import annotations import bisect import os import sys if sys.version_info[:2] >= (3, 9): from functools import cache else: from functools import lru_cache as cache # pragma: no cover from importlib import import_module from typing import TYPE_CHECKING, cast from rich._unicode_data._versions...
def load(unicode_version: str = "auto") -> CellTable: """Load a cell table for the given unicode version. Args: unicode_version: Unicode version, or `None` to auto-detect. """
Load a cell table for the given unicode version. Args: unicode_version: Unicode version, or `None` to auto-detect.
if unicode_version == "auto": unicode_version = os.environ.get("UNICODE_VERSION", "latest") try: _parse_version(unicode_version) except ValueError: # The environment variable is invalid # Fallback to using the latest version seems reasonable un...
def load(unicode_version: str = "auto") -> CellTable: """Load a cell table for the given unicode version. Args: unicode_version: Unicode version, or `None` to auto-detect. """ if unicode_version == "auto": unicode_version = os.environ.get("UNICODE_VERSION", "latest") try: ...
[{"test_file": "tests/test_unicode_data.py", "test_function": "test_load", "test_content": "from __future__ import annotations\n\nimport pytest\n\nfrom rich._unicode_data import VERSIONS, _parse_version, load\n\n\ndef test_load():\n \"\"\"Test all versions may be loaded.\"\"\"\n for version in VERSIONS:\n ...
{"repo_url": "https://github.com/Textualize/rich", "install_cmd": "pip install -e .", "commit_sha": "fc41075a3206d2a5fd846c6f41c4d2becab814fa", "frozen_requirements": "frozen_requirements/Textualize_rich.txt"}
{"body_lines": 26, "file_lines": 94, "has_docstring": true, "num_tests": 3}
{"status": "validated", "tests_run": "docker"}
repo_patch/0053
from __future__ import annotations import bisect import os import sys if sys.version_info[:2] >= (3, 9): from functools import cache else: from functools import lru_cache as cache # pragma: no cover from importlib import import_module from typing import TYPE_CHECKING, cast from rich._unicode_data._versions...
repo_patch/0054
deepspeedai/DeepSpeed
deepspeed/runtime/precision_config.py
get_bfloat16_config
get_bfloat16_config
function
null
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from deepspeed.runtime.config_utils import DeepSpeedConfigModel from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, CONSECUTIVE_HYSTERESIS, MIN_LOSS_SCALE, ) ################...
def get_bfloat16_config(param_dict):
bf16_config_dict = param_dict.get(BFLOAT16, None) if bf16_config_dict is None: bf16_config_dict = param_dict.get(BFLOAT16_OLD, {}) return DeepSpeedBF16Config(**bf16_config_dict)
def get_bfloat16_config(param_dict): bf16_config_dict = param_dict.get(BFLOAT16, None) if bf16_config_dict is None: bf16_config_dict = param_dict.get(BFLOAT16_OLD, {}) return DeepSpeedBF16Config(**bf16_config_dict)
[{"test_file": "tests/unit/runtime/test_ds_config_dict.py", "test_function": "test_get_bfloat16_enabled", "test_content": "# Copyright (c) Microsoft Corporation.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\n# A test on its own\nimport os\nimport pytest\nimport json\nimport hjson\nimport argparse\nimpor...
{"repo_url": "https://github.com/deepspeedai/DeepSpeed", "install_cmd": "pip install -e .", "commit_sha": "a41a96b19f2b5e75567c85ff9155e4bb09c8e539", "frozen_requirements": "frozen_requirements/deepspeedai_DeepSpeed.txt"}
{"body_lines": 4, "file_lines": 157, "has_docstring": false, "num_tests": 1}
{"status": "validated", "tests_run": "docker"}
repo_patch/0054
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from deepspeed.runtime.config_utils import DeepSpeedConfigModel from .fp16.loss_scaler import ( INITIAL_LOSS_SCALE, SCALE_WINDOW, DELAYED_SHIFT, CONSECUTIVE_HYSTERESIS, MIN_LOSS_SCALE, ) ################...
repo_patch/0055
Aider-AI/aider
aider/waiting.py
main
main
function
null
#!/usr/bin/env python """ Thread-based, killable spinner utility. Use it like: from aider.waiting import WaitingSpinner spinner = WaitingSpinner("Waiting for LLM") spinner.start() ... # long task spinner.stop() """ import sys import threading import time from rich.console import Console cla...
def main():
spinner = Spinner("Running spinner...") try: for _ in range(100): time.sleep(0.15) spinner.step() print("Success!") except KeyboardInterrupt: print("\nInterrupted by user.") finally: spinner.end()
def main(): spinner = Spinner("Running spinner...") try: for _ in range(100): time.sleep(0.15) spinner.step() print("Success!") except KeyboardInterrupt: print("\nInterrupted by user.") finally: spinner.end()
[{"test_file": "tests/basic/test_deprecated.py", "test_function": "TestDeprecated.test_deprecated_args_show_warnings", "test_content": "import os\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock, patch\n\nfrom prompt_toolkit.input import DummyInput\nfrom prompt_toolkit.output import DummyOutput\n\nfr...
{"repo_url": "https://github.com/Aider-AI/aider", "install_cmd": "pip install -e .", "commit_sha": "265d8a473b5d5bf001db321b251674a120ad75da", "frozen_requirements": "frozen_requirements/Aider-AI_aider.txt"}
{"body_lines": 10, "file_lines": 222, "has_docstring": false, "num_tests": 76}
{"status": "validated", "tests_run": "docker"}
repo_patch/0055
#!/usr/bin/env python """ Thread-based, killable spinner utility. Use it like: from aider.waiting import WaitingSpinner spinner = WaitingSpinner("Waiting for LLM") spinner.start() ... # long task spinner.stop() """ import sys import threading import time from rich.console import Console cla...