{"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Domain is modified when instantiating an action with an equality predicate\n\n## Description\nWhen an action that includes an equality predicate is instantiated, the original domain is unexpectedly altered. The expected behavior is that instantiating an action should not modify the underlying domain. However, the current behavior results in the domain being changed after such an instantiation.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `f6644e1ca79c` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### pddl/logic/predicates.py\n```python\n#\n# Copyright 2021-2025 WhiteMech\n#\n# ------------------------------\n#\n# This file is part of pddl.\n#\n# Use of this source code is governed by an MIT-style\n# license that can be found in the LICENSE file or at\n# https://opensource.org/licenses/MIT.\n#\n\n\"\"\"This class implements PDDL predicates.\"\"\"\n\nimport functools\nfrom typing import Dict, Mapping, Sequence, Set\n\nfrom pddl.custom_types import name, namelike, parse_name\nfrom pddl.helpers.base import assert_, check\nfrom pddl.helpers.cache_hash import cache_hash\nfrom pddl.logic.base import Atomic, Formula\nfrom pddl.logic.terms import Term, Variable, _print_tag_set\nfrom pddl.parser.symbols import Symbols\n\n\ndef _check_terms_consistency(terms: Sequence[Term]):\n \"\"\"\n Check that the term sequence have consistent type tags.\n\n In particular, terms with the same name must have the same type tags.\n \"\"\"\n seen: Dict[name, Set[name]] = {}\n for term in terms:\n if term.name not in seen:\n seen[term.name] = set(term.type_tags)\n else:\n check(\n seen[term.name] == set(term.type_tags),\n f\"Term {term} has inconsistent type tags: \"\n f\"previous type tags {_print_tag_set(seen[term.name])}, new type tags {_print_tag_set(term.type_tags)}\",\n exception_cls=ValueError,\n )\n\n\n@cache_hash\n@functools.total_ordering\nclass Predicate(Atomic):\n \"\"\"A class for a Predicate in PDDL.\"\"\"\n\n def __init__(self, predicate_name: namelike, *terms: Term):\n \"\"\"Initialize the predicate.\"\"\"\n self._name = parse_name(predicate_name)\n self._terms = tuple(terms)\n _check_terms_consistency(self._terms)\n\n @property\n def name(self) -> str:\n \"\"\"Get the name.\"\"\"\n return self._name\n\n @property\n def terms(self) -> Sequence[Term]:\n \"\"\"Get the terms.\"\"\"\n return self._terms\n\n @property\n def arity(self) -> int:\n \"\"\"Get the arity of the predicate.\"\"\"\n return len(self.terms)\n\n def instantiate(self, mapping: Mapping[Variable, Term]) -> \"Predicate\":\n \"\"\"Instantiate the formula with a mapping from variables to terms.\"\"\"\n instantiated_terms = []\n for term in self.terms:\n if isinstance(term, Variable) and term in mapping:\n # Instantiate the variable\n instantiated_terms.append(mapping[term])\n else:\n # The predicate is already partially instantiated or mapping is a partial instantiation\n instantiated_terms.append(term)\n return Predicate(self.name, *instantiated_terms)\n\n def __call__(self, *terms: Term):\n \"\"\"Replace terms.\"\"\"\n assert_(len(terms) == self.arity, \"Number of terms not correct.\")\n return Predicate(self.name, *terms)\n\n def __str__(self) -> str:\n \"\"\"Get the string.\"\"\"\n if self.arity == 0:\n return f\"({self.name})\"\n else:\n return f\"({self.name} {' '.join(map(str, self.terms))})\"\n\n def __repr__(self) -> str:\n \"\"\"Get an unambiguous string representation.\"\"\"\n return f\"{type(self).__name__}({self.name}, {', '.join(map(str, self.terms))})\"\n\n def __eq__(self, other):\n \"\"\"Override equal operator.\"\"\"\n return (\n isinstance(other, Predicate)\n and self.name == other.name\n and self.terms == other.terms\n )\n\n def __hash__(self):\n \"\"\"Get the has of a Predicate.\"\"\"\n return hash((self.name, self.arity, self.terms))\n\n def __lt__(self, other):\n \"\"\"Compare with another object.\"\"\"\n if isinstance(other, Predicate):\n return (self.name, self.terms) < (other.name, other.terms)\n return super().__lt__(other)\n\n\nclass EqualTo(Atomic):\n \"\"\"Equality predicate.\"\"\"\n\n def __init__(self, left: Term, right: Term):\n \"\"\"\n Initialize the equality predicate.\n\n :param left: the left term.\n :param right: the right term.\n \"\"\"\n self._left = left\n self._right = right\n _check_terms_consistency([self._left, self._right])\n\n @property\n def left(self) -> Term:\n \"\"\"Get the left operand.\"\"\"\n return self._left\n\n @property\n def right(self) -> Term:\n \"\"\"Get the right operand.\"\"\"\n return self._right\n\n def instantiate(self, mapping: Mapping[Variable, Term]) -> \"EqualTo\":\n \"\"\"Instantiate the formula with a mapping from variables to terms.\"\"\"\n if isinstance(self._left, Variable) and self._left in mapping:\n self._left = mapping[self._left]\n if isinstance(self._right, Variable) and self._right in mapping:\n self._right = mapping[self._right]\n return self\n\n def __eq__(self, other) -> bool:\n \"\"\"Compare with another object.\"\"\"\n return (\n isinstance(other, EqualTo)\n and self.left == other.left\n and self.right == other.right\n )\n\n def __hash__(self) -> int:\n \"\"\"Get the hash.\"\"\"\n return hash((EqualTo, self.left, self.right))\n\n def __str__(self) -> str:\n \"\"\"Get the string representation.\"\"\"\n return f\"({Symbols.EQUAL.value} {self.left} {self.right})\"\n\n def __repr__(self) -> str:\n \"\"\"Get the string representation.\"\"\"\n return f\"{type(self).__name__}({repr(self.left)}, {repr(self.right)})\"\n\n\n@cache_hash\n@functools.total_ordering\nclass DerivedPredicate(Atomic):\n \"\"\"A class for a Derived Predicates in PDDL.\"\"\"\n\n def __init__(self, predicate: Predicate, condition: Formula) -> None:\n \"\"\"\n Initialize the derived predicate.\n\n :param predicate: the predicate\n :param condition: the condition\n \"\"\"\n self._predicate = predicate\n self._condition = condition\n\n @property\n def predicate(self) -> Predicate:\n \"\"\"Get the predicate.\"\"\"\n return self._predicate\n\n @property\n def condition(self) -> Formula:\n \"\"\"Get the condition.\"\"\"\n return self._condition\n\n def instantiate(self, mapping: Mapping[Variable, Term]) -> \"DerivedPredicate\":\n \"\"\"Instantiate the formula with a mapping from variables to terms.\"\"\"\n return DerivedPredicate(\n self.predicate.instantiate(mapping),\n self.condition.instantiate(mapping),\n )\n\n def __hash__(self) -> int:\n \"\"\"Get the hash.\"\"\"\n return hash((DerivedPredicate, self.predicate, self.condition))\n\n def __str__(self) -> str:\n \"\"\"Get the string representation.\"\"\"\n return f\"({Symbols.DERIVED.value} {self.predicate} {self.condition})\"\n\n def __repr__(self) -> str:\n \"\"\"Get the string representation.\"\"\"\n return f\"{type(self).__name__}({repr(self.predicate)}, {repr(self.condition)})\"\n\n def __eq__(self, other):\n \"\"\"Override equal operator.\"\"\"\n return (\n isinstance(other, DerivedPredicate)\n and self.predicate == other.predicate\n and self.condition == other.condition\n )\n\n def __lt__(self, other):\n \"\"\"Compare with another object.\"\"\"\n if isinstance(other, DerivedPredicate):\n return (self.predicate, self._predicate) < (\n other.predicate,\n other.condition,\n )\n return super().__lt__(other)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "AI-Planning__pddl-1806839e05b0", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/AI-Planning__pddl-1806839e05b0", "repo_key": "AI-Planning__pddl", "repo": "AI-Planning/pddl", "base_commit": "f6644e1ca79c03cfc886f23649355c0fd4b8ef56", "source_files": ["pddl/logic/predicates.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Derived predicates allow invalid definitions and mishandle type tags\n\n## Description\nWhen defining derived predicates, the system currently accepts invalid definitions and incorrectly handles type tag propagation.\n\nSpecifically:\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `9b7c1a9c4927` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### pddl/parser/domain.py\n```python\n#\n# Copyright 2021-2025 WhiteMech\n#\n# ------------------------------\n#\n# This file is part of pddl.\n#\n# Use of this source code is governed by an MIT-style\n# license that can be found in the LICENSE file or at\n# https://opensource.org/licenses/MIT.\n#\n\n\"\"\"Implementation of the PDDL domain parser.\"\"\"\nfrom typing import Any, Dict, List, Optional, Sequence, Set, Tuple\n\nfrom lark import ParseError, Transformer\n\nfrom pddl.action import Action\nfrom pddl.core import Domain\nfrom pddl.custom_types import name\nfrom pddl.exceptions import PDDLMissingRequirementError, PDDLParsingError\nfrom pddl.helpers.base import assert_\nfrom pddl.logic.base import And, ExistsCondition, ForallCondition, Imply, Not, OneOf, Or\nfrom pddl.logic.effects import Forall, When\nfrom pddl.logic.functions import Assign, Decrease, Divide\nfrom pddl.logic.functions import EqualTo as FunctionEqualTo\nfrom pddl.logic.functions import (\n FunctionExpression,\n GreaterEqualThan,\n GreaterThan,\n Increase,\n LesserEqualThan,\n LesserThan,\n Minus,\n NumericFunction,\n NumericValue,\n Plus,\n ScaleDown,\n ScaleUp,\n Times,\n)\nfrom pddl.logic.predicates import DerivedPredicate, EqualTo, Predicate\nfrom pddl.logic.terms import Constant, Variable\nfrom pddl.parser._update_type_tags import update_type_tags\nfrom pddl.parser.base import BaseParser\nfrom pddl.parser.symbols import BINARY_COMP_SYMBOLS, Symbols\nfrom pddl.parser.typed_list_parser import TypedListParser\nfrom pddl.requirements import Requirements, _extend_domain_requirements\n\n\nclass DomainTransformer(Transformer[Any, Domain]):\n \"\"\"Domain Transformer.\"\"\"\n\n def __init__(self, *args, **kwargs) -> None:\n \"\"\"Initialize the domain transformer.\"\"\"\n super().__init__(*args, **kwargs)\n\n self._constants_by_name: Dict[str, Constant] = {}\n self._predicates_by_name: Dict[str, Predicate] = {}\n self._functions_by_name: Dict[str, FunctionExpression] = {}\n self._current_parameters_by_name: Dict[str, Variable] = {}\n self._requirements: Set[Requirements] = set()\n self._extended_requirements: Set[Requirements] = set()\n\n def start(self, args):\n \"\"\"Entry point.\"\"\"\n return args[0]\n\n def domain(self, args):\n \"\"\"Process the 'domain' rule.\"\"\"\n args = [arg for arg in args if arg is not None]\n kwargs = {}\n actions = []\n derived_predicates = []\n for arg in args[2:-1]:\n if isinstance(arg, Action):\n actions.append(arg)\n elif isinstance(arg, DerivedPredicate):\n derived_predicates.append(arg)\n else:\n assert_(isinstance(arg, dict))\n kwargs.update(arg)\n kwargs.update(actions=actions, derived_predicates=derived_predicates)\n return Domain(**kwargs)\n\n def domain_def(self, args):\n \"\"\"Process the 'domain_def' rule.\"\"\"\n return dict(name=args[2])\n\n def requirements(self, args):\n \"\"\"Process the 'requirements' rule.\"\"\"\n self._requirements = {Requirements(r[1:]) for r in args[2:-1]}\n self._extended_requirements = _extend_domain_requirements(self._requirements)\n\n return dict(requirements=self._requirements)\n\n def types(self, args):\n \"\"\"Parse the 'types' rule.\"\"\"\n has_typing_requirement = self._has_requirement(Requirements.TYPING)\n types_definition = args[2]\n have_type_hierarchy = any(types_definition.values())\n if have_type_hierarchy and not has_typing_requirement:\n raise PDDLMissingRequirementError(Requirements.TYPING)\n for k in types_definition:\n if types_definition[k] == Symbols.OBJECT.value:\n types_definition[k] = None\n return dict(types=types_definition)\n\n def constants(self, args):\n \"\"\"Process the 'constant_def' rule.\"\"\"\n self._constants_by_name = {\n name: Constant(name, type_tags) for name, type_tags in args[2].items()\n }\n return dict(constants=list(self._constants_by_name.values()))\n\n def predicates(self, args):\n \"\"\"Process the 'predicates' rule.\"\"\"\n predicates = args[2:-1]\n self._predicates_by_name = {p.name: p for p in predicates}\n return dict(predicates=predicates)\n\n def functions(self, args):\n \"\"\"Process the 'functions' rule.\"\"\"\n function_definition = args[2]\n # arg[2] is a dict with NumericFunction as keys and types as values, e.g., {(fuel ?l): number, (cost): number}\n return dict(functions=function_definition)\n\n def action_def(self, args):\n \"\"\"Process the 'action_def' rule.\"\"\"\n action_name = args[2]\n variables = args[4]\n\n # process action body\n _children = args[5].children\n action_body = {\n _children[i][1:]: _children[i + 1] for i in range(0, len(_children), 2)\n }\n return Action(action_name, variables, **action_body)\n\n def derived_predicates(self, args):\n \"\"\"Process the 'derived_predicates' rule.\"\"\"\n predicate = args[2]\n condition = args[3]\n # we need to make sure the variables in the condition of the derived predicate\n # have the same type tags of the variables with the same name and scope in the predicate definition\n current_var_to_types = {}\n for term in predicate.terms:\n if isinstance(term, Variable):\n current_var_to_types[term.name] = term.type_tags\n new_condition = update_type_tags(condition, current_var_to_types)\n return DerivedPredicate(predicate, new_condition)\n\n def action_parameters(self, args):\n \"\"\"Process the 'action_parameters' rule.\"\"\"\n self._current_parameters_by_name = {\n var_name: Variable(var_name, tags) for var_name, tags in args[1]\n }\n return list(self._current_parameters_by_name.values())\n\n def emptyor_pregd(self, args):\n \"\"\"Process the 'emptyor_pregd' rule.\"\"\"\n if len(args) == 2:\n return Or()\n else:\n assert_(len(args) == 1)\n return args[0]\n\n def gd_not(self, args):\n \"\"\"Process the 'gd' not rule.\"\"\"\n if not bool(\n {Requirements.NEG_PRECONDITION, Requirements.ADL}\n & self._extended_requirements\n ):\n # raise PDDLMissingRequirementError(Requirements.NEG_PRECONDITION)\n # TODO temporary change; remove\n pass\n return Not(args[2])\n\n def gd_and(self, args):\n \"\"\"Process the 'gd_and' rule.\"\"\"\n operands = args[2:-1]\n return And(*operands)\n\n def gd_or(self, args):\n \"\"\"Process the 'gd' or rule.\"\"\"\n if not bool(\n {Requirements.DIS_PRECONDITION, Requirements.ADL}\n & self._extended_requirements\n ):\n raise PDDLMissingRequirementError(Requirements.DIS_PRECONDITION)\n operands = args[2:-1]\n return Or(*operands)\n\n def gd_imply(self, args):\n \"\"\"Process the 'gd' imply rule.\"\"\"\n if not bool(\n {Requirements.DIS_PRECONDITION, Requirements.ADL}\n & self._extended_requirements\n ):\n raise PDDLMissingRequirementError(Requirements.DIS_PRECONDITION)\n return Imply(args[2], args[3])\n\n def gd_quantifiers(self, args):\n \"\"\"Process the 'gd' quantifiers rule.\"\"\"\n req, cond_class = {\n Symbols.FORALL.value: (\n Requirements.UNIVERSAL_PRECONDITION,\n ForallCondition,\n ),\n Symbols.EXISTS.value: (\n Requirements.EXISTENTIAL_PRECONDITION,\n ExistsCondition,\n ),\n }[args[1]]\n if not bool(\n {req, Requirements.QUANTIFIED_PRECONDITION, Requirements.ADL}\n & self._extended_requirements\n ):\n raise PDDLMissingRequirementError(req)\n variables = [Variable(var_name, tags) for var_name, tags in args[3]]\n condition = args[5]\n return cond_class(cond=condition, variables=variables)\n\n def gd_comparison(self, args):\n \"\"\"Process the 'gd' comparison rule.\"\"\"\n if not bool({Requirements.NUMERIC_FLUENTS, Requirements.FLUENTS}):\n raise PDDLMissingRequirementError(Requirements.NUMERIC_FLUENTS)\n left = args[2]\n right = args[3]\n if args[1] == Symbols.GREATER_EQUAL.value:\n return GreaterEqualThan(left, right)\n elif args[1] == Symbols.GREATER.value:\n return GreaterThan(left, right)\n elif args[1] == Symbols.LESSER_EQUAL.value:\n return LesserEqualThan(left, right)\n elif args[1] == Symbols.LESSER.value:\n return LesserThan(left, right)\n elif args[1] == Symbols.EQUAL.value:\n return FunctionEqualTo(left, right)\n else:\n raise PDDLParsingError(f\"Unknown comparison operator: {args[1]}\")\n\n def gd(self, args):\n \"\"\"Process the 'gd' rule.\"\"\"\n if len(args) == 1:\n return args[0]\n elif args[1] == Symbols.NOT.value:\n return self.gd_not(args)\n elif args[1] == Symbols.AND.value:\n return self.gd_and(args)\n elif args[1] == Symbols.OR.value:\n return self.gd_or(args)\n elif args[1] == Symbols.IMPLY.value:\n return self.gd_imply(args)\n elif args[1] in [Symbols.FORALL.value, Symbols.EXISTS.value]:\n return self.gd_quantifiers(args)\n elif args[1] in BINARY_COMP_SYMBOLS:\n return self.gd_comparison(args)\n\n def num_literal(self, args):\n \"\"\"Process the 'num_literal' rule.\"\"\"\n n = args[0]\n return float(n) if \".\" in n else int(n)\n\n def emptyor_effect(self, args):\n \"\"\"Process the 'emptyor_effect' rule.\"\"\"\n if len(args) == 2:\n return Or()\n else:\n return args[0]\n\n def effect(self, args):\n \"\"\"Process the 'effect' rule.\"\"\"\n if len(args) == 1:\n return args[0]\n if args[1] == Symbols.AND.value:\n return And(*args[2:-1])\n raise ValueError(\"case not recognized\")\n\n def c_effect(self, args):\n \"\"\"Process the 'c_effect' rule.\"\"\"\n if len(args) == 1:\n return args[0]\n if args[1] == Symbols.FORALL.value:\n variables = [Variable(var_name, tags) for var_name, tags in args[3]]\n return Forall(effect=args[-2], variables=variables)\n if args[1] == Symbols.WHEN.value:\n return When(args[2], args[3])\n if args[1] == Symbols.ONEOF.value:\n if not bool({Requirements.NON_DETERMINISTIC} & self._extended_requirements):\n raise PDDLMissingRequirementError(Requirements.NON_DETERMINISTIC)\n return OneOf(*args[2:-1])\n raise ValueError()\n\n def p_effect(self, args):\n \"\"\"Process the 'p_effect' rule.\"\"\"\n if len(args) == 1:\n return args[0]\n else:\n return Not(args[2])\n\n def cond_effect(self, args):\n \"\"\"Process the 'cond_effect' rule.\"\"\"\n if len(args) >= 3 and args[1] == Symbols.AND.value:\n p_effects = args[2:-1]\n return And(*p_effects)\n assert_(len(args) == 1)\n return args[0]\n\n def num_effect(self, args):\n \"\"\"Process the 'num_effect' rule.\"\"\"\n if args[1] == Symbols.ASSIGN.value:\n return Assign(args[2], args[3])\n elif args[1] == Symbols.SCALE_UP.value:\n return ScaleUp(args[2], args[3])\n elif args[1] == Symbols.SCALE_DOWN.value:\n return ScaleDown(args[2], args[3])\n elif args[1] == Symbols.INCREASE.value:\n return Increase(args[2], args[3])\n elif args[1] == Symbols.DECREASE.value:\n return Decrease(args[2], args[3])\n else:\n raise PDDLParsingError(f\"Unrecognized assign operator: {args[1]}\")\n\n def _constant_or_variable(self, t):\n \"\"\"Get the constant or variable with the given name.\"\"\"\n # Case where the term is a free variable (bug) or comes from a parent quantifier\n if not isinstance(t, Constant) and t not in self._current_parameters_by_name:\n return Variable(str(t), {})\n return t if isinstance(t, Constant) else self._current_parameters_by_name[t]\n\n def atomic_formula_term(self, args):\n \"\"\"Process the 'atomic_formula_term' rule.\"\"\"\n if args[1] == Symbols.EQUAL.value:\n if not bool({Requirements.EQUALITY} & self._extended_requirements):\n raise PDDLMissingRequirementError(Requirements.EQUALITY)\n left = self._constant_or_variable(args[2])\n right = self._constant_or_variable(args[3])\n return EqualTo(left, right)\n else:\n predicate_name = args[1]\n terms = list(map(self._constant_or_variable, args[2:-1]))\n return Predicate(predicate_name, *terms)\n\n def constant(self, args):\n \"\"\"Process the 'constant' rule.\"\"\"\n assert_(len(args) == 1, \"Unexpected parsing error.\")\n constant = self._constants_by_name.get(args[0], None)\n if constant is None:\n raise ParseError(f\"Constant '{args[0]}' not defined.\")\n return constant\n\n def _formula_skeleton(self, args) -> Sequence[Variable]:\n \"\"\"Process the '_formula_skeleton' rule.\"\"\"\n variable_data: Tuple[Tuple[str, Set[str]], ...] = args[2]\n variables: List[Variable] = [\n Variable(var_name, tags) for var_name, tags in variable_data\n ]\n return variables\n\n def atomic_formula_skeleton(self, args):\n \"\"\"Process the 'atomic_formula_skeleton' rule.\"\"\"\n predicate_name = args[1]\n variables = self._formula_skeleton(args)\n return Predicate(predicate_name, *variables)\n\n def atomic_function_skeleton(self, args):\n \"\"\"Process the 'atomic_function_skeleton' rule.\"\"\"\n if args[1] == Symbols.TOTAL_COST.value:\n if not bool({Requirements.ACTION_COSTS}):\n raise PDDLMissingRequirementError(Requirements.ACTION_COSTS)\n return NumericFunction(\"total-cost\")\n function_name = args[1]\n variables = self._formula_skeleton(args)\n return NumericFunction(function_name, *variables)\n\n def f_exp(self, args):\n \"\"\"Process the 'f_exp' rule.\"\"\"\n if len(args) == 1:\n if not isinstance(args[0], NumericFunction):\n return NumericValue(args[0])\n return args[0]\n op = None\n if args[1] == Symbols.MINUS.value:\n op = Minus\n if args[1] == Symbols.PLUS.value:\n op = Plus\n if args[1] == Symbols.TIMES.value:\n op = Times\n if args[1] == Symbols.DIVIDE.value:\n op = Divide\n return (\n op(*args[2:-1])\n if op is not None\n else PDDLParsingError(\"Operator not recognized\")\n )\n\n def f_head(self, args):\n \"\"\"Process the 'f_head' rule.\"\"\"\n if len(args) == 1:\n return NumericFunction(args[0])\n function_name = args[1]\n variables = list(map(self._constant_or_variable, args[2:-1]))\n return NumericFunction(function_name, *variables)\n\n def typed_list_name(self, args) -> Dict[name, Optional[name]]:\n \"\"\"Process the 'typed_list_name' rule.\"\"\"\n try:\n types_index = TypedListParser.parse_typed_list(args)\n return types_index.get_typed_list_of_names()\n except ValueError as e:\n raise self._raise_typed_list_parsing_error(args, e) from e\n\n def typed_list_variable(self, args) -> Tuple[Tuple[name, Set[name]], ...]:\n \"\"\"\n Process the 'typed_list_variable' rule.\n\n Return a dictionary with as keys the terms and as value a set of types for each name.\n\n :param args: the argument of this grammar rule\n :return: a typed list (variable), i.e. a mapping from variables to the supported types\n \"\"\"\n try:\n types_index = TypedListParser.parse\n... [truncated 1780 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "AI-Planning__pddl-1b2b8dd2a2ee", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/AI-Planning__pddl-1b2b8dd2a2ee", "repo_key": "AI-Planning__pddl", "repo": "AI-Planning/pddl", "base_commit": "9b7c1a9c4927e14f15468e0ef88c8e20e13db5d2", "source_files": ["pddl/parser/domain.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Problem requirements validation incorrectly requires exact match with domain requirements\n\n## Description\nWhen defining a problem, the system currently validates its requirements by checking if they are exactly equal to the domain's requirements. This prevents users from defining problems that utilize only a subset of the available domain requirements.\n\nFor example, if a domain has requirements `[A, B, C]`, attempting to define a problem with requirements `[A, B]` fails validation. The expected behavior is for the system to accept the problem, as its requirements `[A, B]` are a valid subset of the domain's `[A, B, C]`.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `fbd6b4f40eb6` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### pddl/core.py\n```python\n#\n# Copyright 2021-2025 WhiteMech\n#\n# ------------------------------\n#\n# This file is part of pddl.\n#\n# Use of this source code is governed by an MIT-style\n# license that can be found in the LICENSE file or at\n# https://opensource.org/licenses/MIT.\n#\n\"\"\"\nCore module of the package.\n\nIt contains the class definitions to build and modify PDDL domains or problems.\n\"\"\"\n\nfrom textwrap import indent\nfrom typing import AbstractSet, Collection, Dict, List, Optional, Tuple, cast\n\nfrom pddl._validation import (\n Functions,\n TypeChecker,\n Types,\n _check_types_in_has_terms_objects,\n validate,\n)\nfrom pddl.action import Action\nfrom pddl.custom_types import name as name_type\nfrom pddl.custom_types import namelike, parse_name, to_names, to_types # noqa: F401\nfrom pddl.formatter import (\n print_constants,\n print_function_skeleton,\n print_predicates_with_types,\n print_types_or_functions_with_parents,\n remove_empty_lines,\n sort_and_print_collection,\n)\nfrom pddl.helpers.base import assert_, check, ensure, ensure_set\nfrom pddl.logic.base import And, Formula, is_literal\nfrom pddl.logic.functions import FunctionExpression, Metric, NumericFunction\nfrom pddl.logic.predicates import DerivedPredicate, Predicate\nfrom pddl.logic.terms import Constant\nfrom pddl.parser.symbols import Symbols\nfrom pddl.requirements import Requirements\n\n\nclass Domain:\n \"\"\"A class for a PDDL domain file.\"\"\"\n\n def __init__(\n self,\n name: namelike,\n requirements: Optional[Collection[\"Requirements\"]] = None,\n types: Optional[Dict[namelike, Optional[namelike]]] = None,\n constants: Optional[Collection[Constant]] = None,\n predicates: Optional[Collection[Predicate]] = None, # TODO cannot be empty\n derived_predicates: Optional[\n Collection[DerivedPredicate]\n ] = None, # TODO cannot be empty\n functions: Optional[Collection[FunctionExpression]] = None,\n actions: Optional[Collection[\"Action\"]] = None,\n ):\n \"\"\"\n Initialize a PDDL domain.\n\n :param name: the name of the domain.\n :param requirements: the requirements supported.\n :param types: the hierarchy of supported types.\n types is a dictionary mapping a type name to its ancestor.\n :param constants: the constants.\n :param predicates: the predicates.\n :param functions: the functions.\n functions is a dictionary mapping a function to its type.\n :param derived_predicates: the derived predicates.\n :param actions: the actions.\n \"\"\"\n self._name = parse_name(name)\n self._requirements = ensure_set(requirements)\n self._types = Types(types, self._requirements)\n self._constants = ensure_set(constants)\n self._predicates = ensure_set(predicates)\n self._derived_predicates = ensure_set(derived_predicates)\n self._actions = ensure_set(actions)\n self._functions = Functions(functions, self._requirements)\n\n self._check_consistency()\n\n def _check_consistency(self) -> None:\n \"\"\"Check consistency of a domain instance object.\"\"\"\n type_checker = TypeChecker(self._types, self.requirements)\n type_checker.check_type(self._constants)\n type_checker.check_type(self._predicates)\n type_checker.check_type(self._actions)\n _check_types_in_has_terms_objects(self._actions, self._types.all_types) # type: ignore\n self._check_types_in_derived_predicates()\n\n def _check_types_in_derived_predicates(self) -> None:\n \"\"\"Check types in derived predicates.\"\"\"\n dp_list = (\n [dp.predicate for dp in self._derived_predicates]\n if self._derived_predicates\n else set()\n )\n _check_types_in_has_terms_objects(dp_list, self._types.all_types)\n\n @property\n def name(self) -> name_type:\n \"\"\"Get the name.\"\"\"\n return self._name\n\n @property\n def requirements(self) -> AbstractSet[\"Requirements\"]:\n \"\"\"Get the PDDL requirements for this domain.\"\"\"\n return self._requirements\n\n @property\n def constants(self) -> AbstractSet[Constant]:\n \"\"\"Get the constants.\"\"\"\n return self._constants\n\n @property\n def predicates(self) -> AbstractSet[Predicate]:\n \"\"\"Get the predicates.\"\"\"\n return self._predicates\n\n @property\n def functions(self) -> Dict[NumericFunction, Optional[name_type]]:\n \"\"\"Get the functions.\"\"\"\n return self._functions.raw\n\n @property\n def derived_predicates(self) -> AbstractSet[DerivedPredicate]:\n \"\"\"Get the derived predicates.\"\"\"\n return self._derived_predicates\n\n @property\n def actions(self) -> AbstractSet[\"Action\"]:\n \"\"\"Get the actions.\"\"\"\n return self._actions\n\n @property\n def types(self) -> Dict[name_type, Optional[name_type]]:\n \"\"\"Get the type definitions, if defined. Else, raise error.\"\"\"\n return self._types.raw\n\n def __eq__(self, other):\n \"\"\"Compare with another object.\"\"\"\n return (\n isinstance(other, Domain)\n and self.name == other.name\n and self.requirements == other.requirements\n and self.types == other.types\n and self.constants == other.constants\n and self.predicates == other.predicates\n and self.functions == other.functions\n and self.derived_predicates == other.derived_predicates\n and self.actions == other.actions\n )\n\n def __str__(self) -> str:\n \"\"\"Print a PDDL domain object.\"\"\"\n result = f\"(define (domain {self.name})\"\n body = \"\"\n indentation = \" \" * 4\n body += sort_and_print_collection(\"(:requirements \", self.requirements, \")\\n\")\n body += print_types_or_functions_with_parents(\"(:types\", self.types, \")\\n\")\n body += print_constants(\"(:constants\", self.constants, \")\\n\")\n if self.predicates:\n body += f\"(:predicates {print_predicates_with_types(self.predicates)})\\n\"\n if self.functions:\n body += print_types_or_functions_with_parents(\n \"(:functions\", self.functions, \")\\n\", print_function_skeleton\n )\n body += sort_and_print_collection(\n \"\",\n self.derived_predicates,\n \"\",\n to_string=lambda obj: f\"({Symbols.DERIVED.value} \"\n f\"{print_predicates_with_types([obj.predicate])} \"\n f\"{obj.condition})\\n\",\n )\n body += sort_and_print_collection(\n \"\",\n self.actions,\n \"\",\n to_string=lambda obj: str(obj) + \"\\n\",\n )\n result = result + \"\\n\" + indent(body, indentation) + \"\\n)\"\n result = remove_empty_lines(result)\n return result\n\n\nclass Problem:\n \"\"\"A class for a PDDL problem file.\"\"\"\n\n def __init__(\n self,\n name: namelike,\n domain: Optional[Domain] = None,\n domain_name: Optional[namelike] = None,\n requirements: Optional[Collection[\"Requirements\"]] = None,\n objects: Optional[Collection[\"Constant\"]] = None,\n init: Optional[Collection[Formula]] = None,\n goal: Optional[Formula] = None,\n metric: Optional[Metric] = None,\n ):\n \"\"\"\n Initialize the PDDL problem.\n\n :param name: the name of the PDDL problem.\n :param domain: the PDDL domain.\n :param domain_name: the domain name. Must match with the domain object.\n :param requirements: the set of PDDL requirements.\n :param objects: the set of objects.\n :param init: the initial condition.\n :param goal: the goal condition.\n :param metric: the metric.\n \"\"\"\n self._name = parse_name(name)\n self._domain: Optional[Domain]\n self._domain_name: name_type\n self._domain, self._domain_name = self._parse_domain_and_domain_name(\n domain, domain_name\n )\n self._requirements: Optional[AbstractSet[Requirements]] = (\n self._parse_requirements(domain, requirements)\n )\n self._objects: AbstractSet[Constant] = ensure_set(objects)\n self._init: AbstractSet[Formula] = ensure_set(init)\n self._goal: Formula = ensure(goal, And())\n self._metric: Optional[Metric] = metric\n validate(\n all(map(is_literal, self.init)),\n \"Not all formulas of initial condition are literals!\",\n )\n\n self._check_consistency()\n\n def _parse_domain_and_domain_name(\n self,\n domain: Optional[Domain],\n domain_name: Optional[namelike],\n ) -> Tuple[Optional[Domain], name_type]:\n \"\"\"\n Parse the domain and domain name.\n\n If the domain is given, use it. Otherwise, take the domain from the domain name.\n \"\"\"\n if domain is not None and domain_name is not None:\n check(\n domain.name == domain_name,\n f\"got both domain and domain_name, but domain_name differs: {domain.name} != {domain_name}\",\n exception_cls=ValueError,\n )\n return domain, parse_name(domain_name)\n if domain is not None:\n return domain, domain.name\n if domain_name is not None:\n return None, parse_name(domain_name)\n raise ValueError(\"Either domain or domain_name must be given.\")\n\n def _parse_requirements(\n self,\n domain: Optional[Domain],\n requirements: Optional[Collection[Requirements]],\n ) -> Optional[AbstractSet[Requirements]]:\n \"\"\"\n Parse the requirements.\n\n If the requirements set is given, use it. Otherwise, take the requirements from the domain.\n \"\"\"\n if requirements is None:\n return None if domain is None else domain.requirements\n\n # requirements is not None\n if domain is None:\n return set(cast(Collection[Requirements], requirements))\n\n check(\n ensure_set(requirements) == domain.requirements,\n f\"got both requirements and domain, but requirements differ: {requirements} != {domain.requirements}\",\n exception_cls=ValueError,\n )\n return domain.requirements\n\n def _check_consistency(self) -> None:\n \"\"\"Check consistency of the PDDL Problem instance object.\"\"\"\n if self._domain is not None:\n self.check(self._domain)\n\n def check(self, domain: Domain) -> None:\n \"\"\"Check the problem definition against a domain definition.\"\"\"\n validate(\n self.domain_name.lower() == domain.name.lower(),\n \"Domain names don't match.\",\n )\n validate(\n self._requirements is None or self._requirements == domain.requirements,\n \"Requirements don't match.\",\n )\n types = Types(domain.types, domain.requirements, skip_checks=True) # type: ignore\n type_checker = TypeChecker(types, domain.requirements)\n type_checker.check_type(self.objects)\n type_checker.check_type(self.init)\n type_checker.check_type(self.goal)\n\n @property\n def name(self) -> name_type:\n \"\"\"Get the name.\"\"\"\n return self._name\n\n @property\n def domain(self) -> Domain:\n \"\"\"Get the domain.\"\"\"\n assert_(self._domain is not None, \"Domain is not set.\")\n return cast(Domain, self._domain)\n\n @domain.setter\n def domain(self, domain: Domain) -> None:\n \"\"\"Set the domain.\"\"\"\n self._domain_name = domain.name\n self._domain = domain\n self._check_consistency()\n\n @property\n def domain_name(self) -> name_type:\n \"\"\"Get the domain name.\"\"\"\n if self._domain is not None:\n return self._domain.name\n\n assert_(self._domain_name is not None, \"Domain name is not set.\")\n return cast(name_type, self._domain_name)\n\n @property\n def requirements(self) -> AbstractSet[\"Requirements\"]:\n \"\"\"Get the requirements.\"\"\"\n if self._domain is not None:\n return self._domain.requirements\n\n return self._requirements if self._requirements is not None else set()\n\n @property\n def objects(self) -> AbstractSet[\"Constant\"]:\n \"\"\"Get the set of objects.\"\"\"\n return self._objects\n\n @property\n def init(self) -> AbstractSet[Formula]:\n \"\"\"Get the initial state.\"\"\"\n return self._init\n\n @property\n def goal(self) -> Formula:\n \"\"\"Get the goal.\"\"\"\n return self._goal\n\n @property\n def metric(self) -> Optional[Metric]:\n \"\"\"Get the metric.\"\"\"\n return self._metric\n\n def __eq__(self, other):\n \"\"\"Compare with another object.\"\"\"\n return (\n isinstance(other, Problem)\n and self.name == other.name\n and self._domain == other._domain\n and self.domain_name == other.domain_name\n and self.requirements == other.requirements\n and self.objects == other.objects\n and self.init == other.init\n and self.goal == other.goal\n and self.metric == other.metric\n )\n\n def __str__(self) -> str:\n \"\"\"Print a PDDL problem object.\"\"\"\n result = f\"(define (problem {self.name})\"\n body = f\"(:domain {self.domain_name})\\n\"\n indentation = \" \" * 4\n body += sort_and_print_collection(\"(:requirements \", self.requirements, \")\\n\")\n if self.objects:\n body += print_constants(\"(:objects\", self.objects, \")\\n\")\n body += sort_and_print_collection(\n \"(:init \", self.init, \")\\n\", is_mandatory=True\n )\n body += f\"{'(:goal ' + str(self.goal) + ')'}\\n\"\n body += f\"{'(:metric ' + str(self.metric) + ')'}\\n\" if self.metric else \"\"\n result = result + \"\\n\" + indent(body, indentation) + \"\\n)\"\n result = remove_empty_lines(result)\n return result\n\n\nclass Plan:\n \"\"\"A class for a PDDL plan.\"\"\"\n\n def __init__(self, actions: List[Tuple[namelike, List[\"Constant\"]]]):\n \"\"\"\n Initialize the PDDL plan.\n\n :param actions: the actions of the plan.\n \"\"\"\n self._actions: list[Tuple[namelike, List[\"Constant\"]]] = actions\n\n @property\n def actions(self) -> List[Tuple[namelike, List[\"Constant\"]]]:\n \"\"\"Get the actions.\"\"\"\n return self._actions\n\n def instantiate(self, domain: Domain) -> List[Action]:\n \"\"\"Instantiate the actions in the plan.\"\"\"\n name_to_schema = {action.name: action for action in domain.actions}\n ret = []\n for action_name, parameters in self._actions:\n if action_name not in name_to_schema:\n raise ValueError(f\"Action {action_name} not found in domain.\")\n action_schema = name_to_schema[action_name]\n instantiated_action = action_schema.instantiate(parameters)\n ret.append(instantiated_action)\n return ret\n\n def check(self, domain: Domain, problem: Problem) -> None:\n \"\"\"Check the plan against a domain and a problem.\"\"\"\n name_to_schema = {action.name: action for action in domain.actions}\n domain_actions = {action.name for action in domain.actions}\n all_objects = problem.objects | domain.constants\n for action_name, parameters in self._actions:\n action = self._action_to_string(action_name, parameters)\n validate(\n action_name in domain_actions,\n f\"Action schema name of {action} not found in domain.\",\n )\n validate(\n len(parameters) == len(name_to_schema[action_name].parameters),\n f\"Number of parameters of {action} does not match with the action schema in the domain.\",\n )\n validate(\n all(param in all_objects for param in parameters),\n f\"Some parameters of {action} are not in the problem objects.\",\n )\n\n def _action_to_string(\n self, action_name: \n... [truncated 607 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "AI-Planning__pddl-c9e98703d3d9", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/AI-Planning__pddl-c9e98703d3d9", "repo_key": "AI-Planning__pddl", "repo": "AI-Planning/pddl", "base_commit": "fbd6b4f40eb644454c9dd9c4e69e4c3a6e169c7c", "source_files": ["pddl/core.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** SPARQL Update INSERT into default graph fails to create new named graph with blank node label\n\n## Description\nWhen executing a SPARQL `INSERT DATA` query that targets the default graph but contains data intended for a new named graph identified by a blank node label (e.g., `GRAPH <_:b1> { ... }`), the system does not create the expected new named graph.\n\n**Reproduction:**\n```sparql\nINSERT DATA {\n GRAPH <_:b1> {\n .\n }\n}\n```\n**Expected behavior:** A new named graph identified by a blank node (e.g., `_:b1`) is created, containing the inserted triple.\n**Actual behavior:** The new named graph is not created, and the triple is not stored in the intended\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `2796fee74cf2` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/graph.py\n```python\n\"\"\"\\\n\nRDFLib defines the following kinds of Graphs:\n\n* :class:`~rdflib.graph.Graph`\n* :class:`~rdflib.graph.QuotedGraph`\n* :class:`~rdflib.graph.ConjunctiveGraph`\n* :class:`~rdflib.graph.Dataset`\n\nGraph\n-----\n\nAn RDF graph is a set of RDF triples. Graphs support the python ``in``\noperator, as well as iteration and some operations like union,\ndifference and intersection.\n\nsee :class:`~rdflib.graph.Graph`\n\nConjunctive Graph\n-----------------\n\n.. warning::\n ConjunctiveGraph is deprecated, use :class:`~rdflib.graph.Dataset` instead.\n\nA Conjunctive Graph is the most relevant collection of graphs that are\nconsidered to be the boundary for closed world assumptions. This\nboundary is equivalent to that of the store instance (which is itself\nuniquely identified and distinct from other instances of\n:class:`~rdflib.store.Store` that signify other Conjunctive Graphs). It is\nequivalent to all the named graphs within it and associated with a\n``_default_`` graph which is automatically assigned a\n:class:`~rdflib.term.BNode` for an identifier - if one isn't given.\n\nsee :class:`~rdflib.graph.ConjunctiveGraph`\n\nQuoted graph\n------------\n\nThe notion of an RDF graph [14] is extended to include the concept of\na formula node. A formula node may occur wherever any other kind of\nnode can appear. Associated with a formula node is an RDF graph that\nis completely disjoint from all other graphs; i.e. has no nodes in\ncommon with any other graph. (It may contain the same labels as other\nRDF graphs; because this is, by definition, a separate graph,\nconsiderations of tidiness do not apply between the graph at a formula\nnode and any other graph.)\n\nThis is intended to map the idea of \"{ N3-expression }\" that is used\nby N3 into an RDF graph upon which RDF semantics is defined.\n\nsee :class:`~rdflib.graph.QuotedGraph`\n\nDataset\n-------\n\nThe RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The\nprimary term is \"graphs in the datasets\" and not \"contexts with quads\"\nso there is a separate method to set/retrieve a graph in a dataset and\nto operate with dataset graphs. As a consequence of this approach,\ndataset graphs cannot be identified with blank nodes, a name is always\nrequired (RDFLib will automatically add a name if one is not provided\nat creation time). This implementation includes a convenience method\nto directly add a single quad to a dataset graph.\n\nsee :class:`~rdflib.graph.Dataset`\n\nWorking with graphs\n===================\n\nInstantiating Graphs with default store (Memory) and default identifier\n(a BNode):\n\n >>> g = Graph()\n >>> g.store.__class__\n \n >>> g.identifier.__class__\n \n\nInstantiating Graphs with a Memory store and an identifier -\n:\n\n >>> g = Graph('Memory', URIRef(\"https://rdflib.github.io\"))\n >>> g.identifier\n rdflib.term.URIRef('https://rdflib.github.io')\n >>> str(g) # doctest: +NORMALIZE_WHITESPACE\n \" a rdfg:Graph;rdflib:storage\n [a rdflib:Store;rdfs:label 'Memory'].\"\n\nCreating a ConjunctiveGraph - The top level container for all named Graphs\nin a \"database\":\n\n >>> g = ConjunctiveGraph()\n >>> str(g.default_context)\n \"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']].\"\n\nAdding / removing reified triples to Graph and iterating over it directly or\nvia triple pattern:\n\n >>> g = Graph()\n >>> statementId = BNode()\n >>> print(len(g))\n 0\n >>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.subject,\n ... URIRef(\"https://rdflib.github.io/store/ConjunctiveGraph\"))) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.object, Literal(\"Conjunctive Graph\"))) # doctest: +ELLIPSIS\n )>\n >>> print(len(g))\n 4\n >>> for s, p, o in g:\n ... print(type(s))\n ...\n \n \n \n \n\n >>> for s, p, o in g.triples((None, RDF.object, None)):\n ... print(o)\n ...\n Conjunctive Graph\n >>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> print(len(g))\n 3\n\n``None`` terms in calls to :meth:`~rdflib.graph.Graph.triples` can be\nthought of as \"open variables\".\n\nGraph support set-theoretic operators, you can add/subtract graphs, as\nwell as intersection (with multiplication operator g1*g2) and xor (g1\n^ g2).\n\nNote that BNode IDs are kept when doing set-theoretic operations, this\nmay or may not be what you want. Two named graphs within the same\napplication probably want share BNode IDs, two graphs with data from\ndifferent sources probably not. If your BNode IDs are all generated\nby RDFLib they are UUIDs and unique.\n\n >>> g1 = Graph()\n >>> g2 = Graph()\n >>> u = URIRef(\"http://example.com/foo\")\n >>> g1.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n )>\n >>> g1.add([u, namespace.RDFS.label, Literal(\"bar\")]) # doctest: +ELLIPSIS\n )>\n >>> g2.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n )>\n >>> g2.add([u, namespace.RDFS.label, Literal(\"bing\")]) # doctest: +ELLIPSIS\n )>\n >>> len(g1 + g2) # adds bing as label\n 3\n >>> len(g1 - g2) # removes foo\n 1\n >>> len(g1 * g2) # only foo\n 1\n >>> g1 += g2 # now g1 contains everything\n\n\nGraph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within\nthe same store:\n\n >>> store = plugin.get(\"Memory\", Store)()\n >>> g1 = Graph(store)\n >>> g2 = Graph(store)\n >>> g3 = Graph(store)\n >>> stmt1 = BNode()\n >>> stmt2 = BNode()\n >>> stmt3 = BNode()\n >>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.object, Literal(\n ... 'The top-level aggregate graph - The sum ' +\n ... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS\n )>\n >>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))\n 3\n >>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(\n ... RDF.type, RDF.Statement)))\n 2\n\nConjunctiveGraphs have a :meth:`~rdflib.graph.ConjunctiveGraph.quads` method\nwhich returns quads instead of triples, where the fourth item is the Graph\n(or subclass thereof) instance in which the triple was asserted:\n\n >>> uniqueGraphNames = set(\n ... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store\n ... ).quads((None, RDF.predicate, None))])\n >>> len(uniqueGraphNames)\n 3\n >>> unionGraph = ReadOnlyGraphAggregate([g1, g2])\n >>> uniqueGraphNames = set(\n ... [graph.identifier for s, p, o, graph in unionGraph.quads(\n ... (None, RDF.predicate, None))])\n >>> len(uniqueGraphNames)\n 2\n\nParsing N3 from a string\n\n >>> g2 = Graph()\n >>> src = '''\n ... @prefix rdf: .\n ... @prefix rdfs: .\n ... [ a rdf:Statement ;\n ... rdf:subject ;\n ... rdf:predicate rdfs:label;\n ... rdf:object \"Conjunctive Graph\" ] .\n ... '''\n >>> g2 = g2.parse(data=src, format=\"n3\")\n >>> print(len(g2))\n 4\n\nUsing Namespace class:\n\n >>> RDFLib = Namespace(\"https://rdflib.github.io/\")\n >>> RDFLib.ConjunctiveGraph\n rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')\n >>> RDFLib[\"Graph\"]\n rdflib.term.URIRef('https://rdflib.github.io/Graph')\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport pathlib\nimport random\nimport warnings\nfrom io import BytesIO\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n BinaryIO,\n Callable,\n Dict,\n Generator,\n Iterable,\n List,\n Mapping,\n NoReturn,\n Optional,\n Set,\n TextIO,\n Tuple,\n Type,\n TypeVar,\n Union,\n cast,\n overload,\n)\nfrom urllib.parse import urlparse\nfrom urllib.request import url2pathname\n\nimport rdflib.exceptions as exceptions\nimport rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.\nimport rdflib.plugin as plugin\nimport rdflib.query as query\nimport rdflib.util # avoid circular dependency\nfrom rdflib.collection import Collection\nfrom rdflib.exceptions import ParserError\nfrom rdflib.namespace import RDF, Namespace, NamespaceManager\nfrom rdflib.parser import InputSource, Parser, create_input_source\nfrom rdflib.paths import Path\nfrom rdflib.resource import Resource\nfrom rdflib.serializer import Serializer\nfrom rdflib.store import Store\nfrom rdflib.term import (\n BNode,\n Genid,\n IdentifiedNode,\n Identifier,\n Literal,\n Node,\n RDFLibGenid,\n URIRef,\n)\n\nif TYPE_CHECKING:\n import typing_extensions as te\n\n import rdflib.query\n from rdflib.plugins.sparql.sparql import Query, Update\n\n_SubjectType = Node\n_PredicateType = Node\n_ObjectType = Node\n_ContextIdentifierType = IdentifiedNode\n\n_TripleType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\"]\n_QuadType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\", \"_ContextType\"]\n_OptionalQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextType\"]\n]\n_TripleOrOptionalQuadType = Union[\"_TripleType\", \"_OptionalQuadType\"]\n_OptionalIdentifiedQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextIdentifierType\"]\n]\n_TriplePatternType = Tuple[\n Optional[\"_SubjectType\"], Optional[\"_PredicateType\"], Optional[\"_ObjectType\"]\n]\n_TriplePathPatternType = Tuple[Optional[\"_SubjectType\"], Path, Optional[\"_ObjectType\"]]\n_QuadPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[\"_PredicateType\"],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_QuadPathPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Path,\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadPatternType = Union[\"_TriplePatternType\", \"_QuadPatternType\"]\n_TripleOrQuadPathPatternType = Union[\"_TriplePathPatternType\", \"_QuadPathPatternType\"]\n_TripleSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n]\n_QuadSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadSelectorType = Union[\"_TripleSelectorType\", \"_QuadSelectorType\"]\n_TriplePathType = Tuple[\"_SubjectType\", Path, \"_ObjectType\"]\n_TripleOrTriplePathType = Union[\"_TripleType\", \"_TriplePathType\"]\n_TripleChoiceType = Union[\n Tuple[List[_SubjectType], Optional[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], List[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], Optional[_PredicateType], List[_ObjectType]],\n]\n\n_GraphT = TypeVar(\"_GraphT\", bound=\"Graph\")\n_ConjunctiveGraphT = TypeVar(\"_ConjunctiveGraphT\", bound=\"ConjunctiveGraph\")\n_DatasetT = TypeVar(\"_DatasetT\", bound=\"Dataset\")\n\n# type error: Function \"Type[Literal]\" could always be true in boolean contex\nassert Literal # type: ignore[truthy-function] # avoid warning\n# type error: Function \"Type[Namespace]\" could always be true in boolean context\nassert Namespace # type: ignore[truthy-function] # avoid warning\n\nif TYPE_CHECKING:\n from rdflib._type_checking import _NamespaceSetString\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = [\n \"Graph\",\n \"ConjunctiveGraph\",\n \"QuotedGraph\",\n \"Seq\",\n \"ModificationException\",\n \"Dataset\",\n \"UnSupportedAggregateOperation\",\n \"ReadOnlyGraphAggregate\",\n \"BatchAddGraph\",\n \"_ConjunctiveGraphT\",\n \"_ContextIdentifierType\",\n \"_DatasetT\",\n \"_GraphT\",\n \"_ObjectType\",\n \"_OptionalIdentifiedQuadType\",\n \"_OptionalQuadType\",\n \"_PredicateType\",\n \"_QuadPathPatternType\",\n \"_QuadPatternType\",\n \"_QuadSelectorType\",\n \"_QuadType\",\n \"_SubjectType\",\n \"_TripleOrOptionalQuadType\",\n \"_TripleOrTriplePathType\",\n \"_TripleOrQuadPathPatternType\",\n \"_TripleOrQuadPatternType\",\n \"_TripleOrQuadSelectorType\",\n \"_TriplePathPatternType\",\n \"_TriplePathType\",\n \"_TriplePatternType\",\n \"_TripleSelectorType\",\n \"_TripleType\",\n]\n\n# : Transitive closure arg type.\n_TCArgT = TypeVar(\"_TCArgT\")\n\n\nclass Graph(Node):\n \"\"\"An RDF Graph: a Python object containing nodes and relations between them as\n RDF 'triples'.\n\n This is the central RDFLib object class and Graph objects are almost always present\n it all uses of RDFLib.\n\n The basic use is to create a Graph and iterate through or query its content, e.g.:\n\n >>> from rdflib import Graph, URIRef\n >>> g = Graph()\n\n >>> g.add((\n ... URIRef(\"http://example.com/s1\"), # subject\n ... URIRef(\"http://example.com/p1\"), # predicate\n ... URIRef(\"http://example.com/o1\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> g.add((\n ... URIRef(\"http://example.com/s2\"), # subject\n ... URIRef(\"http://example.com/p2\"), # predicate\n ... URIRef(\"http://example.com/o2\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> for triple in sorted(g): # simple looping\n ... print(triple)\n (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))\n (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))\n\n >>> # get the object of the triple with subject s1 and predicate p1\n >>> o = g.value(\n ... subject=URIRef(\"http://example.com/s1\"),\n ... predicate=URIRef(\"http://example.com/p1\")\n ... )\n\n\n The constructor a\n... [truncated 103267 chars]\n\n```\n\n### rdflib/plugins/sparql/update.py\n```python\n\"\"\"\n\nCode for carrying out Update Operations\n\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Iterator, Mapping, Optional, Sequence\n\nfrom rdflib.graph import Graph\nfrom rdflib.plugins.sparql.evaluate import evalBGP, evalPart\nfrom rdflib.plugins.sparql.evalutils import _fillTemplate, _join\nfrom rdflib.plugins.sparql.parserutils import CompValue\nfrom rdflib.plugins.sparql.sparql import FrozenDict, QueryContext, Update\nfrom rdflib.term import Identifier, URIRef, Variable\n\n\ndef _graphOrDefault(ctx: QueryContext, g: str) -> Optional[Graph]:\n if g == \"DEFAULT\":\n return ctx.graph\n else:\n return ctx.dataset.get_context(g)\n\n\ndef _graphAll(ctx: QueryContext, g: str) -> Sequence[Graph]:\n \"\"\"\n return a list of graphs\n \"\"\"\n if g == \"DEFAULT\":\n # type error: List item 0 has incompatible type \"Optional[Graph]\"; expected \"Graph\"\n return [ctx.graph] # type: ignore[list-item]\n elif g == \"NAMED\":\n return [\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"identifier\"\n c\n for c in ctx.dataset.contexts()\n if c.identifier != ctx.graph.identifier # type: ignore[union-attr]\n ]\n elif g == \"ALL\":\n return list(ctx.dataset.contexts())\n else:\n return [ctx.dataset.get_context(g)]\n\n\ndef evalLoad(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#load\n \"\"\"\n\n if TYPE_CHECKING:\n assert isinstance(u.iri, URIRef)\n\n if u.graphiri:\n ctx.load(u.iri, default=False, into=u.graphiri)\n else:\n ctx.load(u.iri, default=True)\n\n\ndef evalCreate(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#create\n \"\"\"\n g = ctx.dataset.get_context(u.graphiri)\n if len(g) > 0:\n raise Exception(\"Graph %s already exists.\" % g.identifier)\n raise Exception(\"Create not implemented!\")\n\n\ndef evalClear(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#clear\n \"\"\"\n for g in _graphAll(ctx, u.graphiri):\n g.remove((None, None, None))\n\n\ndef evalDrop(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#drop\n \"\"\"\n if ctx.dataset.store.graph_aware:\n for g in _graphAll(ctx, u.graphiri):\n ctx.dataset.store.remove_graph(g)\n else:\n evalClear(ctx, u)\n\n\ndef evalInsertData(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#insertData\n \"\"\"\n # add triples\n g = ctx.graph\n g += u.triples\n # add quads\n # u.quads is a dict of graphURI=>[triples]\n for g in u.quads:\n # type error: Argument 1 to \"get_context\" of \"ConjunctiveGraph\" has incompatible type \"Optional[Graph]\"; expected \"Union[IdentifiedNode, str, None]\"\n cg = ctx.dataset.get_context(g) # type: ignore[arg-type]\n cg += u.quads[g]\n\n\ndef evalDeleteData(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#deleteData\n \"\"\"\n # remove triples\n g = ctx.graph\n g -= u.triples\n\n # remove quads\n # u.quads is a dict of graphURI=>[triples]\n for g in u.quads:\n # type error: Argument 1 to \"get_context\" of \"ConjunctiveGraph\" has incompatible type \"Optional[Graph]\"; expected \"Union[IdentifiedNode, str, None]\"\n cg = ctx.dataset.get_context(g) # type: ignore[arg-type]\n cg -= u.quads[g]\n\n\ndef evalDeleteWhere(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#deleteWhere\n \"\"\"\n\n res: Iterator[FrozenDict] = evalBGP(ctx, u.triples)\n for g in u.quads:\n cg = ctx.dataset.get_context(g)\n c = ctx.pushGraph(cg)\n res = _join(res, list(evalBGP(c, u.quads[g])))\n\n # type error: Incompatible types in assignment (expression has type \"FrozenBindings\", variable has type \"QueryContext\")\n for c in res: # type: ignore[assignment]\n g = ctx.graph\n g -= _fillTemplate(u.triples, c)\n\n for g in u.quads:\n cg = ctx.dataset.get_context(c.get(g))\n cg -= _fillTemplate(u.quads[g], c)\n\n\ndef evalModify(ctx: QueryContext, u: CompValue) -> None:\n originalctx = ctx\n\n # Using replaces the dataset for evaluating the where-clause\n dg: Optional[Graph]\n if u.using:\n otherDefault = False\n for d in u.using:\n if d.default:\n if not otherDefault:\n # replace current default graph\n dg = Graph()\n ctx = ctx.pushGraph(dg)\n otherDefault = True\n\n ctx.load(d.default, default=True)\n\n elif d.named:\n g = d.named\n ctx.load(g, default=False)\n\n # \"The WITH clause provides a convenience for when an operation\n # primarily refers to a single graph. If a graph name is specified\n # in a WITH clause, then - for the purposes of evaluating the\n # WHERE clause - this will define an RDF Dataset containing a\n # default graph with the specified name, but only in the absence\n # of USING or USING NAMED clauses. In the presence of one or more\n # graphs referred to in USING clauses and/or USING NAMED clauses,\n # the WITH clause will be ignored while evaluating the WHERE\n # clause.\"\n if not u.using and u.withClause:\n g = ctx.dataset.get_context(u.withClause)\n ctx = ctx.pushGraph(g)\n\n res = evalPart(ctx, u.where)\n\n if u.using:\n if otherDefault:\n ctx = originalctx # restore original default graph\n if u.withClause:\n g = ctx.dataset.get_context(u.withClause)\n ctx = ctx.pushGraph(g)\n\n for c in list(res):\n dg = ctx.graph\n if u.delete:\n # type error: Unsupported left operand type for - (\"None\")\n # type error: Unsupported operand types for - (\"Graph\" and \"Generator[Tuple[Identifier, Identifier, Identifier], None, None]\")\n dg -= _fillTemplate(u.delete.triples, c) # type: ignore[operator]\n\n for g, q in u.delete.quads.items():\n cg = ctx.dataset.get_context(c.get(g))\n cg -= _fillTemplate(q, c)\n\n if u.insert:\n # type error: Unsupported left operand type for + (\"None\")\n # type error: Unsupported operand types for + (\"Graph\" and \"Generator[Tuple[Identifier, Identifier, Identifier], None, None]\")\n dg += _fillTemplate(u.insert.triples, c) # type: ignore[operator]\n\n for g, q in u.insert.quads.items():\n cg = ctx.dataset.get_context(c.get(g))\n cg += _fillTemplate(q, c)\n\n\ndef evalAdd(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n\n add all triples from src to dst\n\n http://www.w3.org/TR/sparql11-update/#add\n \"\"\"\n src, dst = u.graph\n\n srcg = _graphOrDefault(ctx, src)\n dstg = _graphOrDefault(ctx, dst)\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"identifier\"\n if srcg.identifier == dstg.identifier: # type: ignore[union-attr]\n return\n\n # type error: Unsupported left operand type for + (\"None\")\n dstg += srcg # type: ignore[operator]\n\n\ndef evalMove(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n\n remove all triples from dst\n add all triples from src to dst\n remove all triples from src\n\n http://www.w3.org/TR/sparql11-update/#move\n \"\"\"\n\n src, dst = u.graph\n\n srcg = _graphOrDefault(ctx, src)\n dstg = _graphOrDefault(ctx, dst)\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"identifier\"\n if srcg.identifier == dstg.identifier: # type: ignore[union-attr]\n return\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n dstg.remove((None, None, None)) # type: ignore[union-attr]\n\n # type error: Unsupported left operand type for + (\"None\")\n dstg += srcg # type: ignore[operator]\n\n if ctx.dataset.store.graph_aware:\n # type error: Argument 1 to \"remove_graph\" of \"Store\" has incompatible type \"Optional[Graph]\"; expected \"Graph\"\n ctx.dataset.store.remove_graph(srcg) # type: ignore[arg-type]\n else:\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n srcg.remove((None, None, None)) # type: ignore[union-attr]\n\n\ndef evalCopy(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n\n remove all triples from dst\n add all triples from src to dst\n\n http://www.w3.org/TR/sparql11-update/#copy\n \"\"\"\n\n src, dst = u.graph\n\n srcg = _graphOrDefault(ctx, src)\n dstg = _graphOrDefault(ctx, dst)\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n if srcg.identifier == dstg.identifier: # type: ignore[union-attr]\n return\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n dstg.remove((None, None, None)) # type: ignore[union-attr]\n\n # type error: Unsupported left operand type for + (\"None\")\n dstg += srcg # type: ignore[operator]\n\n\ndef evalUpdate(\n graph: Graph,\n update: Update,\n initBindings: Optional[Mapping[str, Identifier]] = None,\n) -> None:\n \"\"\"\n\n http://www.w3.org/TR/sparql11-update/#updateLanguage\n\n 'A request is a sequence of operations [...] Implementations MUST\n ensure that operations of a single request are executed in a\n fashion that guarantees the same effects as executing them in\n lexical order.\n\n Operations all result either in success or failure.\n\n If multiple operations are present in a single request, then a\n result of failure from any operation MUST abort the sequence of\n operations, causing the subsequent operations to be ignored.'\n\n This will return None on success and raise Exceptions on error\n\n .. caution::\n\n This method can access indirectly requested network endpoints, for\n example, query processing will attempt to access network endpoints\n specified in ``SERVICE`` directives.\n\n When processing untrusted or potentially malicious queries, measures\n should be taken to restrict network and file access.\n\n For information on available security measures, see the RDFLib\n :doc:`Security Considerations `\n documentation.\n\n \"\"\"\n\n for u in update.algebra:\n initBindings = dict((Variable(k), v) for k, v in (initBindings or {}).items())\n\n ctx = QueryContext(graph, initBindings=initBindings)\n ctx.prologue = u.prologue\n\n try:\n if u.name == \"Load\":\n evalLoad(ctx, u)\n elif u.name == \"Clear\":\n evalClear(ctx, u)\n elif u.name == \"Drop\":\n evalDrop(ctx, u)\n elif u.name == \"Create\":\n evalCreate(ctx, u)\n elif u.name == \"Add\":\n evalAdd(ctx, u)\n elif u.name == \"Move\":\n evalMove(ctx, u)\n elif u.name == \"Copy\":\n evalCopy(ctx, u)\n elif u.name == \"InsertData\":\n evalInsertData(ctx, u)\n elif u.name == \"DeleteData\":\n evalDeleteData(ctx, u)\n elif u.name == \"DeleteWhere\":\n evalDeleteWhere(ctx, u)\n elif u.name == \"Modify\":\n evalModify(ctx, u)\n else:\n raise Exception(\"Unknown update operation: %s\" % (u,))\n except: # noqa: E722\n if not u.silent:\n raise\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-01de9bbd3a29", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-01de9bbd3a29", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "2796fee74cf22b2debf5bff019bd0a929af8cee3", "source_files": ["rdflib/graph.py", "rdflib/plugins/sparql/update.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `Dataset.parse` returns incorrect type for subclasses\n\n## Description\nWhen invoking the `parse` class method on a subclass of `Dataset`, the returned object is incorrectly typed as the base `Dataset` class. This prevents type checkers from recognizing the specific subclass type and accessing its unique methods or attributes without explicit casting.\n\n**Expected behavior:** Calling `Subclass.parse(...)` should return an instance of `Subclass`.\n**Actual behavior:** Calling `Subclass.parse(...)` returns an instance of `Dataset`.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `1a20cd94c248` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/graph.py\n```python\n\"\"\"\\\n\nRDFLib defines the following kinds of Graphs:\n\n* :class:`~rdflib.graph.Graph`\n* :class:`~rdflib.graph.QuotedGraph`\n* :class:`~rdflib.graph.ConjunctiveGraph`\n* :class:`~rdflib.graph.Dataset`\n\nGraph\n-----\n\nAn RDF graph is a set of RDF triples. Graphs support the python ``in``\noperator, as well as iteration and some operations like union,\ndifference and intersection.\n\nsee :class:`~rdflib.graph.Graph`\n\nConjunctive Graph\n-----------------\n\n.. warning::\n ConjunctiveGraph is deprecated, use :class:`~rdflib.graph.Dataset` instead.\n\nA Conjunctive Graph is the most relevant collection of graphs that are\nconsidered to be the boundary for closed world assumptions. This\nboundary is equivalent to that of the store instance (which is itself\nuniquely identified and distinct from other instances of\n:class:`~rdflib.store.Store` that signify other Conjunctive Graphs). It is\nequivalent to all the named graphs within it and associated with a\n``_default_`` graph which is automatically assigned a\n:class:`~rdflib.term.BNode` for an identifier - if one isn't given.\n\nsee :class:`~rdflib.graph.ConjunctiveGraph`\n\nQuoted graph\n------------\n\nThe notion of an RDF graph [14] is extended to include the concept of\na formula node. A formula node may occur wherever any other kind of\nnode can appear. Associated with a formula node is an RDF graph that\nis completely disjoint from all other graphs; i.e. has no nodes in\ncommon with any other graph. (It may contain the same labels as other\nRDF graphs; because this is, by definition, a separate graph,\nconsiderations of tidiness do not apply between the graph at a formula\nnode and any other graph.)\n\nThis is intended to map the idea of \"{ N3-expression }\" that is used\nby N3 into an RDF graph upon which RDF semantics is defined.\n\nsee :class:`~rdflib.graph.QuotedGraph`\n\nDataset\n-------\n\nThe RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The\nprimary term is \"graphs in the datasets\" and not \"contexts with quads\"\nso there is a separate method to set/retrieve a graph in a dataset and\nto operate with dataset graphs. As a consequence of this approach,\ndataset graphs cannot be identified with blank nodes, a name is always\nrequired (RDFLib will automatically add a name if one is not provided\nat creation time). This implementation includes a convenience method\nto directly add a single quad to a dataset graph.\n\nsee :class:`~rdflib.graph.Dataset`\n\nWorking with graphs\n===================\n\nInstantiating Graphs with default store (Memory) and default identifier\n(a BNode):\n\n >>> g = Graph()\n >>> g.store.__class__\n \n >>> g.identifier.__class__\n \n\nInstantiating Graphs with a Memory store and an identifier -\n:\n\n >>> g = Graph('Memory', URIRef(\"https://rdflib.github.io\"))\n >>> g.identifier\n rdflib.term.URIRef('https://rdflib.github.io')\n >>> str(g) # doctest: +NORMALIZE_WHITESPACE\n \" a rdfg:Graph;rdflib:storage\n [a rdflib:Store;rdfs:label 'Memory'].\"\n\nCreating a ConjunctiveGraph - The top level container for all named Graphs\nin a \"database\":\n\n >>> g = ConjunctiveGraph()\n >>> str(g.default_context)\n \"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']].\"\n\nAdding / removing reified triples to Graph and iterating over it directly or\nvia triple pattern:\n\n >>> g = Graph()\n >>> statementId = BNode()\n >>> print(len(g))\n 0\n >>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.subject,\n ... URIRef(\"https://rdflib.github.io/store/ConjunctiveGraph\"))) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.object, Literal(\"Conjunctive Graph\"))) # doctest: +ELLIPSIS\n )>\n >>> print(len(g))\n 4\n >>> for s, p, o in g:\n ... print(type(s))\n ...\n \n \n \n \n\n >>> for s, p, o in g.triples((None, RDF.object, None)):\n ... print(o)\n ...\n Conjunctive Graph\n >>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> print(len(g))\n 3\n\n``None`` terms in calls to :meth:`~rdflib.graph.Graph.triples` can be\nthought of as \"open variables\".\n\nGraph support set-theoretic operators, you can add/subtract graphs, as\nwell as intersection (with multiplication operator g1*g2) and xor (g1\n^ g2).\n\nNote that BNode IDs are kept when doing set-theoretic operations, this\nmay or may not be what you want. Two named graphs within the same\napplication probably want share BNode IDs, two graphs with data from\ndifferent sources probably not. If your BNode IDs are all generated\nby RDFLib they are UUIDs and unique.\n\n >>> g1 = Graph()\n >>> g2 = Graph()\n >>> u = URIRef(\"http://example.com/foo\")\n >>> g1.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n )>\n >>> g1.add([u, namespace.RDFS.label, Literal(\"bar\")]) # doctest: +ELLIPSIS\n )>\n >>> g2.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n )>\n >>> g2.add([u, namespace.RDFS.label, Literal(\"bing\")]) # doctest: +ELLIPSIS\n )>\n >>> len(g1 + g2) # adds bing as label\n 3\n >>> len(g1 - g2) # removes foo\n 1\n >>> len(g1 * g2) # only foo\n 1\n >>> g1 += g2 # now g1 contains everything\n\n\nGraph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within\nthe same store:\n\n >>> store = plugin.get(\"Memory\", Store)()\n >>> g1 = Graph(store)\n >>> g2 = Graph(store)\n >>> g3 = Graph(store)\n >>> stmt1 = BNode()\n >>> stmt2 = BNode()\n >>> stmt3 = BNode()\n >>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.object, Literal(\n ... 'The top-level aggregate graph - The sum ' +\n ... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS\n )>\n >>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))\n 3\n >>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(\n ... RDF.type, RDF.Statement)))\n 2\n\nConjunctiveGraphs have a :meth:`~rdflib.graph.ConjunctiveGraph.quads` method\nwhich returns quads instead of triples, where the fourth item is the Graph\n(or subclass thereof) instance in which the triple was asserted:\n\n >>> uniqueGraphNames = set(\n ... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store\n ... ).quads((None, RDF.predicate, None))])\n >>> len(uniqueGraphNames)\n 3\n >>> unionGraph = ReadOnlyGraphAggregate([g1, g2])\n >>> uniqueGraphNames = set(\n ... [graph.identifier for s, p, o, graph in unionGraph.quads(\n ... (None, RDF.predicate, None))])\n >>> len(uniqueGraphNames)\n 2\n\nParsing N3 from a string\n\n >>> g2 = Graph()\n >>> src = '''\n ... @prefix rdf: .\n ... @prefix rdfs: .\n ... [ a rdf:Statement ;\n ... rdf:subject ;\n ... rdf:predicate rdfs:label;\n ... rdf:object \"Conjunctive Graph\" ] .\n ... '''\n >>> g2 = g2.parse(data=src, format=\"n3\")\n >>> print(len(g2))\n 4\n\nUsing Namespace class:\n\n >>> RDFLib = Namespace(\"https://rdflib.github.io/\")\n >>> RDFLib.ConjunctiveGraph\n rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')\n >>> RDFLib[\"Graph\"]\n rdflib.term.URIRef('https://rdflib.github.io/Graph')\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport pathlib\nimport random\nimport warnings\nfrom io import BytesIO\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n BinaryIO,\n Callable,\n Dict,\n Generator,\n Iterable,\n List,\n Mapping,\n NoReturn,\n Optional,\n Set,\n TextIO,\n Tuple,\n Type,\n TypeVar,\n Union,\n cast,\n overload,\n)\nfrom urllib.parse import urlparse\nfrom urllib.request import url2pathname\n\nimport rdflib.exceptions as exceptions\nimport rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.\nimport rdflib.plugin as plugin\nimport rdflib.query as query\nimport rdflib.util # avoid circular dependency\nfrom rdflib.collection import Collection\nfrom rdflib.exceptions import ParserError\nfrom rdflib.namespace import RDF, Namespace, NamespaceManager\nfrom rdflib.parser import InputSource, Parser, create_input_source\nfrom rdflib.paths import Path\nfrom rdflib.resource import Resource\nfrom rdflib.serializer import Serializer\nfrom rdflib.store import Store\nfrom rdflib.term import (\n BNode,\n Genid,\n IdentifiedNode,\n Identifier,\n Literal,\n Node,\n RDFLibGenid,\n URIRef,\n)\n\nif TYPE_CHECKING:\n import typing_extensions as te\n\n import rdflib.query\n from rdflib.plugins.sparql.sparql import Query, Update\n\n_SubjectType = Node\n_PredicateType = Node\n_ObjectType = Node\n_ContextIdentifierType = IdentifiedNode\n\n_TripleType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\"]\n_QuadType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\", \"_ContextType\"]\n_OptionalQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextType\"]\n]\n_TripleOrOptionalQuadType = Union[\"_TripleType\", \"_OptionalQuadType\"]\n_OptionalIdentifiedQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextIdentifierType\"]\n]\n_TriplePatternType = Tuple[\n Optional[\"_SubjectType\"], Optional[\"_PredicateType\"], Optional[\"_ObjectType\"]\n]\n_TriplePathPatternType = Tuple[Optional[\"_SubjectType\"], Path, Optional[\"_ObjectType\"]]\n_QuadPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[\"_PredicateType\"],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_QuadPathPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Path,\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadPatternType = Union[\"_TriplePatternType\", \"_QuadPatternType\"]\n_TripleOrQuadPathPatternType = Union[\"_TriplePathPatternType\", \"_QuadPathPatternType\"]\n_TripleSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n]\n_QuadSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadSelectorType = Union[\"_TripleSelectorType\", \"_QuadSelectorType\"]\n_TriplePathType = Tuple[\"_SubjectType\", Path, \"_ObjectType\"]\n_TripleOrTriplePathType = Union[\"_TripleType\", \"_TriplePathType\"]\n_TripleChoiceType = Union[\n Tuple[List[_SubjectType], Optional[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], List[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], Optional[_PredicateType], List[_ObjectType]],\n]\n\n_GraphT = TypeVar(\"_GraphT\", bound=\"Graph\")\n_ConjunctiveGraphT = TypeVar(\"_ConjunctiveGraphT\", bound=\"ConjunctiveGraph\")\n_DatasetT = TypeVar(\"_DatasetT\", bound=\"Dataset\")\n\n# type error: Function \"Type[Literal]\" could always be true in boolean contex\nassert Literal # type: ignore[truthy-function] # avoid warning\n# type error: Function \"Type[Namespace]\" could always be true in boolean context\nassert Namespace # type: ignore[truthy-function] # avoid warning\n\nif TYPE_CHECKING:\n from rdflib._type_checking import _NamespaceSetString\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = [\n \"Graph\",\n \"ConjunctiveGraph\",\n \"QuotedGraph\",\n \"Seq\",\n \"ModificationException\",\n \"Dataset\",\n \"UnSupportedAggregateOperation\",\n \"ReadOnlyGraphAggregate\",\n \"BatchAddGraph\",\n \"_ConjunctiveGraphT\",\n \"_ContextIdentifierType\",\n \"_DatasetT\",\n \"_GraphT\",\n \"_ObjectType\",\n \"_OptionalIdentifiedQuadType\",\n \"_OptionalQuadType\",\n \"_PredicateType\",\n \"_QuadPathPatternType\",\n \"_QuadPatternType\",\n \"_QuadSelectorType\",\n \"_QuadType\",\n \"_SubjectType\",\n \"_TripleOrOptionalQuadType\",\n \"_TripleOrTriplePathType\",\n \"_TripleOrQuadPathPatternType\",\n \"_TripleOrQuadPatternType\",\n \"_TripleOrQuadSelectorType\",\n \"_TriplePathPatternType\",\n \"_TriplePathType\",\n \"_TriplePatternType\",\n \"_TripleSelectorType\",\n \"_TripleType\",\n]\n\n# : Transitive closure arg type.\n_TCArgT = TypeVar(\"_TCArgT\")\n\n\nclass Graph(Node):\n \"\"\"An RDF Graph: a Python object containing nodes and relations between them as\n RDF 'triples'.\n\n This is the central RDFLib object class and Graph objects are almost always present\n it all uses of RDFLib.\n\n The basic use is to create a Graph and iterate through or query its content, e.g.:\n\n >>> from rdflib import Graph, URIRef\n >>> g = Graph()\n\n >>> g.add((\n ... URIRef(\"http://example.com/s1\"), # subject\n ... URIRef(\"http://example.com/p1\"), # predicate\n ... URIRef(\"http://example.com/o1\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> g.add((\n ... URIRef(\"http://example.com/s2\"), # subject\n ... URIRef(\"http://example.com/p2\"), # predicate\n ... URIRef(\"http://example.com/o2\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> for triple in sorted(g): # simple looping\n ... print(triple)\n (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))\n (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))\n\n >>> # get the object of the triple with subject s1 and predicate p1\n >>> o = g.value(\n ... subject=URIRef(\"http://example.com/s1\"),\n ... predicate=URIRef(\"http://example.com/p1\")\n ... )\n\n\n The constructor a\n... [truncated 101684 chars]\n\n```\n\n### rdflib/plugins/parsers/nquads.py\n```python\n\"\"\"\nThis is a rdflib plugin for parsing NQuad files into Conjunctive\ngraphs that can be used and queried. The store that backs the graph\n*must* be able to handle contexts.\n\n>>> from rdflib import ConjunctiveGraph, URIRef, Namespace\n>>> g = ConjunctiveGraph()\n>>> data = open(\"test/data/nquads.rdflib/example.nquads\", \"rb\")\n>>> g.parse(data, format=\"nquads\") # doctest:+ELLIPSIS\n)>\n>>> assert len(g.store) == 449\n>>> # There should be 16 separate contexts\n>>> assert len([x for x in g.store.contexts()]) == 16\n>>> # is the name of entity E10009 \"Arco Publications\"?\n>>> # (in graph http://bibliographica.org/entity/E10009)\n>>> # Looking for:\n>>> # \n>>> # \n>>> # \"Arco Publications\"\n>>> # \n>>> s = URIRef(\"http://bibliographica.org/entity/E10009\")\n>>> FOAF = Namespace(\"http://xmlns.com/foaf/0.1/\")\n>>> assert(g.value(s, FOAF.name).eq(\"Arco Publications\"))\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom codecs import getreader\nfrom typing import Any, MutableMapping, Optional\n\nfrom rdflib.exceptions import ParserError as ParseError\nfrom rdflib.graph import ConjunctiveGraph, Dataset, Graph\nfrom rdflib.parser import InputSource\n\n# Build up from the NTriples parser:\nfrom rdflib.plugins.parsers.ntriples import W3CNTriplesParser, r_tail, r_wspace\nfrom rdflib.term import BNode\n\n__all__ = [\"NQuadsParser\"]\n\n_BNodeContextType = MutableMapping[str, BNode]\n\n\nclass NQuadsParser(W3CNTriplesParser):\n\n # type error: Signature of \"parse\" incompatible with supertype \"W3CNTriplesParser\"\n def parse( # type: ignore[override]\n self,\n inputsource: InputSource,\n sink: Graph,\n bnode_context: Optional[_BNodeContextType] = None,\n skolemize: bool = False,\n **kwargs: Any,\n ):\n \"\"\"\n Parse inputsource as an N-Quads file.\n\n :type inputsource: `rdflib.parser.InputSource`\n :param inputsource: the source of N-Quads-formatted data\n :type sink: `rdflib.graph.Graph`\n :param sink: where to send parsed triples\n :type bnode_context: `dict`, optional\n :param bnode_context: a dict mapping blank node identifiers to `~rdflib.term.BNode` instances.\n See `.W3CNTriplesParser.parse`\n \"\"\"\n assert (\n sink.store.context_aware\n ), \"NQuadsParser must be given a context-aware store.\"\n # Set default_union to True to mimic ConjunctiveGraph behavior\n ds = Dataset(store=sink.store, default_union=True)\n ds_default = ds.default_context # the DEFAULT_DATASET_GRAPH_ID\n new_default_context = None\n if isinstance(sink, (Dataset, ConjunctiveGraph)):\n new_default_context = sink.default_context\n elif sink.identifier is not None:\n if sink.identifier == ds_default.identifier:\n new_default_context = sink\n else:\n new_default_context = ds.get_context(sink.identifier)\n\n if new_default_context is not None:\n ds.default_context = new_default_context\n ds.remove_graph(ds_default) # remove the original unused default graph\n # type error: Incompatible types in assignment (expression has type \"ConjunctiveGraph\", base class \"W3CNTriplesParser\" defined the type as \"Union[DummySink, NTGraphSink]\")\n self.sink: Dataset = ds # type: ignore[assignment]\n self.skolemize = skolemize\n\n source = inputsource.getCharacterStream()\n if not source:\n source = inputsource.getByteStream()\n source = getreader(\"utf-8\")(source)\n\n if not hasattr(source, \"read\"):\n raise ParseError(\"Item to parse must be a file-like object.\")\n\n self.file = source\n self.buffer = \"\"\n while True:\n self.line = __line = self.readline()\n if self.line is None:\n break\n try:\n self.parseline(bnode_context)\n except ParseError as msg:\n raise ParseError(\"Invalid line (%s):\\n%r\" % (msg, __line))\n\n return self.sink\n\n def parseline(self, bnode_context: Optional[_BNodeContextType] = None) -> None:\n self.eat(r_wspace)\n if (not self.line) or self.line.startswith(\"#\"):\n return # The line is empty or a comment\n\n subject = self.subject(bnode_context)\n self.eat(r_wspace)\n\n predicate = self.predicate()\n self.eat(r_wspace)\n\n obj = self.object(bnode_context)\n self.eat(r_wspace)\n\n context = self.uriref() or self.nodeid(bnode_context)\n self.eat(r_tail)\n\n if self.line:\n raise ParseError(\"Trailing garbage\")\n # Must have a context aware store - add on a normal Graph\n # discards anything where the ctx != graph.identifier\n if context:\n self.sink.get_context(context).add((subject, predicate, obj))\n else:\n self.sink.default_context.add((subject, predicate, obj))\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-0f3237d6765b", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-0f3237d6765b", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "1a20cd94c24816860cff6372b64ecc7f7ffd0b91", "source_files": ["rdflib/graph.py", "rdflib/plugins/parsers/nquads.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Dataset N-Quads serialization includes internal default graph identifier\n\n## Description\nWhen an RDF dataset is serialized to N-Quads format, the output incorrectly includes an internal identifier for the default graph. This identifier is an internal detail of the library and should not be present in the serialized data. The expected behavior is that the N-Quads serialization should only contain the actual data from the named graphs within the dataset, without any extraneous internal identifiers.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `32b6b88e9a26` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/serializers/nquads.py\n```python\nfrom __future__ import annotations\n\nimport warnings\nfrom typing import IO, Any, Optional\n\nfrom rdflib.graph import ConjunctiveGraph, Graph\nfrom rdflib.plugins.serializers.nt import _quoteLiteral\nfrom rdflib.serializer import Serializer\nfrom rdflib.term import Literal\n\n__all__ = [\"NQuadsSerializer\"]\n\n\nclass NQuadsSerializer(Serializer):\n def __init__(self, store: Graph):\n if not store.context_aware:\n raise Exception(\n \"NQuads serialization only makes \" \"sense for context-aware stores!\"\n )\n\n super(NQuadsSerializer, self).__init__(store)\n self.store: ConjunctiveGraph\n\n def serialize(\n self,\n stream: IO[bytes],\n base: Optional[str] = None,\n encoding: Optional[str] = None,\n **kwargs: Any,\n ) -> None:\n if base is not None:\n warnings.warn(\"NQuadsSerializer does not support base.\")\n if encoding is not None and encoding.lower() != self.encoding.lower():\n warnings.warn(\n \"NQuadsSerializer does not use custom encoding. \"\n f\"Given encoding was: {encoding}\"\n )\n encoding = self.encoding\n for context in self.store.contexts():\n for triple in context:\n stream.write(\n _nq_row(triple, context.identifier).encode(encoding, \"replace\")\n )\n stream.write(\"\\n\".encode(\"latin-1\"))\n\n\ndef _nq_row(triple, context):\n if isinstance(triple[2], Literal):\n return \"%s %s %s %s .\\n\" % (\n triple[0].n3(),\n triple[1].n3(),\n _quoteLiteral(triple[2]),\n context.n3(),\n )\n else:\n return \"%s %s %s %s .\\n\" % (\n triple[0].n3(),\n triple[1].n3(),\n triple[2].n3(),\n context.n3(),\n )\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-1a20cd94c248", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-1a20cd94c248", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "32b6b88e9a267c3b517e0a36bf49c3f77535dca9", "source_files": ["rdflib/plugins/serializers/nquads.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** SPARQL MODIFY operations do not reevaluate data between update loops\n\n## Description\nWhen executing a SPARQL MODIFY query that contains multiple update operations (e.g., a `DELETE/INSERT` followed by another `DELETE/INSERT`), changes made by an earlier update operation are not correctly reevaluated for subsequent operations within the same query. This causes later update operations to operate on stale data, leading to incorrect modifications or unexpected query results.\n\nExpected behavior: Each update operation within a SPARQL MODIFY query should see the most up-to-date state of the graph, reflecting changes made by preceding operations within the same query.\nActual behavior: Subsequent update operations within a SPARQL MODIFY query use an outdated view of the graph, ignoring changes from earlier operations in the same query.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `d5774efffab6` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/sparql/update.py\n```python\n\"\"\"\n\nCode for carrying out Update Operations\n\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Iterator, Mapping, Optional, Sequence\n\nfrom rdflib.graph import Graph\nfrom rdflib.plugins.sparql.evaluate import evalBGP, evalPart\nfrom rdflib.plugins.sparql.evalutils import _fillTemplate, _join\nfrom rdflib.plugins.sparql.parserutils import CompValue\nfrom rdflib.plugins.sparql.sparql import FrozenDict, QueryContext, Update\nfrom rdflib.term import Identifier, URIRef, Variable\n\n\ndef _graphOrDefault(ctx: QueryContext, g: str) -> Optional[Graph]:\n if g == \"DEFAULT\":\n return ctx.graph\n else:\n return ctx.dataset.get_context(g)\n\n\ndef _graphAll(ctx: QueryContext, g: str) -> Sequence[Graph]:\n \"\"\"\n return a list of graphs\n \"\"\"\n if g == \"DEFAULT\":\n # type error: List item 0 has incompatible type \"Optional[Graph]\"; expected \"Graph\"\n return [ctx.graph] # type: ignore[list-item]\n elif g == \"NAMED\":\n return [\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"identifier\"\n c\n for c in ctx.dataset.contexts()\n if c.identifier != ctx.graph.identifier # type: ignore[union-attr]\n ]\n elif g == \"ALL\":\n return list(ctx.dataset.contexts())\n else:\n return [ctx.dataset.get_context(g)]\n\n\ndef evalLoad(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#load\n \"\"\"\n\n if TYPE_CHECKING:\n assert isinstance(u.iri, URIRef)\n\n if u.graphiri:\n ctx.load(u.iri, default=False, into=u.graphiri)\n else:\n ctx.load(u.iri, default=True)\n\n\ndef evalCreate(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#create\n \"\"\"\n g = ctx.dataset.get_context(u.graphiri)\n if len(g) > 0:\n raise Exception(\"Graph %s already exists.\" % g.identifier)\n raise Exception(\"Create not implemented!\")\n\n\ndef evalClear(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#clear\n \"\"\"\n for g in _graphAll(ctx, u.graphiri):\n g.remove((None, None, None))\n\n\ndef evalDrop(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#drop\n \"\"\"\n if ctx.dataset.store.graph_aware:\n for g in _graphAll(ctx, u.graphiri):\n ctx.dataset.store.remove_graph(g)\n else:\n evalClear(ctx, u)\n\n\ndef evalInsertData(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#insertData\n \"\"\"\n # add triples\n g = ctx.graph\n g += u.triples\n # add quads\n # u.quads is a dict of graphURI=>[triples]\n for g in u.quads:\n # type error: Argument 1 to \"get_context\" of \"ConjunctiveGraph\" has incompatible type \"Optional[Graph]\"; expected \"Union[IdentifiedNode, str, None]\"\n cg = ctx.dataset.get_context(g) # type: ignore[arg-type]\n cg += u.quads[g]\n\n\ndef evalDeleteData(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#deleteData\n \"\"\"\n # remove triples\n g = ctx.graph\n g -= u.triples\n\n # remove quads\n # u.quads is a dict of graphURI=>[triples]\n for g in u.quads:\n # type error: Argument 1 to \"get_context\" of \"ConjunctiveGraph\" has incompatible type \"Optional[Graph]\"; expected \"Union[IdentifiedNode, str, None]\"\n cg = ctx.dataset.get_context(g) # type: ignore[arg-type]\n cg -= u.quads[g]\n\n\ndef evalDeleteWhere(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n http://www.w3.org/TR/sparql11-update/#deleteWhere\n \"\"\"\n\n res: Iterator[FrozenDict] = evalBGP(ctx, u.triples)\n for g in u.quads:\n cg = ctx.dataset.get_context(g)\n c = ctx.pushGraph(cg)\n res = _join(res, list(evalBGP(c, u.quads[g])))\n\n # type error: Incompatible types in assignment (expression has type \"FrozenBindings\", variable has type \"QueryContext\")\n for c in res: # type: ignore[assignment]\n g = ctx.graph\n g -= _fillTemplate(u.triples, c)\n\n for g in u.quads:\n cg = ctx.dataset.get_context(c.get(g))\n cg -= _fillTemplate(u.quads[g], c)\n\n\ndef evalModify(ctx: QueryContext, u: CompValue) -> None:\n originalctx = ctx\n\n # Using replaces the dataset for evaluating the where-clause\n dg: Optional[Graph]\n if u.using:\n otherDefault = False\n for d in u.using:\n if d.default:\n if not otherDefault:\n # replace current default graph\n dg = Graph()\n ctx = ctx.pushGraph(dg)\n otherDefault = True\n\n ctx.load(d.default, default=True)\n\n elif d.named:\n g = d.named\n ctx.load(g, default=False)\n\n # \"The WITH clause provides a convenience for when an operation\n # primarily refers to a single graph. If a graph name is specified\n # in a WITH clause, then - for the purposes of evaluating the\n # WHERE clause - this will define an RDF Dataset containing a\n # default graph with the specified name, but only in the absence\n # of USING or USING NAMED clauses. In the presence of one or more\n # graphs referred to in USING clauses and/or USING NAMED clauses,\n # the WITH clause will be ignored while evaluating the WHERE\n # clause.\"\n if not u.using and u.withClause:\n g = ctx.dataset.get_context(u.withClause)\n ctx = ctx.pushGraph(g)\n\n res = evalPart(ctx, u.where)\n\n if u.using:\n if otherDefault:\n ctx = originalctx # restore original default graph\n if u.withClause:\n g = ctx.dataset.get_context(u.withClause)\n ctx = ctx.pushGraph(g)\n\n for c in res:\n dg = ctx.graph\n if u.delete:\n # type error: Unsupported left operand type for - (\"None\")\n # type error: Unsupported operand types for - (\"Graph\" and \"Generator[Tuple[Identifier, Identifier, Identifier], None, None]\")\n dg -= _fillTemplate(u.delete.triples, c) # type: ignore[operator]\n\n for g, q in u.delete.quads.items():\n cg = ctx.dataset.get_context(c.get(g))\n cg -= _fillTemplate(q, c)\n\n if u.insert:\n # type error: Unsupported left operand type for + (\"None\")\n # type error: Unsupported operand types for + (\"Graph\" and \"Generator[Tuple[Identifier, Identifier, Identifier], None, None]\")\n dg += _fillTemplate(u.insert.triples, c) # type: ignore[operator]\n\n for g, q in u.insert.quads.items():\n cg = ctx.dataset.get_context(c.get(g))\n cg += _fillTemplate(q, c)\n\n\ndef evalAdd(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n\n add all triples from src to dst\n\n http://www.w3.org/TR/sparql11-update/#add\n \"\"\"\n src, dst = u.graph\n\n srcg = _graphOrDefault(ctx, src)\n dstg = _graphOrDefault(ctx, dst)\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"identifier\"\n if srcg.identifier == dstg.identifier: # type: ignore[union-attr]\n return\n\n # type error: Unsupported left operand type for + (\"None\")\n dstg += srcg # type: ignore[operator]\n\n\ndef evalMove(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n\n remove all triples from dst\n add all triples from src to dst\n remove all triples from src\n\n http://www.w3.org/TR/sparql11-update/#move\n \"\"\"\n\n src, dst = u.graph\n\n srcg = _graphOrDefault(ctx, src)\n dstg = _graphOrDefault(ctx, dst)\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"identifier\"\n if srcg.identifier == dstg.identifier: # type: ignore[union-attr]\n return\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n dstg.remove((None, None, None)) # type: ignore[union-attr]\n\n # type error: Unsupported left operand type for + (\"None\")\n dstg += srcg # type: ignore[operator]\n\n if ctx.dataset.store.graph_aware:\n # type error: Argument 1 to \"remove_graph\" of \"Store\" has incompatible type \"Optional[Graph]\"; expected \"Graph\"\n ctx.dataset.store.remove_graph(srcg) # type: ignore[arg-type]\n else:\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n srcg.remove((None, None, None)) # type: ignore[union-attr]\n\n\ndef evalCopy(ctx: QueryContext, u: CompValue) -> None:\n \"\"\"\n\n remove all triples from dst\n add all triples from src to dst\n\n http://www.w3.org/TR/sparql11-update/#copy\n \"\"\"\n\n src, dst = u.graph\n\n srcg = _graphOrDefault(ctx, src)\n dstg = _graphOrDefault(ctx, dst)\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n if srcg.identifier == dstg.identifier: # type: ignore[union-attr]\n return\n\n # type error: Item \"None\" of \"Optional[Graph]\" has no attribute \"remove\"\n dstg.remove((None, None, None)) # type: ignore[union-attr]\n\n # type error: Unsupported left operand type for + (\"None\")\n dstg += srcg # type: ignore[operator]\n\n\ndef evalUpdate(\n graph: Graph,\n update: Update,\n initBindings: Optional[Mapping[str, Identifier]] = None,\n) -> None:\n \"\"\"\n\n http://www.w3.org/TR/sparql11-update/#updateLanguage\n\n 'A request is a sequence of operations [...] Implementations MUST\n ensure that operations of a single request are executed in a\n fashion that guarantees the same effects as executing them in\n lexical order.\n\n Operations all result either in success or failure.\n\n If multiple operations are present in a single request, then a\n result of failure from any operation MUST abort the sequence of\n operations, causing the subsequent operations to be ignored.'\n\n This will return None on success and raise Exceptions on error\n\n .. caution::\n\n This method can access indirectly requested network endpoints, for\n example, query processing will attempt to access network endpoints\n specified in ``SERVICE`` directives.\n\n When processing untrusted or potentially malicious queries, measures\n should be taken to restrict network and file access.\n\n For information on available security measures, see the RDFLib\n :doc:`Security Considerations `\n documentation.\n\n \"\"\"\n\n for u in update.algebra:\n initBindings = dict((Variable(k), v) for k, v in (initBindings or {}).items())\n\n ctx = QueryContext(graph, initBindings=initBindings)\n ctx.prologue = u.prologue\n\n try:\n if u.name == \"Load\":\n evalLoad(ctx, u)\n elif u.name == \"Clear\":\n evalClear(ctx, u)\n elif u.name == \"Drop\":\n evalDrop(ctx, u)\n elif u.name == \"Create\":\n evalCreate(ctx, u)\n elif u.name == \"Add\":\n evalAdd(ctx, u)\n elif u.name == \"Move\":\n evalMove(ctx, u)\n elif u.name == \"Copy\":\n evalCopy(ctx, u)\n elif u.name == \"InsertData\":\n evalInsertData(ctx, u)\n elif u.name == \"DeleteData\":\n evalDeleteData(ctx, u)\n elif u.name == \"DeleteWhere\":\n evalDeleteWhere(ctx, u)\n elif u.name == \"Modify\":\n evalModify(ctx, u)\n else:\n raise Exception(\"Unknown update operation: %s\" % (u,))\n except: # noqa: E722\n if not u.silent:\n raise\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-2796fee74cf2", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-2796fee74cf2", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "d5774efffab6d28e3805a0beb740ad5c287c34aa", "source_files": ["rdflib/plugins/sparql/update.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Turtle/N3 parser incorrectly accepts local names starting with a dash\n\n## Description\nWhen parsing Turtle or N3 data, local names that begin with a dash character (`-`) are incorrectly accepted as valid. According to the PN_LOCAL production rules, a dash is not allowed as the first character of a local name.\n\n**Actual Behavior:**\nA local name like `:-o` is parsed successfully, potentially forming an invalid IRI.\n\n**Expected Behavior:**\nParsing a local name that starts with a dash, such as `:-o`, should result in a `BadSyntax` error.\n\n**Reproduction:**\n```turtle\n@prefix ex: .\nex:-o a ex:Resource .\n```\nThis input is currently parsed without error, but should raise a syntax error.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `b3f7f978e148` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/parsers/notation3.py\n```python\n\"\"\"\nnotation3.py - Standalone Notation3 Parser\nDerived from CWM, the Closed World Machine\n\nAuthors of the original suite:\n\n* Dan Connolly <@@>\n* Tim Berners-Lee <@@>\n* Yosi Scharf <@@>\n* Joseph M. Reagle Jr. \n* Rich Salz \n\nhttp://www.w3.org/2000/10/swap/notation3.py\n\nCopyright 2000-2007, World Wide Web Consortium.\nCopyright 2001, MIT.\nCopyright 2001, Zolera Systems Inc.\n\nLicense: W3C Software License\nhttp://www.w3.org/Consortium/Legal/copyright-software\n\nModified by Sean B. Palmer\nCopyright 2007, Sean B. Palmer.\n\nModified to work with rdflib by Gunnar Aastrand Grimnes\nCopyright 2010, Gunnar A. Grimnes\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport codecs\nimport os\nimport re\nimport sys\n\n# importing typing for `typing.List` because `List`` is used for something else\nimport typing\nfrom decimal import Decimal\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n Match,\n MutableSequence,\n NoReturn,\n Optional,\n Pattern,\n Set,\n Tuple,\n TypeVar,\n Union,\n)\nfrom uuid import uuid4\n\nfrom rdflib.compat import long_type\nfrom rdflib.exceptions import ParserError\nfrom rdflib.graph import Dataset, Graph, QuotedGraph\nfrom rdflib.term import (\n _XSD_PFX,\n BNode,\n IdentifiedNode,\n Identifier,\n Literal,\n Node,\n URIRef,\n Variable,\n _unique_id,\n)\n\n__all__ = [\n \"BadSyntax\",\n \"N3Parser\",\n \"TurtleParser\",\n \"splitFragP\",\n \"join\",\n \"base\",\n \"runNamespace\",\n \"uniqueURI\",\n \"hexify\",\n \"Formula\",\n \"RDFSink\",\n \"SinkParser\",\n \"sfloat\",\n]\n\nfrom rdflib.parser import Parser\n\nif TYPE_CHECKING:\n from rdflib.parser import InputSource\n\n_AnyT = TypeVar(\"_AnyT\")\n\n\ndef splitFragP(uriref: str, punc: int = 0) -> Tuple[str, str]:\n \"\"\"Split a URI reference before the fragment\n\n Punctuation is kept. e.g.\n\n ```python\n >>> splitFragP(\"abc#def\")\n ('abc', '#def')\n\n >>> splitFragP(\"abcdef\")\n ('abcdef', '')\n\n ```\n \"\"\"\n\n i = uriref.rfind(\"#\")\n if i >= 0:\n return uriref[:i], uriref[i:]\n else:\n return uriref, \"\"\n\n\n_StrT = TypeVar(\"_StrT\", bound=str)\n\n\ndef join(here: str, there: str) -> str:\n \"\"\"join an absolute URI and URI reference\n (non-ascii characters are supported/doctested;\n haven't checked the details of the IRI spec though)\n\n `here` is assumed to be absolute.\n `there` is URI reference.\n\n ```python\n >>> join('http://example/x/y/z', '../abc')\n 'http://example/x/abc'\n\n ```\n\n Raise ValueError if there uses relative path\n syntax but here has no hierarchical path.\n\n ```python\n >>> join('mid:foo@example', '../foo') # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n raise ValueError(here)\n ValueError: Base has no slash\n after colon - with relative '../foo'.\n\n >>> join('http://example/x/y/z', '')\n 'http://example/x/y/z'\n\n >>> join('mid:foo@example', '#foo')\n 'mid:foo@example#foo'\n\n ```\n\n We grok IRIs\n\n ```python\n >>> len('Andr\\\\xe9')\n 5\n\n >>> join('http://example.org/', '#Andr\\\\xe9')\n 'http://example.org/#Andr\\\\xe9'\n\n ```\n \"\"\"\n\n # assert(here.find(\"#\") < 0), \\\n # \"Base may not contain hash: '%s'\" % here # why must caller splitFrag?\n\n slashl = there.find(\"/\")\n colonl = there.find(\":\")\n\n # join(base, 'foo:/') -- absolute\n if colonl >= 0 and (slashl < 0 or colonl < slashl):\n return there\n\n bcolonl = here.find(\":\")\n assert bcolonl >= 0, (\n \"Base uri '%s' is not absolute\" % here\n ) # else it's not absolute\n\n path, frag = splitFragP(there)\n if not path:\n return here + frag\n\n # join('mid:foo@example', '../foo') bzzt\n if here[bcolonl + 1 : bcolonl + 2] != \"/\":\n raise ValueError(\n \"Base <%s> has no slash after \"\n \"colon - with relative '%s'.\" % (here, there)\n )\n\n if here[bcolonl + 1 : bcolonl + 3] == \"//\":\n bpath = here.find(\"/\", bcolonl + 3)\n else:\n bpath = bcolonl + 1\n\n # join('http://xyz', 'foo')\n if bpath < 0:\n bpath = len(here)\n here = here + \"/\"\n\n # join('http://xyz/', '//abc') => 'http://abc'\n if there[:2] == \"//\":\n return here[: bcolonl + 1] + there\n\n # join('http://xyz/', '/abc') => 'http://xyz/abc'\n if there[:1] == \"/\":\n return here[:bpath] + there\n\n slashr = here.rfind(\"/\")\n\n while 1:\n if path[:2] == \"./\":\n path = path[2:]\n if path == \".\":\n path = \"\"\n elif path[:3] == \"../\" or path == \"..\":\n path = path[3:]\n i = here.rfind(\"/\", bpath, slashr)\n if i >= 0:\n here = here[: i + 1]\n slashr = i\n else:\n break\n\n return here[: slashr + 1] + path + frag\n\n\ndef base() -> str:\n \"\"\"The base URI for this process - the Web equiv of cwd\n\n Relative or absolute unix-standard filenames parsed relative to\n this yield the URI of the file.\n If we had a reliable way of getting a computer name,\n we should put it in the hostname just to prevent ambiguity\n \"\"\"\n # return \"file://\" + hostname + os.getcwd() + \"/\"\n return \"file://\" + _fixslash(os.getcwd()) + \"/\"\n\n\ndef _fixslash(s: str) -> str:\n \"\"\"Fix windowslike filename to unixlike - (#ifdef WINDOWS)\"\"\"\n s = s.replace(\"\\\\\", \"/\")\n if s[0] != \"/\" and s[1] == \":\":\n s = s[2:] # @@@ Hack when drive letter present\n return s\n\n\nCONTEXT = 0\nPRED = 1\nSUBJ = 2\nOBJ = 3\n\nPARTS = PRED, SUBJ, OBJ\nALL4 = CONTEXT, PRED, SUBJ, OBJ\n\nSYMBOL = 0\nFORMULA = 1\nLITERAL = 2\nLITERAL_DT = 21\nLITERAL_LANG = 22\nANONYMOUS = 3\nXMLLITERAL = 25\n\nLogic_NS = \"http://www.w3.org/2000/10/swap/log#\"\nNODE_MERGE_URI = Logic_NS + \"is\" # Pseudo-property indicating node merging\nforSomeSym = Logic_NS + \"forSome\"\nforAllSym = Logic_NS + \"forAll\"\n\nRDF_type_URI = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\"\nRDF_NS_URI = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\nOWL_NS = \"http://www.w3.org/2002/07/owl#\"\nDAML_sameAs_URI = OWL_NS + \"sameAs\"\nparsesTo_URI = Logic_NS + \"parsesTo\"\nRDF_spec = \"http://www.w3.org/TR/REC-rdf-syntax/\"\n\nList_NS = RDF_NS_URI # From 20030808\n_Old_Logic_NS = \"http://www.w3.org/2000/10/swap/log.n3#\"\n\nN3_first = (SYMBOL, List_NS + \"first\")\nN3_rest = (SYMBOL, List_NS + \"rest\")\nN3_li = (SYMBOL, List_NS + \"li\")\nN3_nil = (SYMBOL, List_NS + \"nil\")\nN3_List = (SYMBOL, List_NS + \"List\")\nN3_Empty = (SYMBOL, List_NS + \"Empty\")\n\n\nrunNamespaceValue: Optional[str] = None\n\n\ndef runNamespace() -> str:\n \"\"\"Returns a URI suitable as a namespace for run-local objects\"\"\"\n # @@@ include hostname (privacy?) (hash it?)\n global runNamespaceValue\n if runNamespaceValue is None:\n runNamespaceValue = join(base(), _unique_id()) + \"#\"\n return runNamespaceValue\n\n\nnextu = 0\n\n\ndef uniqueURI() -> str:\n \"\"\"A unique URI\"\"\"\n global nextu\n nextu += 1\n return runNamespace() + \"u_\" + str(nextu)\n\n\ntracking = False\nchatty_flag = 50\n\n# from why import BecauseOfData, becauseSubexpression\n\n\ndef BecauseOfData(*args: Any, **kargs: Any) -> None:\n # print args, kargs\n pass\n\n\ndef becauseSubexpression(*args: Any, **kargs: Any) -> None:\n # print args, kargs\n pass\n\n\nN3_forSome_URI = forSomeSym\nN3_forAll_URI = forAllSym\n\n# Magic resources we know about\n\nADDED_HASH = \"#\" # Stop where we use this in case we want to remove it!\n# This is the hash on namespace URIs\n\nRDF_type = (SYMBOL, RDF_type_URI)\nDAML_sameAs = (SYMBOL, DAML_sameAs_URI)\n\nLOG_implies_URI = \"http://www.w3.org/2000/10/swap/log#implies\"\n\nBOOLEAN_DATATYPE = _XSD_PFX + \"boolean\"\nDECIMAL_DATATYPE = _XSD_PFX + \"decimal\"\nDOUBLE_DATATYPE = _XSD_PFX + \"double\"\nFLOAT_DATATYPE = _XSD_PFX + \"float\"\nINTEGER_DATATYPE = _XSD_PFX + \"integer\"\n\noption_noregen = 0 # If set, do not regenerate genids on output\n\n# @@ I18n - the notname chars need extending for well known unicode non-text\n# characters. The XML spec switched to assuming unknown things were name\n# characters.\n# _namechars = string.lowercase + string.uppercase + string.digits + '_-'\n_notQNameChars = set(\"\\t\\r\\n !\\\"#$&'()*,+/;<=>?@[\\\\]^`{|}~\") # else valid qname :-/\n_notKeywordsChars = _notQNameChars | {\".\"}\n_notNameChars = _notQNameChars | {\":\"} # Assume anything else valid name :-/\n_rdfns = \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\nhexChars = set(\"ABCDEFabcdef0123456789\")\nescapeChars = set(\"(_~.-!$&'()*+,;=/?#@%)\") # valid for \\ escapes in localnames\nnumberChars = set(\"0123456789-\")\nnumberCharsPlus = numberChars | {\"+\", \".\"}\n\n\ndef unicodeExpand(m: Match) -> str:\n try:\n return chr(int(m.group(1), 16))\n except Exception:\n raise Exception(\"Invalid unicode code point: \" + m.group(1))\n\n\nunicodeEscape4 = re.compile(r\"\\\\u([0-9a-fA-F]{4})\")\nunicodeEscape8 = re.compile(r\"\\\\U([0-9a-fA-F]{8})\")\n\n\nN3CommentCharacter = \"#\" # For unix script # ! compatibility\n\n# Parse string to sink\n#\n# Regular expressions:\neol = re.compile(r\"[ \\t]*(#[^\\n]*)?\\r?\\n\") # end of line, poss. w/comment\neof = re.compile(r\"[ \\t]*(#[^\\n]*)?$\") # end of file, poss. w/comment\nws = re.compile(r\"[ \\t]*\") # Whitespace not including NL\nsigned_integer = re.compile(r\"[-+]?[0-9]+\") # integer\ninteger_syntax = re.compile(r\"[-+]?[0-9]+\")\ndecimal_syntax = re.compile(r\"[-+]?[0-9]*\\.[0-9]+\")\nexponent_syntax = re.compile(\n r\"[-+]?(?:[0-9]+\\.[0-9]*|\\.[0-9]+|[0-9]+)(?:e|E)[-+]?[0-9]+\"\n)\ndigitstring = re.compile(r\"[0-9]+\") # Unsigned integer\ninteresting = re.compile(r\"\"\"[\\\\\\r\\n\\\"\\']\"\"\")\nlangcode = re.compile(r\"[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\")\n\n\nclass sfloat(str): # noqa: N801\n \"\"\"don't normalize raw XSD.double string representation\"\"\"\n\n\nclass SinkParser:\n def __init__(\n self,\n store: RDFSink,\n openFormula: Optional[Formula] = None,\n thisDoc: str = \"\",\n baseURI: Optional[str] = None,\n genPrefix: str = \"\",\n why: Optional[Callable[[], None]] = None,\n turtle: bool = False,\n ):\n \"\"\"note: namespace names should *not* end in # ;\n the # will get added during qname processing\"\"\"\n\n self._bindings = {}\n if thisDoc != \"\":\n assert \":\" in thisDoc, \"Document URI not absolute: <%s>\" % thisDoc\n self._bindings[\"\"] = thisDoc + \"#\" # default\n\n self._store = store\n if genPrefix:\n # TODO FIXME: there is no function named setGenPrefix\n store.setGenPrefix(genPrefix) # type: ignore[attr-defined] # pass it on\n\n self._thisDoc = thisDoc\n self.lines = 0 # for error handling\n self.startOfLine = 0 # For calculating character number\n self._genPrefix = genPrefix\n self.keywords = [\"a\", \"this\", \"bind\", \"has\", \"is\", \"of\", \"true\", \"false\"]\n self.keywordsSet = 0 # Then only can others be considered qnames\n self._anonymousNodes: Dict[str, BNode] = {}\n # Dict of anon nodes already declared ln: Term\n self._variables: Dict[str, Variable] = {}\n self._parentVariables: Dict[str, Variable] = {}\n self._reason = why # Why the parser was asked to parse this\n\n self.turtle = turtle # raise exception when encountering N3 extensions\n # Turtle allows single or double quotes around strings, whereas N3\n # only allows double quotes.\n self.string_delimiters = ('\"', \"'\") if turtle else ('\"',)\n\n self._reason2: Optional[Callable[..., None]] = None # Why these triples\n # was: diag.tracking\n if tracking:\n # type error: \"BecauseOfData\" does not return a value\n self._reason2 = BecauseOfData( # type: ignore[func-returns-value]\n store.newSymbol(thisDoc), because=self._reason\n )\n\n self._baseURI: Optional[str]\n if baseURI:\n self._baseURI = baseURI\n else:\n if thisDoc:\n self._baseURI = thisDoc\n else:\n self._baseURI = None\n\n assert not self._baseURI or \":\" in self._baseURI\n\n if not self._genPrefix:\n if self._thisDoc:\n self._genPrefix = self._thisDoc + \"#_g\"\n else:\n self._genPrefix = uniqueURI()\n\n self._formula: Optional[Formula]\n if openFormula is None and not turtle:\n if self._thisDoc:\n # TODO FIXME: store.newFormula does not take any arguments\n self._formula = store.newFormula(thisDoc + \"#_formula\") # type: ignore[call-arg]\n else:\n self._formula = store.newFormula()\n else:\n self._formula = openFormula\n\n self._context: Optional[Formula] = self._formula\n self._parentContext: Optional[Formula] = None\n\n def here(self, i: int) -> str:\n \"\"\"String generated from position in file\n\n This is for repeatability when referring people to bnodes in a document.\n This has diagnostic uses less formally, as it should point one to which\n bnode the arbitrary identifier actually is. It gives the\n line and character number of the '[' charcacter or path character\n which introduced the blank node. The first blank node is boringly\n _L1C1. It used to be used only for tracking, but for tests in general\n it makes the canonical ordering of bnodes repeatable.\"\"\"\n\n return \"%s_L%iC%i\" % (self._genPrefix, self.lines, i - self.startOfLine + 1)\n\n def formula(self) -> Optional[Formula]:\n return self._formula\n\n def loadStream(self, stream: Union[IO[str], IO[bytes]]) -> Optional[Formula]:\n return self.loadBuf(stream.read()) # Not ideal\n\n def loadBuf(self, buf: Union[str, bytes]) -> Optional[Formula]:\n \"\"\"Parses a buffer and returns its top level formula\"\"\"\n self.startDoc()\n\n self.feed(buf)\n return self.endDoc() # self._formula\n\n def feed(self, octets: Union[str, bytes]) -> None:\n \"\"\"Feed an octet stream to the parser\n\n if BadSyntax is raised, the string\n passed in the exception object is the\n remainder after any statements have been parsed.\n So if there is more data to feed to the\n parser, it should be straightforward to recover.\"\"\"\n\n if not isinstance(octets, str):\n s = octets.decode(\"utf-8\")\n # NB already decoded, so \\ufeff\n if len(s) > 0 and s[0] == codecs.BOM_UTF8.decode(\"utf-8\"):\n s = s[1:]\n else:\n s = octets\n\n i = 0\n while i >= 0:\n j = self.skipSpace(s, i)\n if j < 0:\n return\n\n i = self.directiveOrStatement(s, j)\n if i < 0:\n # print(\"# next char: %s\" % s[j])\n self.BadSyntax(s, j, \"expected directive or statement\")\n\n def directiveOrStatement(self, argstr: str, h: int) -> int:\n i = self.skipSpace(argstr, h)\n if i < 0:\n return i # EOF\n\n if self.turtle:\n j = self.sparqlDirective(argstr, i)\n if j >= 0:\n return j\n\n j = self.directive(argstr, i)\n if j >= 0:\n return self.checkDot(argstr, j)\n\n j = self.statement(argstr, i)\n if j >= 0:\n return self.checkDot(argstr, j)\n\n return j\n\n # @@I18N\n # _namechars = string.lowercase + string.uppercase + string.digits + '_-'\n\n def tok(self, tok: str, argstr: str, i: int, colon: bool = False) -> int:\n \"\"\"Check for keyword. Space must have been stripped on entry and\n we must not be at end of file.\n\n if colon, then keyword followed by colon is ok\n (`@prefix:` is ok, rdf:type shortcut a must be followed by ws)\n \"\"\"\n\n assert tok[0] not in _notNameChars # not for punctuation\n if argstr[i] == \"@\":\n i += 1\n else:\n if tok not in self.keywords:\n return -1 # No, this has neither keywords declaration nor \"@\"\n\n i_plus_len_tok = i + len(tok)\n if (\n argstr[i:i_plus_len_tok] == tok\n and (\n... [truncated 51727 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-282240b90b7d", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-282240b90b7d", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "b3f7f978e148c13bf6cfdc7359e99da130eacc36", "source_files": ["rdflib/plugins/parsers/notation3.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `pyparsing` Deprecation Warnings During Execution\n\n## Description\nWhen running the application, `pyparsing` deprecation warnings are frequently observed in the console output or logs. This indicates that certain methods from the `pyparsing` library are being used that are no longer recommended and may be removed in future versions.\n\n**Expected behavior:** The application should execute without generating any `pyparsing` deprecation warnings.\n**Actual behavior:** Deprecation warnings related to `pyparsing` methods are printed during normal operation.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `6539dfef42c5` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/sparql/parser.py\n```python\n\"\"\"\nSPARQL 1.1 Parser\n\nbased on pyparsing\n\"\"\"\n\nfrom __future__ import annotations # noqa: I001\n\nimport re\nimport sys\nfrom typing import Any, BinaryIO, List\nfrom typing import Optional as OptionalType\nfrom typing import TextIO, Tuple, Union\n\nfrom pyparsing import CaselessKeyword as Keyword # watch out :)\nfrom pyparsing import (\n Combine,\n Forward,\n Group,\n Literal,\n OneOrMore,\n Optional,\n ParseResults,\n Regex,\n Suppress,\n ZeroOrMore,\n delimitedList,\n restOfLine,\n)\n\nimport rdflib\nfrom rdflib.compat import decodeUnicodeEscape\n\nfrom . import operators as op\nfrom .parserutils import Comp, CompValue, Param, ParamList\n\n# from pyparsing import Keyword as CaseSensitiveKeyword\n\n\nDEBUG = False\n\n# ---------------- ACTIONS\n\n\ndef neg(literal: rdflib.Literal) -> rdflib.Literal:\n return rdflib.Literal(-literal, datatype=literal.datatype)\n\n\ndef setLanguage(terms: Tuple[Any, OptionalType[str]]) -> rdflib.Literal:\n return rdflib.Literal(terms[0], lang=terms[1])\n\n\ndef setDataType(terms: Tuple[Any, OptionalType[str]]) -> rdflib.Literal:\n return rdflib.Literal(terms[0], datatype=terms[1])\n\n\ndef expandTriples(terms: ParseResults) -> List[Any]:\n \"\"\"\n Expand ; and , syntax for repeat predicates, subjects\n \"\"\"\n # import pdb; pdb.set_trace()\n last_subject, last_predicate = None, None # Used for ; and ,\n try:\n res: List[Any] = []\n if DEBUG:\n print(\"Terms\", terms)\n l_ = len(terms)\n for i, t in enumerate(terms):\n if t == \",\":\n res.extend([last_subject, last_predicate])\n elif t == \";\":\n if i + 1 == len(terms) or terms[i + 1] == \";\" or terms[i + 1] == \".\":\n continue # this semicolon is spurious\n res.append(last_subject)\n elif isinstance(t, list):\n # BlankNodePropertyList\n # is this bnode the object of previous triples?\n if (len(res) % 3) == 2:\n res.append(t[0])\n # is this a single [] ?\n if len(t) > 1:\n res += t # Don't update last_subject/last_predicate\n # is this bnode the subject of more triples?\n if i + 1 < l_ and terms[i + 1] not in [\n \".\",\n \",\",\n \";\",\n ]: # term might not be a string\n last_subject, last_predicate = t[0], None\n res.append(t[0])\n elif isinstance(t, ParseResults):\n res += t.asList()\n elif t != \".\":\n res.append(t)\n if (len(res) % 3) == 1:\n last_subject = t\n elif (len(res) % 3) == 2:\n last_predicate = t\n if DEBUG:\n print(len(res), t)\n if DEBUG:\n import json\n\n print(json.dumps(res, indent=2))\n\n return res\n # print res\n # assert len(res)%3 == 0, \\\n # \"Length of triple-list is not divisible by 3: %d!\"%len(res)\n\n # return [tuple(res[i:i+3]) for i in range(len(res)/3)]\n except:\n if DEBUG:\n import traceback\n\n traceback.print_exc()\n raise\n\n\ndef expandBNodeTriples(terms: ParseResults) -> List[Any]:\n \"\"\"\n expand [ ?p ?o ] syntax for implicit bnodes\n \"\"\"\n # import pdb; pdb.set_trace()\n try:\n if DEBUG:\n print(\"Bnode terms\", terms)\n print(\"1\", terms[0])\n print(\"2\", [rdflib.BNode()] + terms.asList()[0])\n return [expandTriples([rdflib.BNode()] + terms.asList()[0])]\n except Exception as e:\n if DEBUG:\n print(\">>>>>>>>\", e)\n raise\n\n\ndef expandCollection(terms: ParseResults) -> List[List[Any]]:\n \"\"\"\n expand ( 1 2 3 ) notation for collections\n \"\"\"\n if DEBUG:\n print(\"Collection: \", terms)\n\n res: List[Any] = []\n other = []\n for x in terms:\n if isinstance(x, list): # is this a [ .. ] ?\n other += x\n x = x[0]\n\n b = rdflib.BNode()\n if res:\n res += [res[-3], rdflib.RDF.rest, b, b, rdflib.RDF.first, x]\n else:\n res += [b, rdflib.RDF.first, x]\n res += [b, rdflib.RDF.rest, rdflib.RDF.nil]\n\n res += other\n\n if DEBUG:\n print(\"CollectionOut\", res)\n return [res]\n\n\n# SPARQL Grammar from http://www.w3.org/TR/sparql11-query/#grammar\n# ------ TERMINALS --------------\n# [139] IRIREF ::= '<' ([^<>\"{}|^`\\]-[#x00-#x20])* '>'\nIRIREF = Combine(\n Suppress(\"<\")\n + Regex(r'[^<>\"{}|^`\\\\%s]*' % \"\".join(\"\\\\x%02X\" % i for i in range(33)))\n + Suppress(\">\")\n)\nIRIREF.setParseAction(lambda x: rdflib.URIRef(x[0]))\n\n# [164] P_CHARS_BASE ::= [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]\n\nif sys.maxunicode == 0xFFFF:\n # this is narrow python build (default on windows/osx)\n # this means that unicode code points over 0xffff are stored\n # as several characters, which in turn means that regex character\n # ranges with these characters do not work.\n # See\n # * http://bugs.python.org/issue12729\n # * http://bugs.python.org/issue12749\n # * http://bugs.python.org/issue3665\n #\n # Here we simple skip the [#x10000-#xEFFFF] part\n # this means that some SPARQL queries will not parse :(\n # We *could* generate a new regex with \\U00010000|\\U00010001 ...\n # but it would be quite long :)\n #\n # in py3.3 this is fixed\n\n PN_CHARS_BASE_re = \"A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\"\nelse:\n # wide python build\n PN_CHARS_BASE_re = \"A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\U00010000-\\U000EFFFF\"\n\n# [165] PN_CHARS_U ::= PN_CHARS_BASE | '_'\nPN_CHARS_U_re = \"_\" + PN_CHARS_BASE_re\n\n# [167] PN_CHARS ::= PN_CHARS_U | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040]\nPN_CHARS_re = \"\\\\-0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040\" + PN_CHARS_U_re\n# PN_CHARS = Regex(u'[%s]'%PN_CHARS_re, flags=re.U)\n\n# [168] PN_PREFIX ::= PN_CHARS_BASE ((PN_CHARS|'.')* PN_CHARS)?\nPN_PREFIX = Regex(\n \"[%s](?:[%s\\\\.]*[%s])?\" % (PN_CHARS_BASE_re, PN_CHARS_re, PN_CHARS_re), flags=re.U\n)\n\n# [140] PNAME_NS ::= PN_PREFIX? ':'\nPNAME_NS = Optional(Param(\"prefix\", PN_PREFIX)) + Suppress(\":\").leaveWhitespace()\n\n# [173] PN_LOCAL_ESC ::= '\\' ( '_' | '~' | '.' | '-' | '!' | '$' | '&' | \"'\" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%' )\n\nPN_LOCAL_ESC_re = \"\\\\\\\\[_~\\\\.\\\\-!$&\\\"'()*+,;=/?#@%]\"\n# PN_LOCAL_ESC = Regex(PN_LOCAL_ESC_re) # regex'd\n# PN_LOCAL_ESC.setParseAction(lambda x: x[0][1:])\n\n# [172] HEX ::= [0-9] | [A-F] | [a-f]\n# HEX = Regex('[0-9A-Fa-f]') # not needed\n\n# [171] PERCENT ::= '%' HEX HEX\nPERCENT_re = \"%[0-9a-fA-F]{2}\"\n# PERCENT = Regex(PERCENT_re) # regex'd\n# PERCENT.setParseAction(lambda x: chr(int(x[0][1:], 16)))\n\n# [170] PLX ::= PERCENT | PN_LOCAL_ESC\nPLX_re = \"(%s|%s)\" % (PN_LOCAL_ESC_re, PERCENT_re)\n# PLX = PERCENT | PN_LOCAL_ESC # regex'd\n\n\n# [169] PN_LOCAL ::= (PN_CHARS_U | ':' | [0-9] | PLX ) ((PN_CHARS | '.' | ':' | PLX)* (PN_CHARS | ':' | PLX) )?\n\nPN_LOCAL = Regex(\n \"\"\"([%(PN_CHARS_U)s:0-9]|%(PLX)s)\n (([%(PN_CHARS)s\\\\.:]|%(PLX)s)*\n ([%(PN_CHARS)s:]|%(PLX)s) )?\"\"\"\n % dict(PN_CHARS_U=PN_CHARS_U_re, PN_CHARS=PN_CHARS_re, PLX=PLX_re),\n flags=re.X | re.UNICODE,\n)\n\n\n# [141] PNAME_LN ::= PNAME_NS PN_LOCAL\nPNAME_LN = PNAME_NS + Param(\"localname\", PN_LOCAL.leaveWhitespace())\n\n# [142] BLANK_NODE_LABEL ::= '_:' ( PN_CHARS_U | [0-9] ) ((PN_CHARS|'.')* PN_CHARS)?\nBLANK_NODE_LABEL = Regex(\n \"_:[0-9%s](?:[\\\\.%s]*[%s])?\" % (PN_CHARS_U_re, PN_CHARS_re, PN_CHARS_re),\n flags=re.U,\n)\nBLANK_NODE_LABEL.setParseAction(lambda x: rdflib.BNode(x[0][2:]))\n\n\n# [166] VARNAME ::= ( PN_CHARS_U | [0-9] ) ( PN_CHARS_U | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )*\nVARNAME = Regex(\n \"[%s0-9][%s0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*\" % (PN_CHARS_U_re, PN_CHARS_U_re),\n flags=re.U,\n)\n\n# [143] VAR1 ::= '?' VARNAME\nVAR1 = Combine(Suppress(\"?\") + VARNAME)\n\n# [144] VAR2 ::= '$' VARNAME\nVAR2 = Combine(Suppress(\"$\") + VARNAME)\n\n# [145] LANGTAG ::= '@' [a-zA-Z]+ ('-' [a-zA-Z0-9]+)*\nLANGTAG = Combine(Suppress(\"@\") + Regex(\"[a-zA-Z]+(?:-[a-zA-Z0-9]+)*\"))\n\n# [146] INTEGER ::= [0-9]+\nINTEGER = Regex(r\"[0-9]+\")\n# INTEGER.setResultsName('integer')\nINTEGER.setParseAction(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.integer))\n\n# [155] EXPONENT ::= [eE] [+-]? [0-9]+\nEXPONENT_re = \"[eE][+-]?[0-9]+\"\n\n# [147] DECIMAL ::= [0-9]* '.' [0-9]+\nDECIMAL = Regex(r\"[0-9]*\\.[0-9]+\") # (?![eE])\n# DECIMAL.setResultsName('decimal')\nDECIMAL.setParseAction(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.decimal))\n\n# [148] DOUBLE ::= [0-9]+ '.' [0-9]* EXPONENT | '.' ([0-9])+ EXPONENT | ([0-9])+ EXPONENT\nDOUBLE = Regex(r\"[0-9]+\\.[0-9]*%(e)s|\\.([0-9])+%(e)s|[0-9]+%(e)s\" % {\"e\": EXPONENT_re})\n# DOUBLE.setResultsName('double')\nDOUBLE.setParseAction(lambda x: rdflib.Literal(x[0], datatype=rdflib.XSD.double))\n\n\n# [149] INTEGER_POSITIVE ::= '+' INTEGER\nINTEGER_POSITIVE = Suppress(\"+\") + INTEGER.copy().leaveWhitespace()\nINTEGER_POSITIVE.setParseAction(\n lambda x: rdflib.Literal(\"+\" + x[0], datatype=rdflib.XSD.integer)\n)\n\n# [150] DECIMAL_POSITIVE ::= '+' DECIMAL\nDECIMAL_POSITIVE = Suppress(\"+\") + DECIMAL.copy().leaveWhitespace()\n\n# [151] DOUBLE_POSITIVE ::= '+' DOUBLE\nDOUBLE_POSITIVE = Suppress(\"+\") + DOUBLE.copy().leaveWhitespace()\n\n# [152] INTEGER_NEGATIVE ::= '-' INTEGER\nINTEGER_NEGATIVE = Suppress(\"-\") + INTEGER.copy().leaveWhitespace()\nINTEGER_NEGATIVE.setParseAction(lambda x: neg(x[0]))\n\n# [153] DECIMAL_NEGATIVE ::= '-' DECIMAL\nDECIMAL_NEGATIVE = Suppress(\"-\") + DECIMAL.copy().leaveWhitespace()\nDECIMAL_NEGATIVE.setParseAction(lambda x: neg(x[0]))\n\n# [154] DOUBLE_NEGATIVE ::= '-' DOUBLE\nDOUBLE_NEGATIVE = Suppress(\"-\") + DOUBLE.copy().leaveWhitespace()\nDOUBLE_NEGATIVE.setParseAction(lambda x: neg(x[0]))\n\n# [160] ECHAR ::= '\\' [tbnrf\\\"']\n# ECHAR = Regex('\\\\\\\\[tbnrf\"\\']')\n\n\n# [158] STRING_LITERAL_LONG1 ::= \"'''\" ( ( \"'\" | \"''\" )? ( [^'\\] | ECHAR ) )* \"'''\"\n# STRING_LITERAL_LONG1 = Literal(\"'''\") + ( Optional( Literal(\"'\") | \"''\"\n# ) + ZeroOrMore( ~ Literal(\"'\\\\\") | ECHAR ) ) + \"'''\"\nSTRING_LITERAL_LONG1 = Regex(\"'''((?:'|'')?(?:[^'\\\\\\\\]|\\\\\\\\['ntbrf\\\\\\\\]))*'''\")\nSTRING_LITERAL_LONG1.setParseAction(\n lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][3:-3]))\n)\n\n# [159] STRING_LITERAL_LONG2 ::= '\"\"\"' ( ( '\"' | '\"\"' )? ( [^\"\\] | ECHAR ) )* '\"\"\"'\n# STRING_LITERAL_LONG2 = Literal('\"\"\"') + ( Optional( Literal('\"') | '\"\"'\n# ) + ZeroOrMore( ~ Literal('\"\\\\') | ECHAR ) ) + '\"\"\"'\nSTRING_LITERAL_LONG2 = Regex('\"\"\"(?:(?:\"|\"\")?(?:[^\"\\\\\\\\]|\\\\\\\\[\"ntbrf\\\\\\\\]))*\"\"\"')\nSTRING_LITERAL_LONG2.setParseAction(\n lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][3:-3]))\n)\n\n# [156] STRING_LITERAL1 ::= \"'\" ( ([^#x27#x5C#xA#xD]) | ECHAR )* \"'\"\n# STRING_LITERAL1 = Literal(\"'\") + ZeroOrMore(\n# Regex(u'[^\\u0027\\u005C\\u000A\\u000D]',flags=re.U) | ECHAR ) + \"'\"\n\nSTRING_LITERAL1 = Regex(\"'(?:[^'\\\\n\\\\r\\\\\\\\]|\\\\\\\\['ntbrf\\\\\\\\])*'(?!')\", flags=re.U)\nSTRING_LITERAL1.setParseAction(\n lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][1:-1]))\n)\n\n# [157] STRING_LITERAL2 ::= '\"' ( ([^#x22#x5C#xA#xD]) | ECHAR )* '\"'\n# STRING_LITERAL2 = Literal('\"') + ZeroOrMore (\n# Regex(u'[^\\u0022\\u005C\\u000A\\u000D]',flags=re.U) | ECHAR ) + '\"'\n\nSTRING_LITERAL2 = Regex('\"(?:[^\"\\\\n\\\\r\\\\\\\\]|\\\\\\\\[\"ntbrf\\\\\\\\])*\"(?!\")', flags=re.U)\nSTRING_LITERAL2.setParseAction(\n lambda x: rdflib.Literal(decodeUnicodeEscape(x[0][1:-1]))\n)\n\n# [161] NIL ::= '(' WS* ')'\nNIL = Literal(\"(\") + \")\"\nNIL.setParseAction(lambda x: rdflib.RDF.nil)\n\n# [162] WS ::= #x20 | #x9 | #xD | #xA\n# Not needed?\n# WS = #x20 | #x9 | #xD | #xA\n# [163] ANON ::= '[' WS* ']'\nANON = Literal(\"[\") + \"]\"\nANON.setParseAction(lambda x: rdflib.BNode())\n\n# A = CaseSensitiveKeyword('a')\nA = Literal(\"a\")\nA.setParseAction(lambda x: rdflib.RDF.type)\n\n\n# ------ NON-TERMINALS --------------\n\n# [5] BaseDecl ::= 'BASE' IRIREF\nBaseDecl = Comp(\"Base\", Keyword(\"BASE\") + Param(\"iri\", IRIREF))\n\n# [6] PrefixDecl ::= 'PREFIX' PNAME_NS IRIREF\nPrefixDecl = Comp(\"PrefixDecl\", Keyword(\"PREFIX\") + PNAME_NS + Param(\"iri\", IRIREF))\n\n# [4] Prologue ::= ( BaseDecl | PrefixDecl )*\nPrologue = Group(ZeroOrMore(BaseDecl | PrefixDecl))\n\n# [108] Var ::= VAR1 | VAR2\nVar = VAR1 | VAR2\nVar.setParseAction(lambda x: rdflib.term.Variable(x[0]))\n\n# [137] PrefixedName ::= PNAME_LN | PNAME_NS\nPrefixedName = Comp(\"pname\", PNAME_LN | PNAME_NS)\n\n# [136] iri ::= IRIREF | PrefixedName\niri = IRIREF | PrefixedName\n\n# [135] String ::= STRING_LITERAL1 | STRING_LITERAL2 | STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2\nString = STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2 | STRING_LITERAL1 | STRING_LITERAL2\n\n# [129] RDFLiteral ::= String ( LANGTAG | ( '^^' iri ) )?\n\nRDFLiteral = Comp(\n \"literal\",\n Param(\"string\", String)\n + Optional(\n Param(\"lang\", LANGTAG.leaveWhitespace())\n | Literal(\"^^\").leaveWhitespace() + Param(\"datatype\", iri).leaveWhitespace()\n ),\n)\n\n# [132] NumericLiteralPositive ::= INTEGER_POSITIVE | DECIMAL_POSITIVE | DOUBLE_POSITIVE\nNumericLiteralPositive = DOUBLE_POSITIVE | DECIMAL_POSITIVE | INTEGER_POSITIVE\n\n# [133] NumericLiteralNegative ::= INTEGER_NEGATIVE | DECIMAL_NEGATIVE | DOUBLE_NEGATIVE\nNumericLiteralNegative = DOUBLE_NEGATIVE | DECIMAL_NEGATIVE | INTEGER_NEGATIVE\n\n# [131] NumericLiteralUnsigned ::= INTEGER | DECIMAL | DOUBLE\nNumericLiteralUnsigned = DOUBLE | DECIMAL | INTEGER\n\n# [130] NumericLiteral ::= NumericLiteralUnsigned | NumericLiteralPositive | NumericLiteralNegative\nNumericLiteral = (\n NumericLiteralUnsigned | NumericLiteralPositive | NumericLiteralNegative\n)\n\n# [134] BooleanLiteral ::= 'true' | 'false'\nBooleanLiteral = Keyword(\"true\").setParseAction(lambda: rdflib.Literal(True)) | Keyword(\n \"false\"\n).setParseAction(lambda: rdflib.Literal(False))\n\n# [138] BlankNode ::= BLANK_NODE_LABEL | ANON\nBlankNode = BLANK_NODE_LABEL | ANON\n\n# [109] GraphTerm ::= iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | NIL\nGraphTerm = iri | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | NIL\n\n# [106] VarOrTerm ::= Var | GraphTerm\nVarOrTerm = Var | GraphTerm\n\n# [107] VarOrIri ::= Var | iri\nVarOrIri = Var | iri\n\n# [46] GraphRef ::= 'GRAPH' iri\nGraphRef = Keyword(\"GRAPH\") + Param(\"graphiri\", iri)\n\n# [47] GraphRefAll ::= GraphRef | 'DEFAULT' | 'NAMED' | 'ALL'\nGraphRefAll = (\n GraphRef\n | Param(\"graphiri\", Keyword(\"DEFAULT\"))\n | Param(\"graphiri\", Keyword(\"NAMED\"))\n | Param(\"graphiri\", Keyword(\"ALL\"))\n)\n\n# [45] GraphOrDefault ::= 'DEFAULT' | 'GRAPH'? iri\nGraphOrDefault = ParamList(\"graph\", Keyword(\"DEFAULT\")) | Optional(\n Keyword(\"GRAPH\")\n) + ParamList(\"graph\", iri)\n\n# [65] DataBlockValue ::= iri | RDFLiteral | NumericLiteral | BooleanLiteral | 'UNDEF'\nDataBlockValue = iri | RDFLiteral | NumericLiteral | BooleanLiteral | Keyword(\"UNDEF\")\n\n# [78] Verb ::= VarOrIri | A\nVerb = VarOrIri | A\n\n\n# [85] VerbSimple ::= Var\nVerbSimple = Var\n\n# [97] Integer ::= INTEGER\nInteger = INTEGER\n\n\nTriplesNode = Forward()\nTriplesNodePath = Forward()\n\n# [104] GraphNode ::= VarOrTerm | TriplesNode\nGraphNode = VarOrTerm | TriplesNode\n\n# [105] GraphNodePath ::= VarOrTerm | TriplesNodePath\nGraphNodePath = VarOrTerm | TriplesNodePath\n\n\n# [93] PathMod ::= '?' | '*' | '+'\nPathMod = Literal(\"?\") | \"*\" | \"+\"\n\n# [96] PathOneInPropertySet ::= iri | A | '^' ( iri | A )\nPathOneInPropertySet = iri | A | Comp(\"InversePath\", \"^\" + (iri | A))\n\nPath = Forward()\n\n# [95] PathNegatedPropertySet ::= PathOneInPropertySet | '(' ( PathOneInPropertySet ( '|' PathOneInPropertySet )* )? ')'\nPathNegatedPropertySet = Comp(\n \"PathNegatedPropertySet\",\n... [truncated 35688 chars]\n\n```\n\n### rdflib/plugins/sparql/parserutils.py\n```python\n\"\"\"\n\nNOTE: PyParsing setResultName/__call__ provides a very similar solution to this\nI didn't realise at the time of writing and I will remove a\nlot of this code at some point\n\nUtility classes for creating an abstract-syntax tree out with pyparsing actions\n\nLets you label and group parts of parser production rules\n\nFor example:\n\n# [5] BaseDecl ::= 'BASE' IRIREF\nBaseDecl = Comp('Base', Keyword('BASE') + Param('iri',IRIREF))\n\nAfter parsing, this gives you back an CompValue object,\nwhich is a dict/object with the parameters specified.\nSo you can access the parameters are attributes or as keys:\n\nbaseDecl.iri\n\nComp lets you set an evalFn that is bound to the eval method of\nthe resulting CompValue\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import OrderedDict\nfrom types import MethodType\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n List,\n Mapping,\n Optional,\n Tuple,\n TypeVar,\n Union,\n)\n\nfrom pyparsing import ParserElement, ParseResults, TokenConverter, originalTextFor\n\nfrom rdflib.term import BNode, Identifier, Variable\n\nif TYPE_CHECKING:\n from rdflib.plugins.sparql.sparql import FrozenBindings\n\n\n# This is an alternative\n\n# Comp('Sum')( Param('x')(Number) + '+' + Param('y')(Number) )\n\n\ndef value(\n ctx: FrozenBindings,\n val: Any,\n variables: bool = False,\n errors: bool = False,\n) -> Any:\n \"\"\"Utility function for evaluating something...\n\n Variables will be looked up in the context\n Normally, non-bound vars is an error,\n set variables=True to return unbound vars\n\n Normally, an error raises the error,\n set errors=True to return error\n \"\"\"\n\n if isinstance(val, Expr):\n return val.eval(ctx) # recurse?\n elif isinstance(val, CompValue):\n raise Exception(\"What do I do with this CompValue? %s\" % val)\n\n elif isinstance(val, list):\n return [value(ctx, x, variables, errors) for x in val]\n\n elif isinstance(val, (BNode, Variable)):\n r = ctx.get(val)\n if isinstance(r, SPARQLError) and not errors:\n raise r\n if r is not None:\n return r\n\n # not bound\n if variables:\n return val\n else:\n raise NotBoundError\n\n elif isinstance(val, ParseResults) and len(val) == 1:\n return value(ctx, val[0], variables, errors)\n else:\n return val\n\n\nclass ParamValue:\n \"\"\"\n The result of parsing a Param\n This just keeps the name/value\n All cleverness is in the CompValue\n \"\"\"\n\n def __init__(\n self, name: str, tokenList: Union[List[Any], ParseResults], isList: bool\n ):\n self.isList = isList\n self.name = name\n if isinstance(tokenList, (list, ParseResults)) and len(tokenList) == 1:\n tokenList = tokenList[0]\n\n self.tokenList = tokenList\n\n def __str__(self) -> str:\n return \"Param(%s, %s)\" % (self.name, self.tokenList)\n\n\nclass Param(TokenConverter):\n \"\"\"\n A pyparsing token for labelling a part of the parse-tree\n if isList is true repeat occurrences of ParamList have\n their values merged in a list\n \"\"\"\n\n def __init__(self, name: str, expr, isList: bool = False):\n self.isList = isList\n TokenConverter.__init__(self, expr)\n self.setName(name)\n self.addParseAction(self.postParse2)\n\n def postParse2(self, tokenList: Union[List[Any], ParseResults]) -> ParamValue:\n return ParamValue(self.name, tokenList, self.isList)\n\n\nclass ParamList(Param):\n \"\"\"\n A shortcut for a Param with isList=True\n \"\"\"\n\n def __init__(self, name: str, expr):\n Param.__init__(self, name, expr, True)\n\n\n_ValT = TypeVar(\"_ValT\")\n\n\nclass CompValue(OrderedDict):\n \"\"\"\n The result of parsing a Comp\n Any included Params are available as Dict keys\n or as attributes\n \"\"\"\n\n def __init__(self, name: str, **values):\n OrderedDict.__init__(self)\n self.name = name\n self.update(values)\n\n def clone(self) -> CompValue:\n return CompValue(self.name, **self)\n\n def __str__(self) -> str:\n return self.name + \"_\" + OrderedDict.__str__(self)\n\n def __repr__(self) -> str:\n return self.name + \"_\" + dict.__repr__(self)\n\n def _value(\n self, val: _ValT, variables: bool = False, errors: bool = False\n ) -> Union[_ValT, Any]:\n if self.ctx is not None:\n return value(self.ctx, val, variables)\n else:\n return val\n\n def __getitem__(self, a):\n return self._value(OrderedDict.__getitem__(self, a))\n\n # type error: Signature of \"get\" incompatible with supertype \"dict\"\n # type error: Signature of \"get\" incompatible with supertype \"Mapping\" [override]\n def get(self, a, variables: bool = False, errors: bool = False): # type: ignore[override]\n return self._value(OrderedDict.get(self, a, a), variables, errors)\n\n def __getattr__(self, a: str) -> Any:\n # Hack hack: OrderedDict relies on this\n if a in (\"_OrderedDict__root\", \"_OrderedDict__end\"):\n raise AttributeError()\n try:\n return self[a]\n except KeyError:\n # raise AttributeError('no such attribute '+a)\n return None\n\n if TYPE_CHECKING:\n # this is here because properties are dynamically set on CompValue\n def __setattr__(self, __name: str, __value: Any) -> None: ...\n\n\nclass Expr(CompValue):\n \"\"\"\n A CompValue that is evaluatable\n \"\"\"\n\n def __init__(\n self,\n name: str,\n evalfn: Optional[Callable[[Any, Any], Any]] = None,\n **values,\n ):\n super(Expr, self).__init__(name, **values)\n\n self._evalfn = None\n if evalfn:\n self._evalfn = MethodType(evalfn, self)\n\n def eval(self, ctx: Any = {}) -> Union[SPARQLError, Any]:\n try:\n self.ctx: Optional[Union[Mapping, FrozenBindings]] = ctx\n # type error: \"None\" not callable\n return self._evalfn(ctx) # type: ignore[misc]\n except SPARQLError as e:\n return e\n finally:\n self.ctx = None\n\n\nclass Comp(TokenConverter):\n \"\"\"\n A pyparsing token for grouping together things with a label\n Any sub-tokens that are not Params will be ignored.\n\n Returns CompValue / Expr objects - depending on whether evalFn is set.\n \"\"\"\n\n def __init__(self, name: str, expr: ParserElement):\n self.expr = expr\n TokenConverter.__init__(self, expr)\n self.setName(name)\n self.evalfn: Optional[Callable[[Any, Any], Any]] = None\n\n def postParse(\n self, instring: str, loc: int, tokenList: ParseResults\n ) -> Union[Expr, CompValue]:\n res: Union[Expr, CompValue]\n if self.evalfn:\n res = Expr(self.name)\n res._evalfn = MethodType(self.evalfn, res)\n else:\n res = CompValue(self.name)\n if self.name == \"ServiceGraphPattern\":\n # Then this must be a service graph pattern and have\n # already matched.\n # lets assume there is one, for now, then test for two later.\n sgp = originalTextFor(self.expr)\n service_string = sgp.searchString(instring)[0][0]\n res[\"service_string\"] = service_string\n\n for t in tokenList:\n if isinstance(t, ParamValue):\n if t.isList:\n if t.name not in res:\n res[t.name] = []\n res[t.name].append(t.tokenList)\n else:\n res[t.name] = t.tokenList\n # res.append(t.tokenList)\n # if isinstance(t,CompValue):\n # res.update(t)\n return res\n\n def setEvalFn(self, evalfn: Callable[[Any, Any], Any]) -> Comp:\n self.evalfn = evalfn\n return self\n\n\ndef prettify_parsetree(t: ParseResults, indent: str = \"\", depth: int = 0) -> str:\n out: List[str] = []\n for e in t.asList():\n out.append(_prettify_sub_parsetree(e, indent, depth + 1))\n for k, v in sorted(t.items()):\n out.append(\"%s%s- %s:\\n\" % (indent, \" \" * depth, k))\n out.append(_prettify_sub_parsetree(v, indent, depth + 1))\n return \"\".join(out)\n\n\ndef _prettify_sub_parsetree(\n t: Union[Identifier, CompValue, set, list, dict, Tuple, bool, None],\n indent: str = \"\",\n depth: int = 0,\n) -> str:\n out: List[str] = []\n if isinstance(t, CompValue):\n out.append(\"%s%s> %s:\\n\" % (indent, \" \" * depth, t.name))\n for k, v in t.items():\n out.append(\"%s%s- %s:\\n\" % (indent, \" \" * (depth + 1), k))\n out.append(_prettify_sub_parsetree(v, indent, depth + 2))\n elif isinstance(t, dict):\n for k, v in t.items():\n out.append(\"%s%s- %s:\\n\" % (indent, \" \" * (depth + 1), k))\n out.append(_prettify_sub_parsetree(v, indent, depth + 2))\n elif isinstance(t, list):\n for e in t:\n out.append(_prettify_sub_parsetree(e, indent, depth + 1))\n else:\n out.append(\"%s%s- %r\\n\" % (indent, \" \" * depth, t))\n return \"\".join(out)\n\n\n# hurrah for circular imports\nfrom rdflib.plugins.sparql.sparql import NotBoundError, SPARQLError # noqa: E402\n\n```\n\n### rdflib/plugins/sparql/results/tsvresults.py\n```python\n\"\"\"\nThis implements the Tab Separated SPARQL Result Format\n\nIt is implemented with pyparsing, reusing the elements from the SPARQL Parser\n\"\"\"\n\nfrom __future__ import annotations\n\nimport codecs\nimport typing\nfrom typing import IO, Union\n\nfrom pyparsing import (\n FollowedBy,\n LineEnd,\n Literal,\n Optional,\n ParserElement,\n Suppress,\n ZeroOrMore,\n)\n\nfrom rdflib.plugins.sparql.parser import (\n BLANK_NODE_LABEL,\n IRIREF,\n LANGTAG,\n STRING_LITERAL1,\n STRING_LITERAL2,\n BooleanLiteral,\n NumericLiteral,\n Var,\n)\nfrom rdflib.plugins.sparql.parserutils import Comp, CompValue, Param\nfrom rdflib.query import Result, ResultParser\nfrom rdflib.term import BNode, URIRef\nfrom rdflib.term import Literal as RDFLiteral\n\nParserElement.setDefaultWhitespaceChars(\" \\n\")\n\n\nString = STRING_LITERAL1 | STRING_LITERAL2\n\nRDFLITERAL = Comp(\n \"literal\",\n Param(\"string\", String)\n + Optional(\n Param(\"lang\", LANGTAG.leaveWhitespace())\n | Literal(\"^^\").leaveWhitespace() + Param(\"datatype\", IRIREF).leaveWhitespace()\n ),\n)\n\nNONE_VALUE = object()\n\nEMPTY = FollowedBy(LineEnd()) | FollowedBy(\"\\t\")\nEMPTY.setParseAction(lambda x: NONE_VALUE)\n\nTERM = RDFLITERAL | IRIREF | BLANK_NODE_LABEL | NumericLiteral | BooleanLiteral\n\nROW = (EMPTY | TERM) + ZeroOrMore(Suppress(\"\\t\") + (EMPTY | TERM))\nROW.parseWithTabs()\n\nHEADER = Var + ZeroOrMore(Suppress(\"\\t\") + Var)\nHEADER.parseWithTabs()\n\n\nclass TSVResultParser(ResultParser):\n \"\"\"Parses SPARQL TSV results into a Result object.\"\"\"\n\n # type error: Signature of \"parse\" incompatible with supertype \"ResultParser\" [override]\n def parse(self, source: IO, content_type: typing.Optional[str] = None) -> Result: # type: ignore[override]\n if isinstance(source.read(0), bytes):\n # if reading from source returns bytes do utf-8 decoding\n # type error: Incompatible types in assignment (expression has type \"StreamReader\", variable has type \"IO[Any]\")\n source = codecs.getreader(\"utf-8\")(source) # type: ignore[assignment]\n\n r = Result(\"SELECT\")\n\n header = source.readline()\n\n r.vars = list(HEADER.parseString(header.strip(), parseAll=True))\n r.bindings = []\n while True:\n line = source.readline()\n if not line:\n break\n line = line.strip(\"\\n\")\n if line == \"\":\n continue\n\n row = ROW.parseString(line, parseAll=True)\n # type error: Generator has incompatible item type \"object\"; expected \"Identifier\"\n r.bindings.append(dict(zip(r.vars, (self.convertTerm(x) for x in row)))) # type: ignore[misc]\n\n return r\n\n def convertTerm(\n self, t: Union[object, RDFLiteral, BNode, CompValue, URIRef]\n ) -> typing.Optional[Union[object, BNode, URIRef, RDFLiteral]]:\n if t is NONE_VALUE:\n return None\n if isinstance(t, CompValue):\n if t.name == \"literal\":\n return RDFLiteral(t.string, lang=t.lang, datatype=t.datatype)\n else:\n raise Exception(\"I dont know how to handle this: %s\" % (t,))\n else:\n return t\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-2be67dca9f5d", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-2be67dca9f5d", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "6539dfef42c5b853ccab41c046772a8e0c8e1658", "source_files": ["rdflib/plugins/sparql/parser.py", "rdflib/plugins/sparql/parserutils.py", "rdflib/plugins/sparql/pyparsing_compat.py", "rdflib/plugins/sparql/results/tsvresults.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Base namespace predicates generate unnecessary prefixes in Turtle/LongTurtle output\n\n## Description\nWhen serializing data into Turtle or LongTurtle formats, predicates that belong to the base namespace are incorrectly rendered with an explicit prefix. For example, a predicate that should appear as `myPredicate` might instead be output as `base:myPredicate` or `_base:myPredicate`. This is unexpected, as predicates in the base namespace should not require an explicit prefix.\n\nAdditionally, in LongTurtle format, pnames (prefixed names) containing bracket characters are not properly escaped, leading to malformed output.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `1964642d472c` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/serializers/longturtle.py\n```python\n\"\"\"\nLongTurtle RDF graph serializer for RDFLib.\nSee for syntax specification.\n\nThis variant, longturtle as opposed to just turtle, makes some small format changes\nto turtle - the original turtle serializer. It:\n\n* uses PREFIX instead of @prefix\n* uses BASE instead of @base\n* adds a new line at RDF.type, or 'a'\n* adds a newline and an indent for all triples with more than one object (object list)\n* adds a new line and ';' for the last triple in a set with '.'\n on the start of the next line\n* uses default encoding (encode()) is used instead of \"latin-1\"\n\n- Nicholas Car, 2023\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import IO, Any, Optional\n\nfrom rdflib.compare import to_canonical_graph\nfrom rdflib.exceptions import Error\nfrom rdflib.graph import Graph\nfrom rdflib.namespace import RDF\nfrom rdflib.term import BNode, Literal, URIRef\n\nfrom .turtle import RecursiveSerializer\n\n__all__ = [\"LongTurtleSerializer\"]\n\nSUBJECT = 0\nVERB = 1\nOBJECT = 2\n\n_GEN_QNAME_FOR_DT = False\n_SPACIOUS_OUTPUT = False\n\n\nclass LongTurtleSerializer(RecursiveSerializer):\n \"\"\"LongTurtle, a Turtle serialization format.\n\n When the optional parameter ``canon`` is set to :py:obj:`True`, the graph is canonicalized\n before serialization. This normalizes blank node identifiers and allows for\n deterministic serialization of the graph. Useful when consistent outputs are required.\n \"\"\"\n\n short_name = \"longturtle\"\n indentString = \" \"\n\n def __init__(self, store):\n self._ns_rewrite = {}\n self._canon = False\n super(LongTurtleSerializer, self).__init__(store)\n self.keywords = {RDF.type: \"a\"}\n self.reset()\n self.stream = None\n self._spacious: bool = _SPACIOUS_OUTPUT\n\n def addNamespace(self, prefix, namespace):\n # Turtle does not support prefixes that start with _\n # if they occur in the graph, rewrite to p_blah\n # this is more complicated since we need to make sure p_blah\n # does not already exist. And we register namespaces as we go, i.e.\n # we may first see a triple with prefix _9 - rewrite it to p_9\n # and then later find a triple with a \"real\" p_9 prefix\n\n # so we need to keep track of ns rewrites we made so far.\n\n if (prefix > \"\" and prefix[0] == \"_\") or self.namespaces.get(\n prefix, namespace\n ) != namespace:\n if prefix not in self._ns_rewrite:\n p = \"p\" + prefix\n while p in self.namespaces:\n p = \"p\" + p\n self._ns_rewrite[prefix] = p\n\n prefix = self._ns_rewrite.get(prefix, prefix)\n\n super(LongTurtleSerializer, self).addNamespace(prefix, namespace)\n return prefix\n\n def canonize(self):\n \"\"\"Apply canonicalization to the store.\n\n This normalizes blank node identifiers and allows for deterministic\n serialization of the graph.\n \"\"\"\n if not self._canon:\n return\n\n namespace_manager = self.store.namespace_manager\n store = to_canonical_graph(self.store)\n content = store.serialize(format=\"application/n-triples\")\n lines = content.split(\"\\n\")\n lines.sort()\n graph = Graph()\n graph.parse(\n data=\"\\n\".join(lines), format=\"application/n-triples\", skolemize=True\n )\n graph = graph.de_skolemize()\n graph.namespace_manager = namespace_manager\n self.store = graph\n\n def reset(self):\n super(LongTurtleSerializer, self).reset()\n self._shortNames = {}\n self._started = False\n self._ns_rewrite = {}\n self.canonize()\n\n def serialize(\n self,\n stream: IO[bytes],\n base: Optional[str] = None,\n encoding: Optional[str] = None,\n spacious: Optional[bool] = None,\n **kwargs: Any,\n ) -> None:\n self._canon = kwargs.get(\"canon\", False)\n self.reset()\n self.stream = stream\n # if base is given here, use, if not and a base is set for the graph use that\n if base is not None:\n self.base = base\n elif self.store.base is not None:\n self.base = self.store.base\n\n if spacious is not None:\n self._spacious = spacious\n\n self.preprocess()\n subjects_list = self.orderSubjects()\n\n self.startDocument()\n\n firstTime = True\n for subject in subjects_list:\n if self.isDone(subject):\n continue\n if firstTime:\n firstTime = False\n if self.statement(subject) and not firstTime:\n self.write(\"\\n\")\n\n self.endDocument()\n\n self.base = None\n\n def preprocessTriple(self, triple):\n super(LongTurtleSerializer, self).preprocessTriple(triple)\n for i, node in enumerate(triple):\n if node in self.keywords:\n continue\n # Don't use generated prefixes for subjects and objects\n self.getQName(node, gen_prefix=(i == VERB))\n if isinstance(node, Literal) and node.datatype:\n self.getQName(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT)\n p = triple[1]\n if isinstance(p, BNode): # hmm - when is P ever a bnode?\n self._references[p] += 1\n\n def getQName(self, uri, gen_prefix=True):\n if not isinstance(uri, URIRef):\n return None\n\n try:\n parts = self.store.compute_qname(uri, generate=gen_prefix)\n except Exception:\n # is the uri a namespace in itself?\n pfx = self.store.store.prefix(uri)\n\n if pfx is not None:\n parts = (pfx, uri, \"\")\n else:\n # nothing worked\n return None\n\n prefix, namespace, local = parts\n\n # QName cannot end with .\n if local.endswith(\".\"):\n return None\n\n prefix = self.addNamespace(prefix, namespace)\n\n return \"%s:%s\" % (prefix, local)\n\n def startDocument(self):\n self._started = True\n ns_list = sorted(self.namespaces.items())\n\n if self.base:\n self.write(self.indent() + \"BASE <%s>\\n\" % self.base)\n for prefix, uri in ns_list:\n self.write(self.indent() + \"PREFIX %s: <%s>\\n\" % (prefix, uri))\n if ns_list and self._spacious:\n self.write(\"\\n\")\n\n def endDocument(self):\n if self._spacious:\n self.write(\"\\n\")\n\n def statement(self, subject):\n self.subjectDone(subject)\n return self.s_squared(subject) or self.s_default(subject)\n\n def s_default(self, subject):\n self.write(\"\\n\" + self.indent())\n self.path(subject, SUBJECT)\n self.write(\"\\n\" + self.indent())\n self.predicateList(subject)\n self.write(\"\\n.\")\n return True\n\n def s_squared(self, subject):\n if (self._references[subject] > 0) or not isinstance(subject, BNode):\n return False\n self.write(\"\\n\" + self.indent() + \"[]\")\n self.predicateList(subject, newline=False)\n self.write(\"\\n.\")\n return True\n\n def path(self, node, position, newline=False):\n if not (\n self.p_squared(node, position) or self.p_default(node, position, newline)\n ):\n raise Error(\"Cannot serialize node '%s'\" % (node,))\n\n def p_default(self, node, position, newline=False):\n if position != SUBJECT and not newline:\n self.write(\" \")\n self.write(self.label(node, position))\n return True\n\n def label(self, node, position):\n if node == RDF.nil:\n return \"()\"\n if position is VERB and node in self.keywords:\n return self.keywords[node]\n if isinstance(node, Literal):\n return node._literal_n3(\n use_plain=True,\n qname_callback=lambda dt: self.getQName(dt, _GEN_QNAME_FOR_DT),\n )\n else:\n node = self.relativize(node)\n\n return self.getQName(node, position == VERB) or node.n3()\n\n def p_squared(\n self,\n node,\n position,\n ):\n if (\n not isinstance(node, BNode)\n or node in self._serialized\n or self._references[node] > 1\n or position == SUBJECT\n ):\n return False\n\n if self.isValidList(node):\n # this is a list\n self.depth += 2\n self.write(\" (\\n\")\n self.depth -= 2\n self.doList(node)\n self.write(\"\\n\" + self.indent() + \")\")\n else:\n # this is a Blank Node\n self.subjectDone(node)\n self.write(\"\\n\" + self.indent(1) + \"[\\n\")\n self.depth += 1\n self.predicateList(node)\n self.depth -= 1\n self.write(\"\\n\" + self.indent(1) + \"]\")\n\n return True\n\n def isValidList(self, l_):\n \"\"\"\n Checks if l is a valid RDF list, i.e. no nodes have other properties.\n \"\"\"\n try:\n if self.store.value(l_, RDF.first) is None:\n return False\n except Exception:\n return False\n while l_:\n if l_ != RDF.nil and len(list(self.store.predicate_objects(l_))) != 2:\n return False\n l_ = self.store.value(l_, RDF.rest)\n return True\n\n def doList(self, l_):\n i = 0\n while l_:\n item = self.store.value(l_, RDF.first)\n if item is not None:\n if i == 0:\n self.write(self.indent(1))\n else:\n self.write(\"\\n\" + self.indent(1))\n self.path(item, OBJECT, newline=True)\n self.subjectDone(l_)\n l_ = self.store.value(l_, RDF.rest)\n i += 1\n\n def predicateList(self, subject, newline=False):\n properties = self.buildPredicateHash(subject)\n propList = self.sortProperties(properties)\n if len(propList) == 0:\n return\n self.write(self.indent(1))\n self.verb(propList[0], newline=True)\n self.objectList(properties[propList[0]])\n for predicate in propList[1:]:\n self.write(\" ;\\n\" + self.indent(1))\n self.verb(predicate, newline=True)\n self.objectList(properties[predicate])\n self.write(\" ;\")\n\n def verb(self, node, newline=False):\n self.path(node, VERB, newline)\n\n def objectList(self, objects):\n count = len(objects)\n if count == 0:\n return\n depthmod = (count == 1) and 0 or 1\n self.depth += depthmod\n first_nl = False\n if count > 1:\n if not isinstance(objects[0], BNode):\n self.write(\"\\n\" + self.indent(1))\n else:\n self.write(\" \")\n first_nl = True\n self.path(objects[0], OBJECT, newline=first_nl)\n for obj in objects[1:]:\n self.write(\" ,\")\n if not isinstance(obj, BNode):\n self.write(\"\\n\" + self.indent(1))\n self.path(obj, OBJECT, newline=True)\n self.depth -= depthmod\n\n```\n\n### rdflib/plugins/serializers/turtle.py\n```python\n\"\"\"\nTurtle RDF graph serializer for RDFLib.\nSee for syntax specification.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n DefaultDict,\n Dict,\n List,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n)\n\nfrom rdflib.exceptions import Error\nfrom rdflib.graph import Graph\nfrom rdflib.namespace import RDF, RDFS\nfrom rdflib.serializer import Serializer\nfrom rdflib.term import BNode, Literal, Node, URIRef\n\nif TYPE_CHECKING:\n from rdflib.graph import _PredicateType, _SubjectType, _TripleType\n\n__all__ = [\"RecursiveSerializer\", \"TurtleSerializer\"]\n\n\nclass RecursiveSerializer(Serializer):\n topClasses = [RDFS.Class]\n predicateOrder = [RDF.type, RDFS.label]\n maxDepth = 10\n indentString = \" \"\n roundtrip_prefixes: Tuple[Any, ...] = ()\n\n def __init__(self, store: Graph):\n super(RecursiveSerializer, self).__init__(store)\n self.stream: Optional[IO[bytes]] = None\n self.reset()\n\n def addNamespace(self, prefix: str, uri: URIRef) -> None:\n if prefix in self.namespaces and self.namespaces[prefix] != uri:\n raise Exception(\n \"Trying to override namespace prefix %s => %s, but it's already bound to %s\"\n % (prefix, uri, self.namespaces[prefix])\n )\n self.namespaces[prefix] = uri\n\n def checkSubject(self, subject: _SubjectType) -> bool:\n \"\"\"Check to see if the subject should be serialized yet\"\"\"\n if (\n (self.isDone(subject))\n or (subject not in self._subjects)\n or ((subject in self._topLevels) and (self.depth > 1))\n or (isinstance(subject, URIRef) and (self.depth >= self.maxDepth))\n ):\n return False\n return True\n\n def isDone(self, subject: _SubjectType) -> bool:\n \"\"\"Return true if subject is serialized\"\"\"\n return subject in self._serialized\n\n def orderSubjects(self) -> List[_SubjectType]:\n seen: Dict[_SubjectType, bool] = {}\n subjects: List[_SubjectType] = []\n\n for classURI in self.topClasses:\n members = list(self.store.subjects(RDF.type, classURI))\n members.sort()\n\n subjects.extend(members)\n for member in members:\n self._topLevels[member] = True\n seen[member] = True\n\n recursable = [\n (isinstance(subject, BNode), self._references[subject], subject)\n for subject in self._subjects\n if subject not in seen\n ]\n\n recursable.sort()\n subjects.extend([subject for (isbnode, refs, subject) in recursable])\n\n return subjects\n\n def preprocess(self) -> None:\n for triple in self.store.triples((None, None, None)):\n self.preprocessTriple(triple)\n\n def preprocessTriple(self, spo: _TripleType) -> None:\n s, p, o = spo\n self._references[o] += 1\n self._subjects[s] = True\n\n def reset(self) -> None:\n self.depth = 0\n # Typed none because nothing is using it ...\n self.lists: Dict[None, None] = {}\n self.namespaces: Dict[str, URIRef] = {}\n self._references: DefaultDict[Node, int] = defaultdict(int)\n self._serialized: Dict[_SubjectType, bool] = {}\n self._subjects: Dict[_SubjectType, bool] = {}\n self._topLevels: Dict[_SubjectType, bool] = {}\n\n if self.roundtrip_prefixes:\n if hasattr(self.roundtrip_prefixes, \"__iter__\"):\n for prefix, ns in self.store.namespaces():\n if prefix in self.roundtrip_prefixes:\n self.addNamespace(prefix, ns)\n else:\n for prefix, ns in self.store.namespaces():\n self.addNamespace(prefix, ns)\n\n def buildPredicateHash(\n self, subject: _SubjectType\n ) -> Mapping[_PredicateType, List[Node]]:\n \"\"\"\n Build a hash key by predicate to a list of objects for the given\n subject\n \"\"\"\n properties: Dict[_PredicateType, List[Node]] = {}\n for s, p, o in self.store.triples((subject, None, None)):\n oList = properties.get(p, [])\n oList.append(o)\n properties[p] = oList\n return properties\n\n def sortProperties(\n self, properties: Mapping[_PredicateType, List[Node]]\n ) -> List[_PredicateType]:\n \"\"\"Take a hash from predicate uris to lists of values.\n Sort the lists of values. Return a sorted list of properties.\"\"\"\n # Sort object lists\n for prop, objects in properties.items():\n objects.sort()\n\n # Make sorted list of properties\n propList: List[_PredicateType] = []\n seen: Dict[_PredicateType, bool] = {}\n for prop in self.predicateOrder:\n if (prop in properties) and (prop not in seen):\n propList.append(prop)\n seen[prop] = True\n props = list(properties.keys())\n props.sort()\n for prop in props:\n if prop not in seen:\n propList.append(prop)\n seen[prop] = True\n return propList\n\n def subjectDone(self, subject: _SubjectType) -> None:\n \"\"\"Mark a subject as done.\"\"\"\n self._serialized[subject] = True\n\n def indent(self, modifier: int = 0) -> str:\n \"\"\"Returns indent string multiplied by the depth\"\"\"\n return (self.depth + modifier) * self.indentString\n\n def write(self, text: str) -> None:\n \"\"\"Write text in given encoding.\"\"\"\n # type error: Item \"None\" of \"Optional[IO[bytes]]\" has no attribute \"write\"\n self.stream.write(text.encode(self.encoding, \"replace\")) # type: ignore[union-attr]\n\n\nSUBJECT = 0\nVERB = 1\nOBJECT = 2\n\n_GEN_QNAME_FOR_DT = False\n_SPACIOUS_OUTPUT = False\n\n\nclass TurtleSerializer(RecursiveSerializer):\n short_name = \"turtle\"\n indentString = \" \"\n\n def __init__(self, store: Graph):\n self._ns_rewrite: Dict[str, str] = {}\n super(TurtleSerializer, self).__init__(store)\n self.keywords: Dict[Node, str] = {RDF.type: \"a\"}\n self.reset()\n self.stream = None\n self._spacious = _SPACIOUS_OUTPUT\n\n # type error: Return type \"str\" of \"addNamespace\" incompatible with return type \"None\" in supertype \"RecursiveSerializer\"\n def addNamespace(self, prefix: str, namespace: URIRef) -> str: # type: ignore[override]\n # Turtle does not support prefix that start with _\n # if they occur in the graph, rewrite to p_blah\n # this is more complicated since we need to make sure p_blah\n # does not already exist. And we register namespaces as we go, i.e.\n # we may first see a triple with prefix _9 - rewrite it to p_9\n # and then later find a triple with a \"real\" p_9 prefix\n\n # so we need to keep track of ns rewrites we made so far.\n\n if (prefix > \"\" and prefix[0] == \"_\") or self.namespaces.get(\n prefix, namespace\n ) != namespace:\n if prefix not in self._ns_rewrite:\n p = \"p\" + prefix\n while p in self.namespaces:\n p = \"p\" + p\n self._ns_rewrite[prefix] = p\n\n prefix = self._ns_rewrite.get(prefix, prefix)\n\n super(TurtleSerializer, self).addNamespace(prefix, namespace)\n return prefix\n\n def reset(self) -> None:\n super(TurtleSerializer, self).reset()\n # typing as Dict[None, None] because nothing seems to be using it\n self._shortNames: Dict[None, None] = {}\n self._started = False\n self._ns_rewrite = {}\n\n def serialize(\n self,\n stream: IO[bytes],\n base: Optional[str] = None,\n encoding: Optional[str] = None,\n spacious: Optional[bool] = None,\n **kwargs: Any,\n ) -> None:\n self.reset()\n self.stream = stream\n # if base is given here, use that, if not and a base is set for the graph use that\n if base is not None:\n self.base = base\n elif self.store.base is not None:\n self.base = self.store.base\n\n if spacious is not None:\n self._spacious = spacious\n\n self.preprocess()\n subjects_list = self.orderSubjects()\n\n self.startDocument()\n\n firstTime = True\n for subject in subjects_list:\n if self.isDone(subject):\n continue\n if firstTime:\n firstTime = False\n if self.statement(subject) and not firstTime:\n self.write(\"\\n\")\n\n self.endDocument()\n stream.write(\"\\n\".encode(\"latin-1\"))\n\n self.base = None\n\n def preprocessTriple(self, triple: _TripleType) -> None:\n super(TurtleSerializer, self).preprocessTriple(triple)\n for i, node in enumerate(triple):\n if i == VERB and node in self.keywords:\n # predicate is a keyword\n continue\n # Don't use generated prefixes for subjects and objects\n self.getQName(node, gen_prefix=(i == VERB))\n if isinstance(node, Literal) and node.datatype:\n self.getQName(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT)\n p = triple[1]\n if isinstance(p, BNode): # hmm - when is P ever a bnode?\n self._references[p] += 1\n\n # TODO: Rename to get_pname\n def getQName(self, uri: Node, gen_prefix: bool = True) -> Optional[str]:\n if not isinstance(uri, URIRef):\n return None\n\n parts = None\n\n try:\n parts = self.store.compute_qname(uri, generate=gen_prefix)\n except Exception:\n # is the uri a namespace in itself?\n pfx = self.store.store.prefix(uri)\n\n if pfx is not None:\n parts = (pfx, uri, \"\")\n else:\n # nothing worked\n return None\n\n prefix, namespace, local = parts\n\n local = local.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n\n # QName cannot end with .\n if local.endswith(\".\"):\n return None\n\n prefix = self.addNamespace(prefix, namespace)\n\n return \"%s:%s\" % (prefix, local)\n\n def startDocument(self) -> None:\n self._started = True\n ns_list = sorted(self.namespaces.items())\n\n if self.base:\n self.write(self.indent() + \"@base <%s> .\\n\" % self.base)\n for prefix, uri in ns_list:\n self.write(self.indent() + \"@prefix %s: <%s> .\\n\" % (prefix, uri))\n if ns_list and self._spacious:\n self.write(\"\\n\")\n\n def endDocument(self) -> None:\n if self._spacious:\n self.write(\"\\n\")\n\n def statement(self, subject: _SubjectType) -> bool:\n self.subjectDone(subject)\n return self.s_squared(subject) or self.s_default(subject)\n\n def s_default(self, subject: _SubjectType) -> bool:\n self.write(\"\\n\" + self.indent())\n self.path(subject, SUBJECT)\n self.predicateList(subject)\n self.write(\" .\")\n return True\n\n def s_squared(self, subject: _SubjectType) -> bool:\n if (self._references[subject] > 0) or not isinstance(subject, BNode):\n return False\n self.write(\"\\n\" + self.indent() + \"[]\")\n self.predicateList(subject)\n self.write(\" .\")\n return True\n\n def path(self, node: Node, position: int, newline: bool = False) -> None:\n if not (\n self.p_squared(node, position, newline)\n or self.p_default(node, position, newline)\n ):\n raise Error(\"Cannot serialize node '%s'\" % (node,))\n\n def p_default(self, node: Node, position: int, newline: bool = False) -> bool:\n if position != SUBJECT and not newline:\n self.write(\" \")\n self.write(self.label(node, position))\n return True\n\n def label(self, node: Node, position: int) -> str:\n if node == RDF.nil:\n return \"()\"\n if position is VERB and node in self.keywords:\n return self.keywords[node]\n if isinstance(node, Literal):\n return node._literal_n3(\n use_plain=True,\n qname_callback=lambda dt: self.getQName(dt, _GEN_QNAME_FOR_DT),\n )\n else:\n node = self.relativize(node) # type: ignore[type-var]\n\n return self.getQName(node, position == VERB) or node.n3()\n\n def p_squared(self, node: Node, position: int, newline: bool = False) -> bool:\n if (\n not isinstance(node, BNode)\n or node in self._serialized\n or self._references[node] > 1\n or position == SUBJECT\n ):\n return False\n\n if not newline:\n self.write(\" \")\n\n if self.isValidList(node):\n # this is a list\n self.write(\"(\")\n self.depth += 1 # 2\n self.doList(node)\n self.depth -= 1 # 2\n self.write(\" )\")\n else:\n self.subjectDone(node)\n self.depth += 2\n # self.write('[\\n' + self.indent())\n self.write(\"[\")\n self.depth -= 1\n # self.predicateList(node, newline=True)\n self.predicateList(node, newline=False)\n # self.write('\\n' + self.indent() + ']')\n self.write(\" ]\")\n self.depth -= 1\n\n return True\n\n def isValidList(self, l_: Node) -> bool:\n \"\"\"\n Checks if l is a valid RDF list, i.e. no nodes have other properties.\n \"\"\"\n try:\n if self.store.value(l_, RDF.first) is None:\n return False\n except Exception:\n return False\n while l_:\n if l_ != RDF.nil and len(list(self.store.predicate_objects(l_))) != 2:\n return False\n # type error: Incompatible types in assignment (expression has type \"Optional[Node]\", variable has type \"Node\")\n l_ = self.store.value(l_, RDF.rest) # type: ignore[assignment]\n return True\n\n def doList(self, l_: Node) -> None:\n while l_:\n item = self.store.value(l_, RDF.first)\n if item is not None:\n self.path(item, OBJECT)\n self.subjectDone(l_)\n # type error: Incompatible types in assignment (expression has type \"Optional[Node]\", variable has type \"Node\")\n l_ = self.store.value(l_, RDF.rest) # type: ignore[assignment]\n\n def predicateList(self, subject: Node, newline: bool = False) -> None:\n properties = self.buildPredicateHash(subject)\n propList = self.sortProperties(properties)\n if len(propList) == 0:\n return\n self.verb(propList[0], newline=newline)\n self.objectList(properties[propList[0]])\n for predicate in propList[1:]:\n self.write(\" ;\\n\" + self.indent(1))\n self.verb(predicate, newline=True)\n self.objectList(properties[predicate])\n\n def verb(self, node: Node, newline: bool = False) -> None:\n self.path(node, VERB, newline)\n\n def objectList(self, objects: Sequence[Node]) -> None:\n count = len(objects)\n if count == 0:\n return\n depthmod = (count == 1) and 0 or 1\n self.depth += depthmod\n self.path(objects[0], OBJECT)\n for obj in objects[1:]:\n self.write(\",\\n\" + self.indent(1))\n self.path(obj, OBJECT, newline=True)\n self.depth -= depthmod\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-49afac8c15ce", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-49afac8c15ce", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "1964642d472c4b44de6aba1a6fe3be6b9d7a8153", "source_files": ["rdflib/plugins/serializers/longturtle.py", "rdflib/plugins/serializers/turtle.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Internal ConjunctiveGraph warning displayed when processing JSON-LD\n\n## Description\nWhen processing JSON-LD data, an internal `ConjunctiveGraph` warning is unexpectedly displayed in the console or logs. This warning indicates the use of a deprecated component within the library. The expected behavior is that no such warning should appear, ensuring clean output and indicating up-to-date internal component usage.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `b459049af00b` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/parsers/jsonld.py\n```python\n\"\"\"\nThis parser will interpret a JSON-LD document as an RDF Graph. See http://json-ld.org/\n\nExample:\n ```python\n >>> from rdflib import Graph, URIRef, Literal\n >>> test_json = '''\n ... {\n ... \"@context\": {\n ... \"dc\": \"http://purl.org/dc/terms/\",\n ... \"rdf\": \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\n ... \"rdfs\": \"http://www.w3.org/2000/01/rdf-schema#\"\n ... },\n ... \"@id\": \"http://example.org/about\",\n ... \"dc:title\": {\n ... \"@language\": \"en\",\n ... \"@value\": \"Someone's Homepage\"\n ... }\n ... }\n ... '''\n >>> g = Graph().parse(data=test_json, format='json-ld')\n >>> list(g) == [(URIRef('http://example.org/about'),\n ... URIRef('http://purl.org/dc/terms/title'),\n ... Literal(\"Someone's Homepage\", lang='en'))]\n True\n\n ```\n\"\"\"\n\n# From: https://github.com/RDFLib/rdflib-jsonld/blob/feature/json-ld-1.1/rdflib_jsonld/parser.py\n\n# NOTE: This code reads the entire JSON object into memory before parsing, but\n# we should consider streaming the input to deal with arbitrarily large graphs.\nfrom __future__ import annotations\n\nimport secrets\nimport warnings\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union\n\nimport rdflib.parser\nfrom rdflib.graph import ConjunctiveGraph, Graph\nfrom rdflib.namespace import RDF, XSD\nfrom rdflib.parser import InputSource, URLInputSource\nfrom rdflib.term import BNode, IdentifiedNode, Literal, Node, URIRef\n\nfrom ..shared.jsonld.context import UNDEF, Context, Term\nfrom ..shared.jsonld.keys import (\n CONTEXT,\n GRAPH,\n ID,\n INCLUDED,\n INDEX,\n JSON,\n LANG,\n LIST,\n NEST,\n NONE,\n REV,\n SET,\n TYPE,\n VALUE,\n VOCAB,\n)\nfrom ..shared.jsonld.util import (\n _HAS_ORJSON,\n VOCAB_DELIMS,\n context_from_urlinputsource,\n json,\n orjson,\n source_to_json,\n)\n\n__all__ = [\"JsonLDParser\", \"to_rdf\"]\n\nTYPE_TERM = Term(str(RDF.type), TYPE, VOCAB) # type: ignore[call-arg]\n\nALLOW_LISTS_OF_LISTS = True # NOTE: Not allowed in JSON-LD 1.0\n\n\nclass JsonLDParser(rdflib.parser.Parser):\n def __init__(self):\n super(JsonLDParser, self).__init__()\n\n def parse(\n self,\n source: InputSource,\n sink: Graph,\n version: float = 1.1,\n skolemize: bool = False,\n encoding: Optional[str] = \"utf-8\",\n base: Optional[str] = None,\n context: Optional[\n Union[\n List[Union[Dict[str, Any], str, None]],\n Dict[str, Any],\n str,\n ]\n ] = None,\n generalized_rdf: Optional[bool] = False,\n extract_all_scripts: Optional[bool] = False,\n **kwargs: Any,\n ) -> None:\n \"\"\"Parse JSON-LD from a source document.\n\n The source document can be JSON or HTML with embedded JSON script\n elements (type attribute = `application/ld+json`). To process as HTML\n `source.content_type` must be set to \"text/html\" or\n `application/xhtml+xml.\n\n Args:\n source: InputSource with JSON-formatted data (JSON or HTML)\n sink: Graph to receive the parsed triples\n version: parse as JSON-LD version, defaults to 1.1\n skolemize: whether to skolemize blank nodes, defaults to False\n encoding: character encoding of the JSON (should be \"utf-8\"\n base: JSON-LD [Base IRI](https://www.w3.org/TR/json-ld/#base-iri), defaults to None\n context: JSON-LD [Context](https://www.w3.org/TR/json-ld/#the-context), defaults to None\n generalized_rdf: parse as [Generalized RDF](https://www.w3.org/TR/json-ld/#relationship-to-rdf), defaults to False\n extract_all_scripts: if source is an HTML document then extract\n script element). This is ignored if `source.system_id` contains\n a fragment identifier, in which case only the script element with\n matching id attribute is extracted.\n \"\"\"\n if encoding not in (\"utf-8\", \"utf-16\"):\n warnings.warn(\n \"JSON should be encoded as unicode. \"\n \"Given encoding was: %s\" % encoding\n )\n\n if not base:\n base = sink.absolutize(source.getPublicId() or source.getSystemId() or \"\")\n\n context_data = context\n if not context_data and hasattr(source, \"url\") and hasattr(source, \"links\"):\n if TYPE_CHECKING:\n assert isinstance(source, URLInputSource)\n context_data = context_from_urlinputsource(source)\n\n try:\n version = float(version)\n except ValueError:\n version = 1.1\n\n # Get the optional fragment identifier\n try:\n fragment_id = URIRef(source.getSystemId()).fragment\n except Exception:\n fragment_id = None\n\n data, html_base = source_to_json(source, fragment_id, extract_all_scripts)\n if html_base is not None:\n base = URIRef(html_base, base=base)\n\n # NOTE: A ConjunctiveGraph parses into a Graph sink, so no sink will be\n # context_aware. Keeping this check in case RDFLib is changed, or\n # someone passes something context_aware to this parser directly.\n conj_sink: Graph\n if not sink.context_aware:\n conj_sink = ConjunctiveGraph(store=sink.store, identifier=sink.identifier)\n else:\n conj_sink = sink\n\n to_rdf(\n data,\n conj_sink,\n base,\n context_data,\n version,\n bool(generalized_rdf),\n skolemize=skolemize,\n )\n\n\ndef to_rdf(\n data: Any,\n dataset: Graph,\n base: Optional[str] = None,\n context_data: Optional[\n Union[\n List[Union[Dict[str, Any], str, None]],\n Dict[str, Any],\n str,\n ]\n ] = None,\n version: Optional[float] = None,\n generalized_rdf: bool = False,\n allow_lists_of_lists: Optional[bool] = None,\n skolemize: bool = False,\n):\n # TODO: docstring w. args and return value\n context = Context(base=base, version=version)\n if context_data:\n context.load(context_data)\n parser = Parser(\n generalized_rdf=generalized_rdf,\n allow_lists_of_lists=allow_lists_of_lists,\n skolemize=skolemize,\n )\n return parser.parse(data, context, dataset)\n\n\nclass Parser:\n def __init__(\n self,\n generalized_rdf: bool = False,\n allow_lists_of_lists: Optional[bool] = None,\n skolemize: bool = False,\n ):\n self.skolemize = skolemize\n self.generalized_rdf = generalized_rdf\n self.allow_lists_of_lists = (\n allow_lists_of_lists\n if allow_lists_of_lists is not None\n else ALLOW_LISTS_OF_LISTS\n )\n self.invalid_uri_to_bnode: dict[str, BNode] = {}\n\n def parse(self, data: Any, context: Context, dataset: Graph) -> Graph:\n topcontext = False\n resources: Union[Dict[str, Any], List[Any]]\n if isinstance(data, list):\n resources = data\n elif isinstance(data, dict):\n local_context = data.get(CONTEXT)\n if local_context:\n context.load(local_context, context.base)\n topcontext = True\n resources = data\n # type error: Subclass of \"Dict[str, Any]\" and \"List[Any]\" cannot exist: would have incompatible method signatures\n if not isinstance(resources, list): # type: ignore[unreachable]\n resources = [resources]\n\n if context.vocab:\n dataset.bind(None, context.vocab)\n for name, term in context.terms.items():\n if term.id and term.id.endswith(VOCAB_DELIMS):\n dataset.bind(name, term.id)\n\n # type error: \"Graph\" has no attribute \"default_context\"\n graph = dataset.default_context if dataset.context_aware else dataset # type: ignore[attr-defined]\n\n for node in resources:\n self._add_to_graph(dataset, graph, context, node, topcontext)\n\n return graph\n\n def _add_to_graph(\n self,\n dataset: Graph,\n graph: Graph,\n context: Context,\n node: Any,\n topcontext: bool = False,\n ) -> Optional[Node]:\n if not isinstance(node, dict) or context.get_value(node):\n # type error: Return value expected\n return # type: ignore[return-value]\n\n if CONTEXT in node and not topcontext:\n local_context = node[CONTEXT]\n if local_context:\n context = context.subcontext(local_context)\n else:\n context = Context(base=context.doc_base)\n\n # type error: Incompatible types in assignment (expression has type \"Optional[Context]\", variable has type \"Context\")\n context = context.get_context_for_type(node) # type: ignore[assignment]\n\n id_val = context.get_id(node)\n\n if id_val is None:\n nested_id = self._get_nested_id(context, node)\n if nested_id is not None and len(nested_id) > 0:\n id_val = nested_id\n\n if isinstance(id_val, str):\n subj = self._to_rdf_id(context, id_val)\n else:\n subj = BNode()\n if self.skolemize:\n subj = subj.skolemize()\n\n if subj is None:\n return None\n\n # NOTE: crude way to signify that this node might represent a named graph\n no_id = id_val is None\n\n for key, obj in node.items():\n if key == CONTEXT or key in context.get_keys(ID):\n continue\n\n if key == REV or key in context.get_keys(REV):\n for rkey, robj in obj.items():\n self._key_to_graph(\n dataset,\n graph,\n context,\n subj,\n rkey,\n robj,\n reverse=True,\n no_id=no_id,\n )\n else:\n self._key_to_graph(dataset, graph, context, subj, key, obj, no_id=no_id)\n\n return subj\n\n # type error: Missing return statement\n def _get_nested_id(self, context: Context, node: Dict[str, Any]) -> Optional[str]: # type: ignore[return]\n for key, obj in node.items():\n if context.version >= 1.1 and key in context.get_keys(NEST):\n term = context.terms.get(key)\n if term and term.id is None:\n continue\n objs = obj if isinstance(obj, list) else [obj]\n for obj in objs:\n if not isinstance(obj, dict):\n continue\n id_val = context.get_id(obj)\n if not id_val:\n subcontext = context.get_context_for_term(\n context.terms.get(key)\n )\n id_val = self._get_nested_id(subcontext, obj)\n if isinstance(id_val, str):\n return id_val\n\n def _key_to_graph(\n self,\n dataset: Graph,\n graph: Graph,\n context: Context,\n subj: Node,\n key: str,\n obj: Any,\n reverse: bool = False,\n no_id: bool = False,\n ) -> None:\n if isinstance(obj, list):\n obj_nodes = obj\n else:\n obj_nodes = [obj]\n\n term = context.terms.get(key)\n if term:\n term_id = term.id\n if term.type == JSON:\n obj_nodes = [self._to_typed_json_value(obj)]\n elif LIST in term.container:\n obj_nodes = [self._expand_nested_list(obj_nodes)]\n elif isinstance(obj, dict):\n obj_nodes = self._parse_container(context, term, obj)\n else:\n term_id = None\n\n if TYPE in (key, term_id):\n term = TYPE_TERM\n\n if GRAPH in (key, term_id):\n if dataset.context_aware and not no_id:\n if TYPE_CHECKING:\n assert isinstance(dataset, ConjunctiveGraph)\n # type error: Argument 1 to \"get_context\" of \"ConjunctiveGraph\" has incompatible type \"Node\"; expected \"Union[IdentifiedNode, str, None]\"\n subgraph = dataset.get_context(subj) # type: ignore[arg-type]\n else:\n subgraph = graph\n for onode in obj_nodes:\n self._add_to_graph(dataset, subgraph, context, onode)\n return\n\n if SET in (key, term_id):\n for onode in obj_nodes:\n self._add_to_graph(dataset, graph, context, onode)\n return\n\n if INCLUDED in (key, term_id):\n for onode in obj_nodes:\n self._add_to_graph(dataset, graph, context, onode)\n return\n\n if context.version >= 1.1 and key in context.get_keys(NEST):\n term = context.terms.get(key)\n if term and term.id is None:\n return\n objs = obj if isinstance(obj, list) else [obj]\n for obj in objs:\n if not isinstance(obj, dict):\n continue\n for nkey, nobj in obj.items():\n # NOTE: we've already captured subject\n if nkey in context.get_keys(ID):\n continue\n subcontext = context.get_context_for_type(obj)\n # type error: Argument 3 to \"_key_to_graph\" of \"Parser\" has incompatible type \"Optional[Context]\"; expected \"Context\"\n self._key_to_graph(dataset, graph, subcontext, subj, nkey, nobj) # type: ignore[arg-type]\n return\n\n pred_uri = term.id if term else context.expand(key)\n\n context = context.get_context_for_term(term)\n\n # Flatten deep nested lists\n def flatten(n: Iterable[Any]) -> List[Any]:\n flattened = []\n for obj in n:\n if isinstance(obj, dict):\n objs = context.get_set(obj)\n if objs is not None:\n obj = objs\n if isinstance(obj, list):\n flattened += flatten(obj)\n continue\n flattened.append(obj)\n return flattened\n\n obj_nodes = flatten(obj_nodes)\n\n if not pred_uri:\n return\n\n if term and term.reverse:\n reverse = not reverse\n\n pred: IdentifiedNode\n bid = self._get_bnodeid(pred_uri)\n if bid:\n if not self.generalized_rdf:\n return\n pred = BNode(bid)\n if self.skolemize:\n pred = pred.skolemize()\n else:\n pred = URIRef(pred_uri)\n\n for obj_node in obj_nodes:\n obj = self._to_object(dataset, graph, context, term, obj_node)\n if obj is None:\n continue\n if reverse:\n graph.add((obj, pred, subj))\n else:\n graph.add((subj, pred, obj))\n\n def _parse_container(\n self, context: Context, term: Term, obj: Dict[str, Any]\n ) -> List[Any]:\n if LANG in term.container:\n obj_nodes = []\n for lang, values in obj.items():\n if not isinstance(values, list):\n values = [values]\n if lang in context.get_keys(NONE):\n obj_nodes += values\n else:\n for v in values:\n obj_nodes.append((v, lang))\n return obj_nodes\n\n v11 = context.version >= 1.1\n\n if v11 and GRAPH in term.container and ID in term.container:\n return [\n (\n dict({GRAPH: o})\n if k in context.get_keys(NONE)\n else dict({ID: k, GRAPH: o}) if isinstance(o, dict) else o\n \n... [truncated 8409 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-607e086b11a9", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-607e086b11a9", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "b459049af00b1cdd1453bf99344636b0cbc910df", "source_files": ["rdflib/plugins/parsers/jsonld.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Turtle/N3 serializers output undeclared prefixes for predicates matching the base URI\n\n## Description\nWhen serializing an RDF graph to Turtle, Long Turtle, or N3 format, if a base URI is set and a predicate URI contains that base URI as a substring (e.g., the predicate starts with the base URI), the serializer incorrectly outputs an undeclared prefix for that predicate.\n\nFor example, if the base URI is `http://example.org/base/` and a predicate is `http://example.org/base/something`, the output might contain `base:something` without `base` being declared as a prefix. This results in invalid Turtle/N3 output.\n\nThe expected behavior\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `2a902e512123` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/serializers/longturtle.py\n```python\n\"\"\"\nLongTurtle RDF graph serializer for RDFLib.\nSee for syntax specification.\n\nThis variant, longturtle as opposed to just turtle, makes some small format changes\nto turtle - the original turtle serializer. It:\n\n* uses PREFIX instead of @prefix\n* uses BASE instead of @base\n* adds a new line at RDF.type, or 'a'\n* adds a newline and an indent for all triples with more than one object (object list)\n* adds a new line and ';' for the last triple in a set with '.'\n on the start of the next line\n* uses default encoding (encode()) is used instead of \"latin-1\"\n\n- Nicholas Car, 2023\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import IO, Any, Optional\n\nfrom rdflib.compare import to_canonical_graph\nfrom rdflib.exceptions import Error\nfrom rdflib.graph import Graph, _TripleType\nfrom rdflib.namespace import RDF\nfrom rdflib.term import BNode, Literal, URIRef\n\nfrom .turtle import RecursiveSerializer\n\n__all__ = [\"LongTurtleSerializer\"]\n\nSUBJECT = 0\nVERB = 1\nOBJECT = 2\n\n_GEN_QNAME_FOR_DT = False\n_SPACIOUS_OUTPUT = False\n\n\nclass LongTurtleSerializer(RecursiveSerializer):\n \"\"\"LongTurtle, a Turtle serialization format.\n\n When the optional parameter ``canon`` is set to :py:obj:`True`, the graph is canonicalized\n before serialization. This normalizes blank node identifiers and allows for\n deterministic serialization of the graph. Useful when consistent outputs are required.\n \"\"\"\n\n short_name = \"longturtle\"\n indentString = \" \"\n\n def __init__(self, store):\n self._ns_rewrite = {}\n self._canon = False\n super(LongTurtleSerializer, self).__init__(store)\n self.keywords = {RDF.type: \"a\"}\n self.reset()\n self.stream = None\n self._spacious: bool = _SPACIOUS_OUTPUT\n\n def addNamespace(self, prefix, namespace):\n # Turtle does not support prefixes that start with _\n # if they occur in the graph, rewrite to p_blah\n # this is more complicated since we need to make sure p_blah\n # does not already exist. And we register namespaces as we go, i.e.\n # we may first see a triple with prefix _9 - rewrite it to p_9\n # and then later find a triple with a \"real\" p_9 prefix\n\n # so we need to keep track of ns rewrites we made so far.\n\n if (prefix > \"\" and prefix[0] == \"_\") or self.namespaces.get(\n prefix, namespace\n ) != namespace:\n if prefix not in self._ns_rewrite:\n p = \"p\" + prefix\n while p in self.namespaces:\n p = \"p\" + p\n self._ns_rewrite[prefix] = p\n\n prefix = self._ns_rewrite.get(prefix, prefix)\n\n super(LongTurtleSerializer, self).addNamespace(prefix, namespace)\n return prefix\n\n def canonize(self):\n \"\"\"Apply canonicalization to the store.\n\n This normalizes blank node identifiers and allows for deterministic\n serialization of the graph.\n \"\"\"\n if not self._canon:\n return\n\n namespace_manager = self.store.namespace_manager\n store = to_canonical_graph(self.store)\n content = store.serialize(format=\"application/n-triples\")\n lines = content.split(\"\\n\")\n lines.sort()\n graph = Graph()\n graph.parse(\n data=\"\\n\".join(lines), format=\"application/n-triples\", skolemize=True\n )\n graph = graph.de_skolemize()\n graph.namespace_manager = namespace_manager\n self.store = graph\n\n def reset(self):\n super(LongTurtleSerializer, self).reset()\n self._shortNames = {}\n self._started = False\n self._ns_rewrite = {}\n self.canonize()\n\n def serialize(\n self,\n stream: IO[bytes],\n base: Optional[str] = None,\n encoding: Optional[str] = None,\n spacious: Optional[bool] = None,\n **kwargs: Any,\n ) -> None:\n self._canon = kwargs.get(\"canon\", False)\n self.reset()\n self.stream = stream\n # if base is given here, use, if not and a base is set for the graph use that\n if base is not None:\n self.base = base\n elif self.store.base is not None:\n self.base = self.store.base\n\n if spacious is not None:\n self._spacious = spacious\n\n self.preprocess()\n subjects_list = self.orderSubjects()\n\n self.startDocument()\n\n firstTime = True\n for subject in subjects_list:\n if self.isDone(subject):\n continue\n if firstTime:\n firstTime = False\n if self.statement(subject) and not firstTime:\n self.write(\"\\n\")\n\n self.endDocument()\n\n self.base = None\n\n def preprocessTriple(self, triple: _TripleType) -> None:\n super(LongTurtleSerializer, self).preprocessTriple(triple)\n for i, node in enumerate(triple):\n if i == VERB:\n if node in self.keywords:\n # predicate is a keyword\n continue\n if (\n self.base is not None\n and isinstance(node, URIRef)\n and node.startswith(self.base)\n ):\n # predicate corresponds to base namespace\n continue\n # Don't use generated prefixes for subjects and objects\n self.getQName(node, gen_prefix=(i == VERB))\n if isinstance(node, Literal) and node.datatype:\n self.getQName(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT)\n p = triple[1]\n if isinstance(p, BNode): # hmm - when is P ever a bnode?\n self._references[p] += 1\n\n def getQName(self, uri, gen_prefix=True):\n if not isinstance(uri, URIRef):\n return None\n\n try:\n parts = self.store.compute_qname(uri, generate=gen_prefix)\n except Exception:\n # is the uri a namespace in itself?\n pfx = self.store.store.prefix(uri)\n\n if pfx is not None:\n parts = (pfx, uri, \"\")\n else:\n # nothing worked\n return None\n\n prefix, namespace, local = parts\n\n local = local.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n\n # QName cannot end with .\n if local.endswith(\".\"):\n return None\n\n prefix = self.addNamespace(prefix, namespace)\n\n return \"%s:%s\" % (prefix, local)\n\n def startDocument(self):\n self._started = True\n ns_list = sorted(self.namespaces.items())\n\n if self.base:\n self.write(self.indent() + \"BASE <%s>\\n\" % self.base)\n for prefix, uri in ns_list:\n self.write(self.indent() + \"PREFIX %s: <%s>\\n\" % (prefix, uri))\n if ns_list and self._spacious:\n self.write(\"\\n\")\n\n def endDocument(self):\n if self._spacious:\n self.write(\"\\n\")\n\n def statement(self, subject):\n self.subjectDone(subject)\n return self.s_squared(subject) or self.s_default(subject)\n\n def s_default(self, subject):\n self.write(\"\\n\" + self.indent())\n self.path(subject, SUBJECT)\n self.write(\"\\n\" + self.indent())\n self.predicateList(subject)\n self.write(\"\\n.\")\n return True\n\n def s_squared(self, subject):\n if (self._references[subject] > 0) or not isinstance(subject, BNode):\n return False\n self.write(\"\\n\" + self.indent() + \"[]\")\n self.predicateList(subject, newline=False)\n self.write(\"\\n.\")\n return True\n\n def path(self, node, position, newline=False):\n if not (\n self.p_squared(node, position) or self.p_default(node, position, newline)\n ):\n raise Error(\"Cannot serialize node '%s'\" % (node,))\n\n def p_default(self, node, position, newline=False):\n if position != SUBJECT and not newline:\n self.write(\" \")\n self.write(self.label(node, position))\n return True\n\n def label(self, node, position):\n if node == RDF.nil:\n return \"()\"\n if position is VERB and node in self.keywords:\n return self.keywords[node]\n if isinstance(node, Literal):\n return node._literal_n3(\n use_plain=True,\n qname_callback=lambda dt: self.getQName(dt, _GEN_QNAME_FOR_DT),\n )\n else:\n node = self.relativize(node)\n\n return self.getQName(node, position == VERB) or node.n3()\n\n def p_squared(\n self,\n node,\n position,\n ):\n if (\n not isinstance(node, BNode)\n or node in self._serialized\n or self._references[node] > 1\n or position == SUBJECT\n ):\n return False\n\n if self.isValidList(node):\n # this is a list\n self.depth += 2\n self.write(\" (\\n\")\n self.depth -= 2\n self.doList(node)\n self.write(\"\\n\" + self.indent() + \")\")\n else:\n # this is a Blank Node\n self.subjectDone(node)\n self.write(\"\\n\" + self.indent(1) + \"[\\n\")\n self.depth += 1\n self.predicateList(node)\n self.depth -= 1\n self.write(\"\\n\" + self.indent(1) + \"]\")\n\n return True\n\n def isValidList(self, l_):\n \"\"\"\n Checks if l is a valid RDF list, i.e. no nodes have other properties.\n \"\"\"\n try:\n if self.store.value(l_, RDF.first) is None:\n return False\n except Exception:\n return False\n while l_:\n if l_ != RDF.nil and len(list(self.store.predicate_objects(l_))) != 2:\n return False\n l_ = self.store.value(l_, RDF.rest)\n return True\n\n def doList(self, l_):\n i = 0\n while l_:\n item = self.store.value(l_, RDF.first)\n if item is not None:\n if i == 0:\n self.write(self.indent(1))\n else:\n self.write(\"\\n\" + self.indent(1))\n self.path(item, OBJECT, newline=True)\n self.subjectDone(l_)\n l_ = self.store.value(l_, RDF.rest)\n i += 1\n\n def predicateList(self, subject, newline=False):\n properties = self.buildPredicateHash(subject)\n propList = self.sortProperties(properties)\n if len(propList) == 0:\n return\n self.write(self.indent(1))\n self.verb(propList[0], newline=True)\n self.objectList(properties[propList[0]])\n for predicate in propList[1:]:\n self.write(\" ;\\n\" + self.indent(1))\n self.verb(predicate, newline=True)\n self.objectList(properties[predicate])\n self.write(\" ;\")\n\n def verb(self, node, newline=False):\n self.path(node, VERB, newline)\n\n def objectList(self, objects):\n count = len(objects)\n if count == 0:\n return\n depthmod = (count == 1) and 0 or 1\n self.depth += depthmod\n first_nl = False\n if count > 1:\n if not isinstance(objects[0], BNode):\n self.write(\"\\n\" + self.indent(1))\n else:\n self.write(\" \")\n first_nl = True\n self.path(objects[0], OBJECT, newline=first_nl)\n for obj in objects[1:]:\n self.write(\" ,\")\n if not isinstance(obj, BNode):\n self.write(\"\\n\" + self.indent(1))\n self.path(obj, OBJECT, newline=True)\n self.depth -= depthmod\n\n```\n\n### rdflib/plugins/serializers/turtle.py\n```python\n\"\"\"\nTurtle RDF graph serializer for RDFLib.\nSee for syntax specification.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n DefaultDict,\n Dict,\n List,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n)\n\nfrom rdflib.exceptions import Error\nfrom rdflib.graph import Graph\nfrom rdflib.namespace import RDF, RDFS\nfrom rdflib.serializer import Serializer\nfrom rdflib.term import BNode, Literal, Node, URIRef\n\nif TYPE_CHECKING:\n from rdflib.graph import _PredicateType, _SubjectType, _TripleType\n\n__all__ = [\"RecursiveSerializer\", \"TurtleSerializer\"]\n\n\nclass RecursiveSerializer(Serializer):\n topClasses = [RDFS.Class]\n predicateOrder = [RDF.type, RDFS.label]\n maxDepth = 10\n indentString = \" \"\n roundtrip_prefixes: Tuple[Any, ...] = ()\n\n def __init__(self, store: Graph):\n super(RecursiveSerializer, self).__init__(store)\n self.stream: Optional[IO[bytes]] = None\n self.reset()\n\n def addNamespace(self, prefix: str, uri: URIRef) -> None:\n if prefix in self.namespaces and self.namespaces[prefix] != uri:\n raise Exception(\n \"Trying to override namespace prefix %s => %s, but it's already bound to %s\"\n % (prefix, uri, self.namespaces[prefix])\n )\n self.namespaces[prefix] = uri\n\n def checkSubject(self, subject: _SubjectType) -> bool:\n \"\"\"Check to see if the subject should be serialized yet\"\"\"\n if (\n (self.isDone(subject))\n or (subject not in self._subjects)\n or ((subject in self._topLevels) and (self.depth > 1))\n or (isinstance(subject, URIRef) and (self.depth >= self.maxDepth))\n ):\n return False\n return True\n\n def isDone(self, subject: _SubjectType) -> bool:\n \"\"\"Return true if subject is serialized\"\"\"\n return subject in self._serialized\n\n def orderSubjects(self) -> List[_SubjectType]:\n seen: Dict[_SubjectType, bool] = {}\n subjects: List[_SubjectType] = []\n\n for classURI in self.topClasses:\n members = list(self.store.subjects(RDF.type, classURI))\n members.sort()\n\n subjects.extend(members)\n for member in members:\n self._topLevels[member] = True\n seen[member] = True\n\n recursable = [\n (isinstance(subject, BNode), self._references[subject], subject)\n for subject in self._subjects\n if subject not in seen\n ]\n\n recursable.sort()\n subjects.extend([subject for (isbnode, refs, subject) in recursable])\n\n return subjects\n\n def preprocess(self) -> None:\n for triple in self.store.triples((None, None, None)):\n self.preprocessTriple(triple)\n\n def preprocessTriple(self, spo: _TripleType) -> None:\n s, p, o = spo\n self._references[o] += 1\n self._subjects[s] = True\n\n def reset(self) -> None:\n self.depth = 0\n # Typed none because nothing is using it ...\n self.lists: Dict[None, None] = {}\n self.namespaces: Dict[str, URIRef] = {}\n self._references: DefaultDict[Node, int] = defaultdict(int)\n self._serialized: Dict[_SubjectType, bool] = {}\n self._subjects: Dict[_SubjectType, bool] = {}\n self._topLevels: Dict[_SubjectType, bool] = {}\n\n if self.roundtrip_prefixes:\n if hasattr(self.roundtrip_prefixes, \"__iter__\"):\n for prefix, ns in self.store.namespaces():\n if prefix in self.roundtrip_prefixes:\n self.addNamespace(prefix, ns)\n else:\n for prefix, ns in self.store.namespaces():\n self.addNamespace(prefix, ns)\n\n def buildPredicateHash(\n self, subject: _SubjectType\n ) -> Mapping[_PredicateType, List[Node]]:\n \"\"\"\n Build a hash key by predicate to a list of objects for the given\n subject\n \"\"\"\n properties: Dict[_PredicateType, List[Node]] = {}\n for s, p, o in self.store.triples((subject, None, None)):\n oList = properties.get(p, [])\n oList.append(o)\n properties[p] = oList\n return properties\n\n def sortProperties(\n self, properties: Mapping[_PredicateType, List[Node]]\n ) -> List[_PredicateType]:\n \"\"\"Take a hash from predicate uris to lists of values.\n Sort the lists of values. Return a sorted list of properties.\"\"\"\n # Sort object lists\n for prop, objects in properties.items():\n objects.sort()\n\n # Make sorted list of properties\n propList: List[_PredicateType] = []\n seen: Dict[_PredicateType, bool] = {}\n for prop in self.predicateOrder:\n if (prop in properties) and (prop not in seen):\n propList.append(prop)\n seen[prop] = True\n props = list(properties.keys())\n props.sort()\n for prop in props:\n if prop not in seen:\n propList.append(prop)\n seen[prop] = True\n return propList\n\n def subjectDone(self, subject: _SubjectType) -> None:\n \"\"\"Mark a subject as done.\"\"\"\n self._serialized[subject] = True\n\n def indent(self, modifier: int = 0) -> str:\n \"\"\"Returns indent string multiplied by the depth\"\"\"\n return (self.depth + modifier) * self.indentString\n\n def write(self, text: str) -> None:\n \"\"\"Write text in given encoding.\"\"\"\n # type error: Item \"None\" of \"Optional[IO[bytes]]\" has no attribute \"write\"\n self.stream.write(text.encode(self.encoding, \"replace\")) # type: ignore[union-attr]\n\n\nSUBJECT = 0\nVERB = 1\nOBJECT = 2\n\n_GEN_QNAME_FOR_DT = False\n_SPACIOUS_OUTPUT = False\n\n\nclass TurtleSerializer(RecursiveSerializer):\n short_name = \"turtle\"\n indentString = \" \"\n\n def __init__(self, store: Graph):\n self._ns_rewrite: Dict[str, str] = {}\n super(TurtleSerializer, self).__init__(store)\n self.keywords: Dict[Node, str] = {RDF.type: \"a\"}\n self.reset()\n self.stream = None\n self._spacious = _SPACIOUS_OUTPUT\n\n # type error: Return type \"str\" of \"addNamespace\" incompatible with return type \"None\" in supertype \"RecursiveSerializer\"\n def addNamespace(self, prefix: str, namespace: URIRef) -> str: # type: ignore[override]\n # Turtle does not support prefix that start with _\n # if they occur in the graph, rewrite to p_blah\n # this is more complicated since we need to make sure p_blah\n # does not already exist. And we register namespaces as we go, i.e.\n # we may first see a triple with prefix _9 - rewrite it to p_9\n # and then later find a triple with a \"real\" p_9 prefix\n\n # so we need to keep track of ns rewrites we made so far.\n\n if (prefix > \"\" and prefix[0] == \"_\") or self.namespaces.get(\n prefix, namespace\n ) != namespace:\n if prefix not in self._ns_rewrite:\n p = \"p\" + prefix\n while p in self.namespaces:\n p = \"p\" + p\n self._ns_rewrite[prefix] = p\n\n prefix = self._ns_rewrite.get(prefix, prefix)\n\n super(TurtleSerializer, self).addNamespace(prefix, namespace)\n return prefix\n\n def reset(self) -> None:\n super(TurtleSerializer, self).reset()\n # typing as Dict[None, None] because nothing seems to be using it\n self._shortNames: Dict[None, None] = {}\n self._started = False\n self._ns_rewrite = {}\n\n def serialize(\n self,\n stream: IO[bytes],\n base: Optional[str] = None,\n encoding: Optional[str] = None,\n spacious: Optional[bool] = None,\n **kwargs: Any,\n ) -> None:\n self.reset()\n self.stream = stream\n # if base is given here, use that, if not and a base is set for the graph use that\n if base is not None:\n self.base = base\n elif self.store.base is not None:\n self.base = self.store.base\n\n if spacious is not None:\n self._spacious = spacious\n\n self.preprocess()\n subjects_list = self.orderSubjects()\n\n self.startDocument()\n\n firstTime = True\n for subject in subjects_list:\n if self.isDone(subject):\n continue\n if firstTime:\n firstTime = False\n if self.statement(subject) and not firstTime:\n self.write(\"\\n\")\n\n self.endDocument()\n stream.write(\"\\n\".encode(\"latin-1\"))\n\n self.base = None\n\n def preprocessTriple(self, triple: _TripleType) -> None:\n super(TurtleSerializer, self).preprocessTriple(triple)\n for i, node in enumerate(triple):\n if i == VERB:\n if node in self.keywords:\n # predicate is a keyword\n continue\n if (\n self.base is not None\n and isinstance(node, URIRef)\n and node.startswith(self.base)\n ):\n # predicate corresponds to base namespace\n continue\n # Don't use generated prefixes for subjects and objects\n self.getQName(node, gen_prefix=(i == VERB))\n if isinstance(node, Literal) and node.datatype:\n self.getQName(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT)\n p = triple[1]\n if isinstance(p, BNode): # hmm - when is P ever a bnode?\n self._references[p] += 1\n\n # TODO: Rename to get_pname\n def getQName(self, uri: Node, gen_prefix: bool = True) -> Optional[str]:\n if not isinstance(uri, URIRef):\n return None\n\n parts = None\n\n try:\n parts = self.store.compute_qname(uri, generate=gen_prefix)\n except Exception:\n # is the uri a namespace in itself?\n pfx = self.store.store.prefix(uri)\n\n if pfx is not None:\n parts = (pfx, uri, \"\")\n else:\n # nothing worked\n return None\n\n prefix, namespace, local = parts\n\n local = local.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n\n # QName cannot end with .\n if local.endswith(\".\"):\n return None\n\n prefix = self.addNamespace(prefix, namespace)\n\n return \"%s:%s\" % (prefix, local)\n\n def startDocument(self) -> None:\n self._started = True\n ns_list = sorted(self.namespaces.items())\n\n if self.base:\n self.write(self.indent() + \"@base <%s> .\\n\" % self.base)\n for prefix, uri in ns_list:\n self.write(self.indent() + \"@prefix %s: <%s> .\\n\" % (prefix, uri))\n if ns_list and self._spacious:\n self.write(\"\\n\")\n\n def endDocument(self) -> None:\n if self._spacious:\n self.write(\"\\n\")\n\n def statement(self, subject: _SubjectType) -> bool:\n self.subjectDone(subject)\n return self.s_squared(subject) or self.s_default(subject)\n\n def s_default(self, subject: _SubjectType) -> bool:\n self.write(\"\\n\" + self.indent())\n self.path(subject, SUBJECT)\n self.predicateList(subject)\n self.write(\" .\")\n return True\n\n def s_squared(self, subject: _SubjectType) -> bool:\n if (self._references[subject] > 0) or not isinstance(subject, BNode):\n return False\n self.write(\"\\n\" + self.indent() + \"[]\")\n self.predicateList(subject)\n self.write(\" .\")\n return True\n\n def path(self, node: Node, position: int, newline: bool = False) -> None:\n if not (\n self.p_squared(node, position, newline)\n or self.p_default(node, position, newline)\n ):\n raise Error(\"Cannot serialize node '%s'\" % (node,))\n\n def p_default(self, node: Node, position: int, newline: bool = False) -> bool:\n if position != SUBJECT and not newline:\n self.write(\" \")\n self.write(self.label(node, position))\n return True\n\n def label(self, node: Node, position: int) -> str:\n if node == RDF.nil:\n return \"()\"\n if position is VERB and node in self.keywords:\n return self.keywords[node]\n if isinstance(node, Literal):\n return node._literal_n3(\n use_plain=True,\n qname_callback=lambda dt: self.getQName(dt, _GEN_QNAME_FOR_DT),\n )\n else:\n node = self.relativize(node) # type: ignore[type-var]\n\n return self.getQName(node, position == VERB) or node.n3()\n\n def p_squared(self, node: Node, position: int, newline: bool = False) -> bool:\n if (\n not isinstance(node, BNode)\n or node in self._serialized\n or self._references[node] > 1\n or position == SUBJECT\n ):\n return False\n\n if not newline:\n self.write(\" \")\n\n if self.isValidList(node):\n # this is a list\n self.write(\"(\")\n self.depth += 1 # 2\n self.doList(node)\n self.depth -= 1 # 2\n self.write(\" )\")\n else:\n self.subjectDone(node)\n self.depth += 2\n # self.write('[\\n' + self.indent())\n self.write(\"[\")\n self.depth -= 1\n # self.predicateList(node, newline=True)\n self.predicateList(node, newline=False)\n # self.write('\\n' + self.indent() + ']')\n self.write(\" ]\")\n self.depth -= 1\n\n return True\n\n def isValidList(self, l_: Node) -> bool:\n \"\"\"\n Checks if l is a valid RDF list, i.e. no nodes have other properties.\n \"\"\"\n try:\n if self.store.value(l_, RDF.first) is None:\n return False\n except Exception:\n return False\n while l_:\n if l_ != RDF.nil and len(list(self.store.predicate_objects(l_))) != 2:\n return False\n # type error: Incompatible types in assignment (expression has type \"Optional[Node]\", variable has type \"Node\")\n l_ = self.store.value(l_, RDF.rest) # type: ignore[assignment]\n return True\n\n def doList(self, l_: Node) -> None:\n while l_:\n item = self.store.value(l_, RDF.first)\n if item is not None:\n self.path(item, OBJECT)\n self.subjectDone(l_)\n # type error: Incompatible types in assignment (expression has type \"Optional[Node]\", variable has type \"Node\")\n l_ = self.store.value(l_, RDF.rest) # type: ignore[assignment]\n\n def predicateList(self, subject: Node, newline: bool = False) -> None:\n properties = self.buildPredicateHash(subject)\n propList = self.sortProperties(properties)\n if len(propList) == 0:\n return\n self.verb(propList[0], newline=newline)\n self.objectList(properties[propList[0]])\n for predicate in propList[1:]:\n self.write(\" ;\\n\" + self.indent(1))\n self.verb(predicate, newline=True)\n self.objectList(properties[predicate])\n\n def verb(self, node: Node, newline: bool = False) -> None:\n self.path(node, VERB, newline)\n\n def objectList(self, objects: Sequence[Node]) -> None:\n count = len(objects)\n if count == 0:\n return\n depthmod = (count == 1) and 0 or 1\n self.depth += depthmod\n self.path(objects[0], OBJECT)\n for obj in objects[1:]:\n self.write(\",\\n\" + self.indent(1))\n self.path(obj, OBJECT, newline=True)\n self.depth -= depthmod\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-72287e45ad1a", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-72287e45ad1a", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "2a902e512123d1b9a8035fa1652aa3d0a0a918a4", "source_files": ["rdflib/plugins/serializers/longturtle.py", "rdflib/plugins/serializers/turtle.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Incorrect \"changed size\" reported or unstable iteration when processing store graphs\n\n## Description\nWhen iterating through the graphs within the store, the \"changed size\" metric is not being updated or reported accurately. Additionally, the iteration process itself appears unstable, potentially leading to inconsistent results or missed items. Expected behavior is that iterating over the store's graphs should reliably and accurately reflect the \"changed size\" and provide a stable, consistent traversal of all graphs.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `9b14b8f97994` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/stores/memory.py\n```python\n#\n#\nfrom __future__ import annotations\n\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Collection,\n Dict,\n Generator,\n Iterator,\n Mapping,\n Optional,\n Set,\n Tuple,\n Union,\n overload,\n)\n\nfrom rdflib.store import Store\nfrom rdflib.util import _coalesce\n\nif TYPE_CHECKING:\n from rdflib.graph import (\n Graph,\n _ContextType,\n _ObjectType,\n _PredicateType,\n _SubjectType,\n _TriplePatternType,\n _TripleType,\n )\n from rdflib.plugins.sparql.sparql import Query, Update\n from rdflib.query import Result\n from rdflib.term import Identifier, URIRef\n\n__all__ = [\"SimpleMemory\", \"Memory\"]\n\nANY: None = None\n\n\nclass SimpleMemory(Store):\n \"\"\"A fast naive in memory implementation of a triple store.\n\n This triple store uses nested dictionaries to store triples. Each\n triple is stored in two such indices as follows `spo[s][p][o]` = 1 and\n `pos[p][o][s]` = 1.\n\n Authors: Michel Pelletier, Daniel Krech, Stefan Niederhauser\n \"\"\"\n\n def __init__(\n self,\n configuration: Optional[str] = None,\n identifier: Optional[Identifier] = None,\n ):\n super(SimpleMemory, self).__init__(configuration)\n self.identifier = identifier\n\n # indexed by [subject][predicate][object]\n self.__spo: Dict[_SubjectType, Dict[_PredicateType, Dict[_ObjectType, int]]] = (\n {}\n )\n\n # indexed by [predicate][object][subject]\n self.__pos: Dict[_PredicateType, Dict[_ObjectType, Dict[_SubjectType, int]]] = (\n {}\n )\n\n # indexed by [predicate][object][subject]\n self.__osp: Dict[_ObjectType, Dict[_SubjectType, Dict[_PredicateType, int]]] = (\n {}\n )\n\n self.__namespace: Dict[str, URIRef] = {}\n self.__prefix: Dict[URIRef, str] = {}\n\n def add(\n self,\n triple: _TripleType,\n context: _ContextType,\n quoted: bool = False,\n ) -> None:\n \"\"\"Add a triple to the store of triples.\"\"\"\n # add dictionary entries for spo[s][p][p] = 1 and pos[p][o][s]\n # = 1, creating the nested dictionaries where they do not yet\n # exits.\n subject, predicate, object = triple\n spo = self.__spo\n try:\n po = spo[subject]\n except: # noqa: E722\n po = spo[subject] = {}\n try:\n o = po[predicate]\n except: # noqa: E722\n o = po[predicate] = {}\n o[object] = 1\n\n pos = self.__pos\n try:\n os = pos[predicate]\n except: # noqa: E722\n os = pos[predicate] = {}\n try:\n s = os[object]\n except: # noqa: E722\n s = os[object] = {}\n s[subject] = 1\n\n osp = self.__osp\n try:\n sp = osp[object]\n except: # noqa: E722\n sp = osp[object] = {}\n try:\n p = sp[subject]\n except: # noqa: E722\n p = sp[subject] = {}\n p[predicate] = 1\n\n def remove(\n self,\n triple_pattern: _TriplePatternType,\n context: Optional[_ContextType] = None,\n ) -> None:\n for (subject, predicate, object), c in list(self.triples(triple_pattern)):\n del self.__spo[subject][predicate][object]\n del self.__pos[predicate][object][subject]\n del self.__osp[object][subject][predicate]\n\n def triples(\n self,\n triple_pattern: _TriplePatternType,\n context: Optional[_ContextType] = None,\n ) -> Iterator[Tuple[_TripleType, Iterator[Optional[_ContextType]]]]:\n \"\"\"A generator over all the triples matching\"\"\"\n subject, predicate, object = triple_pattern\n if subject != ANY: # subject is given\n spo = self.__spo\n if subject in spo:\n subjectDictionary = spo[subject] # noqa: N806\n if predicate != ANY: # subject+predicate is given\n if predicate in subjectDictionary:\n if object != ANY: # subject+predicate+object is given\n if object in subjectDictionary[predicate]:\n yield (subject, predicate, object), self.__contexts()\n else: # given object not found\n pass\n else: # subject+predicate is given, object unbound\n for o in subjectDictionary[predicate].keys():\n yield (subject, predicate, o), self.__contexts()\n else: # given predicate not found\n pass\n else: # subject given, predicate unbound\n for p in subjectDictionary.keys():\n if object != ANY: # object is given\n if object in subjectDictionary[p]:\n yield (subject, p, object), self.__contexts()\n else: # given object not found\n pass\n else: # object unbound\n for o in subjectDictionary[p].keys():\n yield (subject, p, o), self.__contexts()\n else: # given subject not found\n pass\n elif predicate != ANY: # predicate is given, subject unbound\n pos = self.__pos\n if predicate in pos:\n predicateDictionary = pos[predicate] # noqa: N806\n if object != ANY: # predicate+object is given, subject unbound\n if object in predicateDictionary:\n for s in predicateDictionary[object].keys():\n yield (s, predicate, object), self.__contexts()\n else: # given object not found\n pass\n else: # predicate is given, object+subject unbound\n for o in predicateDictionary.keys():\n for s in predicateDictionary[o].keys():\n yield (s, predicate, o), self.__contexts()\n elif object != ANY: # object is given, subject+predicate unbound\n osp = self.__osp\n if object in osp:\n objectDictionary = osp[object] # noqa: N806\n for s in objectDictionary.keys():\n for p in objectDictionary[s].keys():\n yield (s, p, object), self.__contexts()\n else: # subject+predicate+object unbound\n spo = self.__spo\n for s in spo.keys():\n subjectDictionary = spo[s] # noqa: N806\n for p in subjectDictionary.keys():\n for o in subjectDictionary[p].keys():\n yield (s, p, o), self.__contexts()\n\n def __len__(self, context: Optional[_ContextType] = None) -> int:\n # @@ optimize\n i = 0\n for triple in self.triples((None, None, None)):\n i += 1\n return i\n\n def bind(self, prefix: str, namespace: URIRef, override: bool = True) -> None:\n # should be identical to `Memory.bind`\n bound_namespace = self.__namespace.get(prefix)\n bound_prefix = _coalesce(\n self.__prefix.get(namespace),\n # type error: error: Argument 1 to \"get\" of \"Mapping\" has incompatible type \"Optional[URIRef]\"; expected \"URIRef\"\n self.__prefix.get(bound_namespace), # type: ignore[arg-type]\n )\n if override:\n if bound_prefix is not None:\n del self.__namespace[bound_prefix]\n if bound_namespace is not None:\n del self.__prefix[bound_namespace]\n self.__prefix[namespace] = prefix\n self.__namespace[prefix] = namespace\n else:\n # type error: Invalid index type \"Optional[URIRef]\" for \"Dict[URIRef, str]\"; expected type \"URIRef\"\n self.__prefix[_coalesce(bound_namespace, namespace)] = _coalesce( # type: ignore[index]\n bound_prefix, default=prefix\n )\n # type error: Invalid index type \"Optional[str]\" for \"Dict[str, URIRef]\"; expected type \"str\"\n self.__namespace[_coalesce(bound_prefix, prefix)] = _coalesce( # type: ignore[index]\n bound_namespace, default=namespace\n )\n\n def namespace(self, prefix: str) -> Optional[URIRef]:\n return self.__namespace.get(prefix, None)\n\n def prefix(self, namespace: URIRef) -> Optional[str]:\n return self.__prefix.get(namespace, None)\n\n def namespaces(self) -> Iterator[Tuple[str, URIRef]]:\n for prefix, namespace in self.__namespace.items():\n yield prefix, namespace\n\n def __contexts(self) -> Generator[_ContextType, None, None]:\n # TODO: best way to return empty generator\n # type error: Need type annotation for \"c\"\n return (c for c in []) # type: ignore[var-annotated]\n\n # type error: Missing return statement\n def query( # type: ignore[return]\n self,\n query: Union[Query, str],\n initNs: Mapping[str, Any], # noqa: N803\n initBindings: Mapping[str, Identifier], # noqa: N803\n queryGraph: str, # noqa: N803\n **kwargs: Any,\n ) -> Result:\n super(SimpleMemory, self).query(\n query, initNs, initBindings, queryGraph, **kwargs\n )\n\n def update(\n self,\n update: Union[Update, str],\n initNs: Mapping[str, Any], # noqa: N803\n initBindings: Mapping[str, Identifier], # noqa: N803\n queryGraph: str, # noqa: N803\n **kwargs: Any,\n ) -> None:\n super(SimpleMemory, self).update(\n update, initNs, initBindings, queryGraph, **kwargs\n )\n\n\nclass Memory(Store):\n \"\"\"An in memory implementation of a triple store.\n\n Same as SimpleMemory above, but is Context-aware, Graph-aware, and Formula-aware\n Authors: Ashley Sommer\n \"\"\"\n\n context_aware = True\n formula_aware = True\n graph_aware = True\n\n def __init__(\n self,\n configuration: Optional[str] = None,\n identifier: Optional[Identifier] = None,\n ):\n super(Memory, self).__init__(configuration)\n self.identifier = identifier\n\n # indexed by [subject][predicate][object]\n self.__spo: Dict[_SubjectType, Dict[_PredicateType, Dict[_ObjectType, int]]] = (\n {}\n )\n\n # indexed by [predicate][object][subject]\n self.__pos: Dict[_PredicateType, Dict[_ObjectType, Dict[_SubjectType, int]]] = (\n {}\n )\n\n # indexed by [predicate][object][subject]\n self.__osp: Dict[_ObjectType, Dict[_SubjectType, Dict[_PredicateType, int]]] = (\n {}\n )\n\n self.__namespace: Dict[str, URIRef] = {}\n self.__prefix: Dict[URIRef, str] = {}\n self.__context_obj_map: Dict[str, Graph] = {}\n self.__tripleContexts: Dict[_TripleType, Dict[Optional[str], bool]] = {}\n self.__contextTriples: Dict[Optional[str], Set[_TripleType]] = {None: set()}\n # all contexts used in store (unencoded)\n self.__all_contexts: Set[Graph] = set()\n # default context information for triples\n self.__defaultContexts: Optional[Dict[Optional[str], bool]] = None\n\n def add(\n self,\n triple: _TripleType,\n context: _ContextType,\n quoted: bool = False,\n ) -> None:\n \"\"\"Add a triple to the store of triples.\"\"\"\n # add dictionary entries for spo[s][p][p] = 1 and pos[p][o][s]\n # = 1, creating the nested dictionaries where they do not yet\n # exits.\n Store.add(self, triple, context, quoted=quoted)\n if context is not None:\n self.__all_contexts.add(context)\n subject, predicate, object_ = triple\n\n spo = self.__spo\n try:\n po = spo[subject]\n except LookupError:\n po = spo[subject] = {}\n try:\n o = po[predicate]\n except LookupError:\n o = po[predicate] = {}\n\n try:\n _ = o[object_]\n # This cannot be reached if (s, p, o) was not inserted before.\n triple_exists = True\n except KeyError:\n o[object_] = 1\n triple_exists = False\n self.__add_triple_context(triple, triple_exists, context, quoted)\n\n if triple_exists:\n # No need to insert twice this triple.\n return\n\n pos = self.__pos\n try:\n os = pos[predicate]\n except LookupError:\n os = pos[predicate] = {}\n try:\n s = os[object_]\n except LookupError:\n s = os[object_] = {}\n s[subject] = 1\n\n osp = self.__osp\n try:\n sp = osp[object_]\n except LookupError:\n sp = osp[object_] = {}\n try:\n p = sp[subject]\n except LookupError:\n p = sp[subject] = {}\n p[predicate] = 1\n\n def remove(\n self,\n triple_pattern: _TriplePatternType,\n context: Optional[_ContextType] = None,\n ) -> None:\n req_ctx = self.__ctx_to_str(context)\n for triple, c in self.triples(triple_pattern, context=context):\n subject, predicate, object_ = triple\n for ctx in self.__get_context_for_triple(triple):\n if context is not None and req_ctx != ctx:\n continue\n self.__remove_triple_context(triple, ctx)\n ctxs = self.__get_context_for_triple(triple, skipQuoted=True)\n if None in ctxs and (context is None or len(ctxs) == 1):\n # remove from default graph too\n self.__remove_triple_context(triple, None)\n if len(self.__get_context_for_triple(triple)) == 0:\n del self.__spo[subject][predicate][object_]\n del self.__pos[predicate][object_][subject]\n del self.__osp[object_][subject][predicate]\n del self.__tripleContexts[triple]\n if (\n req_ctx is not None\n and req_ctx in self.__contextTriples\n and len(self.__contextTriples[req_ctx]) == 0\n ):\n # all triples are removed out of this context\n # and it's not the default context so delete it\n del self.__contextTriples[req_ctx]\n\n if (\n triple_pattern == (None, None, None)\n and context in self.__all_contexts\n and not self.graph_aware\n ):\n # remove the whole context\n self.__all_contexts.remove(context)\n\n def triples(\n self,\n triple_pattern: _TriplePatternType,\n context: Optional[_ContextType] = None,\n ) -> Generator[\n Tuple[_TripleType, Generator[Optional[_ContextType], None, None]],\n None,\n None,\n ]:\n \"\"\"A generator over all the triples matching\"\"\"\n req_ctx = self.__ctx_to_str(context)\n subject, predicate, object_ = triple_pattern\n\n # all triples case (no triple parts given as pattern)\n if subject is None and predicate is None and object_ is None:\n # Just dump all known triples from the given graph\n if req_ctx not in self.__contextTriples:\n return\n for triple in self.__contextTriples[req_ctx].copy():\n yield triple, self.__contexts(triple)\n\n # optimize \"triple in graph\" case (all parts given)\n elif subject is not None and predicate is not None and object_ is not None:\n # type error: Incompatible types in assignment (expression has type \"Tuple[Optional[IdentifiedNode], Optional[IdentifiedNode], Optional[Identifier]]\", variable has type \"Tuple[IdentifiedNode, IdentifiedNode, Identifier]\")\n # NOTE on type error: at this point, all elements of triple_pattern\n # is not None, so it has the same type as triple\n triple = triple_pattern # type: ignore[assignment]\n \n... [truncated 14056 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-8685a85503c1", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-8685a85503c1", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "9b14b8f97994222b3744aa3c7710ecab240c9042", "source_files": ["rdflib/plugins/stores/memory.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** WGS namespace IRI mismatch leads to incorrect Turtle serialization prefixes\n\n## Description\nWhen serializing data containing WGS (W3C Basic Geo) vocabulary to Turtle, the system currently uses an `https://` namespace IRI. This `https://` IRI does not align with the standard `http://www.w3.org/2003/01/geo/wgs84_pos#` IRI found in published W3C data. As a result, the Turtle serialization invents an incorrect `wgs1:` prefix for the WGS vocabulary. The expected behavior is for the system to use the official `http://` WGS namespace IRI, allowing for correct and consistent prefixes like `geo:` or `wgs:` in Turtle output.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `695f864a6763` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/namespace/_WGS.py\n```python\nfrom rdflib.namespace import DefinedNamespace, Namespace\nfrom rdflib.term import URIRef\n\n\nclass WGS(DefinedNamespace):\n \"\"\"\n Basic Geo (WGS84 lat/long) Vocabulary\n\n The HTML Specification for the vocabulary can be found\n here .\n \"\"\"\n\n _NS = Namespace(\"https://www.w3.org/2003/01/geo/wgs84_pos#\")\n\n # http://www.w3.org/2000/01/rdf-schema#Class\n SpatialThing: URIRef\n Point: URIRef\n\n # http://www.w3.org/2002/07/owl#DatatypeProperty\n alt: URIRef\n\n lat: URIRef # http://www.w3.org/2003/01/geo/wgs84_pos#lat\n lat_long: URIRef\n location: URIRef\n long: URIRef\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-b3e60e79c9b0", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-b3e60e79c9b0", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "695f864a67636ef8e5610483dacf2442423c3254", "source_files": ["rdflib/namespace/_WGS.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Invalid QName generated for XML namespace URIs\n\n## Description\nWhen a URI starts with `http://www.w3.org/XML/1998/namespace/` (including a trailing slash), it is incorrectly serialized.\n\n**Expected behavior:** The URI should be serialized as a valid QName or a full IRI, allowing it to be parsed back successfully.\n**Actual behavior:** The URI is serialized as `xml:/`, which is not a valid QName and causes subsequent parsing to fail.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `5abda95ac70c` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/namespace/__init__.py\n```python\n\"\"\"\n# Namespace Utilities\n\nRDFLib provides mechanisms for managing Namespaces.\n\nIn particular, there is a [`Namespace`][rdflib.namespace.Namespace] class\nthat takes as its argument the base URI of the namespace.\n\n```python\n>>> from rdflib.namespace import Namespace\n>>> RDFS = Namespace(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\n\n```\n\nFully qualified URIs in the namespace can be constructed either by attribute\nor by dictionary access on Namespace instances:\n\n```python\n>>> RDFS.seeAlso\nrdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')\n>>> RDFS['seeAlso']\nrdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')\n\n```\n\n## Automatic handling of unknown predicates\n\nAs a programming convenience, a namespace binding is automatically\ncreated when [`URIRef`][rdflib.term.URIRef] predicates are added to the graph.\n\n## Importable namespaces\n\nThe following namespaces are available by directly importing from rdflib:\n\n* BRICK\n* CSVW\n* DC\n* DCAT\n* DCMITYPE\n* DCTERMS\n* DCAM\n* DOAP\n* FOAF\n* ODRL2\n* ORG\n* OWL\n* PROF\n* PROV\n* QB\n* RDF\n* RDFS\n* SDO\n* SH\n* SKOS\n* SOSA\n* SSN\n* TIME\n* VANN\n* VOID\n* WGS\n* XSD\n\n```python\n>>> from rdflib.namespace import RDFS\n>>> RDFS.seeAlso\nrdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#seeAlso')\n\n```\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport warnings\n\ntry:\n # Python >= 3.14\n from annotationlib import (\n get_annotations, # type: ignore[attr-defined,unused-ignore]\n )\nexcept ImportError: # pragma: no cover\n try:\n # Python >= 3.10\n from inspect import get_annotations # type: ignore[attr-defined,unused-ignore]\n except ImportError:\n\n def get_annotations(thing: Any) -> dict:\n return thing.__annotations__\n\n\nfrom functools import lru_cache\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Union\nfrom unicodedata import category\nfrom urllib.parse import urldefrag, urljoin\n\nfrom rdflib.term import URIRef, Variable, _is_valid_uri\n\nif TYPE_CHECKING:\n from rdflib.graph import Graph\n from rdflib.store import Store\n\n\n__all__ = [\n \"is_ncname\",\n \"split_uri\",\n \"Namespace\",\n \"ClosedNamespace\",\n \"DefinedNamespace\",\n \"NamespaceManager\",\n \"BRICK\",\n \"CSVW\",\n \"DC\",\n \"DCAM\",\n \"DCAT\",\n \"DCMITYPE\",\n \"DCTERMS\",\n \"DOAP\",\n \"FOAF\",\n \"GEO\",\n \"ODRL2\",\n \"ORG\",\n \"OWL\",\n \"PROF\",\n \"PROV\",\n \"QB\",\n \"RDF\",\n \"RDFS\",\n \"SDO\",\n \"SH\",\n \"SKOS\",\n \"SOSA\",\n \"SSN\",\n \"TIME\",\n \"VANN\",\n \"VOID\",\n \"WGS\",\n \"XSD\",\n]\n\nlogger = logging.getLogger(__name__)\n\n\nclass Namespace(str):\n \"\"\"Utility class for quickly generating URIRefs with a common prefix.\n\n ```python\n >>> from rdflib.namespace import Namespace\n >>> n = Namespace(\"http://example.org/\")\n >>> n.Person # as attribute\n rdflib.term.URIRef('http://example.org/Person')\n >>> n['first-name'] # as item - for things that are not valid python identifiers\n rdflib.term.URIRef('http://example.org/first-name')\n >>> n.Person in n\n True\n >>> n2 = Namespace(\"http://example2.org/\")\n >>> n.Person in n2\n False\n\n ```\n \"\"\"\n\n def __new__(cls, value: Union[str, bytes]) -> Namespace:\n try:\n rt = str.__new__(cls, value)\n except UnicodeDecodeError:\n rt = str.__new__(cls, value, \"utf-8\") # type: ignore[arg-type]\n return rt\n\n # type error: Signature of \"title\" incompatible with supertype \"str\"\n @property\n def title(self) -> URIRef: # type: ignore[override]\n # Override for DCTERMS.title to return a URIRef instead of str.title method\n return URIRef(self + \"title\")\n\n def term(self, name: str) -> URIRef:\n # need to handle slices explicitly because of __getitem__ override\n return URIRef(self + (name if isinstance(name, str) else \"\"))\n\n def __getitem__(self, key: str) -> URIRef: # type: ignore[override]\n return self.term(key)\n\n def __getattr__(self, name: str) -> URIRef:\n if name.startswith(\"__\"): # ignore any special Python names!\n raise AttributeError\n return self.term(name)\n\n def __repr__(self) -> str:\n return f\"Namespace({super().__repr__()})\"\n\n def __contains__(self, ref: str) -> bool: # type: ignore[override]\n \"\"\"Allows to check if a URI is within (starts with) this Namespace.\n\n ```python\n >>> from rdflib import URIRef\n >>> namespace = Namespace('http://example.org/')\n >>> uri = URIRef('http://example.org/foo')\n >>> uri in namespace\n True\n >>> person_class = namespace['Person']\n >>> person_class in namespace\n True\n >>> obj = URIRef('http://not.example.org/bar')\n >>> obj in namespace\n False\n\n ```\n \"\"\"\n return ref.startswith(self) # test namespace membership with \"ref in ns\" syntax\n\n\nclass URIPattern(str):\n \"\"\"Utility class for creating URIs according to some pattern.\n\n This supports either new style formatting with .format\n or old-style with % operator.\n\n ```python\n >>> u=URIPattern(\"http://example.org/%s/%d/resource\")\n >>> u%('books', 12345)\n rdflib.term.URIRef('http://example.org/books/12345/resource')\n\n ```\n \"\"\"\n\n def __new__(cls, value: Union[str, bytes]) -> URIPattern:\n try:\n rt = str.__new__(cls, value)\n except UnicodeDecodeError:\n if TYPE_CHECKING:\n assert isinstance(value, bytes)\n rt = str.__new__(cls, value, \"utf-8\")\n return rt\n\n def __mod__(self, *args, **kwargs) -> URIRef:\n return URIRef(super().__mod__(*args, **kwargs))\n\n def format(self, *args, **kwargs) -> URIRef:\n return URIRef(super().format(*args, **kwargs))\n\n def __repr__(self) -> str:\n return f\"URIPattern({super().__repr__()})\"\n\n\n# _DFNS_RESERVED_ATTRS are attributes for which DefinedNamespaceMeta should\n# always raise AttributeError if they are not defined and which should not be\n# considered part of __dir__ results. These should be all annotations on\n# `DefinedNamespaceMeta`.\n_DFNS_RESERVED_ATTRS: Set[str] = {\n \"__slots__\",\n \"_NS\",\n \"_warn\",\n \"_fail\",\n \"_extras\",\n \"_underscore_num\",\n}\n\n# Some libraries probe classes for certain attributes or items.\n# This is a list of those attributes and items that should be ignored.\n_IGNORED_ATTR_LOOKUP: Set[str] = {\n \"_pytestfixturefunction\", # pytest tries to look this up on Defined namespaces\n \"_partialmethod\", # sphinx tries to look this up during autodoc generation\n}\n\n\nclass DefinedNamespaceMeta(type):\n \"\"\"Utility metaclass for generating URIRefs with a common prefix.\"\"\"\n\n __slots__: Tuple[str, ...] = tuple()\n\n _NS: Namespace\n _warn: bool = True\n _fail: bool = False # True means mimic ClosedNamespace\n _extras: List[str] = [] # List of non-pythonesque items\n _underscore_num: bool = False # True means pass \"_n\" constructs\n\n @lru_cache(maxsize=None)\n def __getitem__(cls, name: str, default=None) -> URIRef:\n name = str(name)\n\n if name in _DFNS_RESERVED_ATTRS:\n raise KeyError(\n f\"DefinedNamespace like object has no access item named {name!r}\"\n )\n elif name in _IGNORED_ATTR_LOOKUP:\n raise KeyError()\n if (cls._warn or cls._fail) and name not in cls:\n if cls._fail:\n raise AttributeError(f\"term '{name}' not in namespace '{cls._NS}'\")\n else:\n warnings.warn(\n f\"Code: {name} is not defined in namespace {cls.__name__}\",\n stacklevel=3,\n )\n return cls._NS[name]\n\n def __getattr__(cls, name: str):\n if name in _IGNORED_ATTR_LOOKUP:\n raise AttributeError()\n elif name in _DFNS_RESERVED_ATTRS:\n raise AttributeError(\n f\"DefinedNamespace like object has no attribute {name!r}\"\n )\n elif name.startswith(\"__\"):\n return super(DefinedNamespaceMeta, cls).__getattribute__(name)\n return cls.__getitem__(name)\n\n def __repr__(cls) -> str:\n try:\n ns_repr = repr(cls._NS)\n except AttributeError:\n ns_repr = \"\"\n return f\"Namespace({ns_repr})\"\n\n def __str__(cls) -> str:\n try:\n return str(cls._NS)\n except AttributeError:\n return \"\"\n\n def __add__(cls, other: str) -> URIRef:\n return cls.__getitem__(other)\n\n def __contains__(cls, item: str) -> bool:\n \"\"\"Determine whether a URI or an individual item belongs to this namespace\"\"\"\n try:\n this_ns = cls._NS\n except AttributeError:\n return False\n item_str = str(item)\n if item_str.startswith(str(this_ns)):\n item_str = item_str[len(str(this_ns)) :]\n return any(\n item_str in get_annotations(c)\n or item_str in c._extras\n or (cls._underscore_num and item_str[0] == \"_\" and item_str[1:].isdigit())\n for c in cls.mro()\n if issubclass(c, DefinedNamespace)\n )\n\n def __dir__(cls) -> Iterable[str]:\n attrs = {str(x) for x in get_annotations(cls)}\n # Removing these as they should not be considered part of the namespace.\n attrs.difference_update(_DFNS_RESERVED_ATTRS)\n values = {cls[str(x)] for x in attrs}\n return values\n\n def as_jsonld_context(self, pfx: str) -> dict: # noqa: N804\n \"\"\"Returns this DefinedNamespace as a JSON-LD 'context' object\"\"\"\n terms = {pfx: str(self._NS)}\n for key, term in get_annotations(self).items():\n if issubclass(term, URIRef):\n terms[key] = f\"{pfx}:{key}\"\n\n return {\"@context\": terms}\n\n\nclass DefinedNamespace(metaclass=DefinedNamespaceMeta):\n \"\"\"A Namespace with an enumerated list of members.\n\n Warnings are emitted if unknown members are referenced if _warn is True.\n \"\"\"\n\n __slots__: Tuple[str, ...] = tuple()\n\n def __init__(self):\n raise TypeError(\"namespace may not be instantiated\")\n\n\nclass ClosedNamespace(Namespace):\n \"\"\"\n A namespace with a closed list of members\n\n Trying to create terms not listed is an error\n \"\"\"\n\n __uris: Dict[str, URIRef]\n\n def __new__(cls, uri: str, terms: List[str]):\n rt = super().__new__(cls, uri)\n rt.__uris = {t: URIRef(rt + t) for t in terms} # type: ignore[attr-defined]\n return rt\n\n @property\n def uri(self) -> str: # Back-compat\n return str(self)\n\n def term(self, name: str) -> URIRef:\n uri = self.__uris.get(name)\n if uri is None:\n raise KeyError(f\"term '{name}' not in namespace '{self}'\")\n return uri\n\n def __getitem__(self, key: str) -> URIRef: # type: ignore[override]\n return self.term(key)\n\n def __getattr__(self, name: str) -> URIRef:\n if name.startswith(\"__\"): # ignore any special Python names!\n raise AttributeError\n else:\n try:\n return self.term(name)\n except KeyError as e:\n raise AttributeError(e)\n\n def __repr__(self) -> str:\n return f\"{self.__module__}.{self.__class__.__name__}({str(self)!r})\"\n\n def __dir__(self) -> List[str]:\n return list(self.__uris)\n\n def __contains__(self, ref: str) -> bool: # type: ignore[override]\n return (\n ref in self.__uris.values()\n ) # test namespace membership with \"ref in ns\" syntax\n\n def _ipython_key_completions_(self) -> List[str]:\n return dir(self)\n\n\nXMLNS = Namespace(\"http://www.w3.org/XML/1998/namespace\")\n\nif TYPE_CHECKING:\n from rdflib._type_checking import _NamespaceSetString\n\n_with_bind_override_fix = True\n\n\nclass NamespaceManager:\n \"\"\"Class for managing prefix => namespace mappings\n\n This class requires an RDFlib Graph as an input parameter and may optionally have\n the parameter bind_namespaces set. This second parameter selects a strategy which\n is one of the following:\n\n * core:\n * binds several core RDF prefixes only\n * owl, rdf, rdfs, xsd, xml from the NAMESPACE_PREFIXES_CORE object\n * rdflib:\n * binds all the namespaces shipped with RDFLib as DefinedNamespace instances\n * all the core namespaces and all the following: brick, csvw, dc, dcat\n * dcmitype, dcterms, dcam, doap, foaf, geo, odrl, org, prof, prov, qb, schema\n * sh, skos, sosa, ssn, time, vann, void\n * see the NAMESPACE_PREFIXES_RDFLIB object for the up-to-date list\n * this is default\n * none:\n * binds no namespaces to prefixes\n * note this is NOT default behaviour\n * cc:\n * using prefix bindings from prefix.cc which is a online prefixes database\n * not implemented yet - this is aspirational\n\n !!! warning \"Breaking changes\"\n\n The namespaces bound for specific values of `bind_namespaces`\n constitute part of RDFLib's public interface, so changes to them should\n only be additive within the same minor version. Removing values, or\n removing namespaces that are bound by default, constitutes a breaking\n change.\n\n See the sample usage\n\n ```python\n >>> import rdflib\n >>> from rdflib import Graph\n >>> from rdflib.namespace import Namespace, NamespaceManager\n >>> EX = Namespace('http://example.com/')\n >>> namespace_manager = NamespaceManager(Graph())\n >>> namespace_manager.bind('ex', EX, override=False)\n >>> g = Graph()\n >>> g.namespace_manager = namespace_manager\n >>> all_ns = [n for n in g.namespace_manager.namespaces()]\n >>> assert ('ex', rdflib.term.URIRef('http://example.com/')) in all_ns\n\n ```\n \"\"\"\n\n def __init__(self, graph: Graph, bind_namespaces: _NamespaceSetString = \"rdflib\"):\n self.graph = graph\n self.__cache: Dict[str, Tuple[str, URIRef, str]] = {}\n self.__cache_strict: Dict[str, Tuple[str, URIRef, str]] = {}\n self.__log = None\n self.__strie: Dict[str, Any] = {}\n self.__trie: Dict[str, Any] = {}\n # This type declaration is here becuase there is no common base class\n # for all namespaces and without it the inferred type of ns is not\n # compatible with all prefixes.\n ns: Any\n # bind Namespaces as per options.\n # default is core\n if bind_namespaces == \"none\":\n # binds no namespaces to prefixes\n # note this is NOT default\n pass\n elif bind_namespaces == \"rdflib\":\n # bind all the Namespaces shipped with RDFLib\n for prefix, ns in _NAMESPACE_PREFIXES_RDFLIB.items():\n self.bind(prefix, ns)\n # ... don't forget the core ones too\n for prefix, ns in _NAMESPACE_PREFIXES_CORE.items():\n self.bind(prefix, ns)\n elif bind_namespaces == \"cc\":\n # bind any prefix that can be found with lookups to prefix.cc\n # first bind core and rdflib ones\n # work out remainder - namespaces without prefixes\n # only look those ones up\n raise NotImplementedError(\"Haven't got to this option yet\")\n elif bind_namespaces == \"core\":\n # bind a few core RDF namespaces - default\n for prefix, ns in _NAMESPACE_PREFIXES_CORE.items():\n self.bind(prefix, ns)\n else:\n raise ValueError(f\"unsupported namespace set {bind_namespaces}\")\n\n def __contains__(self, ref: str) -> bool:\n # checks if a reference is in any of the managed namespaces with syntax\n # \"ref in manager\". Note that we don't use \"ref in ns\", as\n # NamespaceManager.namespaces() returns Iterator[Tuple[str, URIRef]]\n # rather than Iterator[Tuple[str, Namespace]]\n return any(ref.startswith(ns) for prefix, ns in self.namespaces())\n\n def reset(self\n... [truncated 18371 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-b3f7f978e148", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-b3f7f978e148", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "5abda95ac70ce2c520165f15c256554629aef407", "source_files": ["rdflib/namespace/__init__.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Turtle/LongTurtle serializer corrupts shared RDF lists with shared internal cells\n\n## Description\nWhen serializing an RDF graph using the Turtle or LongTurtle format, if an RDF list contains an internal cell (not just the head of the list) that is referenced by multiple subjects, the serializer incorrectly uses the compact `(...)` collection syntax. This causes the shared list cell to be consumed by one reference, leaving other references to that cell undefined in the serialized output. The resulting serialization is incomplete and does not round-trip, leading to data loss.\n\n**Reproduction:**\nGiven the following RDF graph:\n```turtle\n_:tail rdf:first \"\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `29eb45e55fd6` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/plugins/serializers/longturtle.py\n```python\n\"\"\"\nLongTurtle RDF graph serializer for RDFLib.\nSee http://www.w3.org/TeamSubmission/turtle/ for syntax specification.\n\nThis variant, longturtle as opposed to just turtle, makes some small format changes\nto turtle - the original turtle serializer. It:\n\n* uses PREFIX instead of @prefix\n* uses BASE instead of @base\n* adds a new line at RDF.type, or 'a'\n* adds a newline and an indent for all triples with more than one object (object list)\n* adds a new line and ';' for the last triple in a set with '.'\n on the start of the next line\n* uses default encoding (encode()) is used instead of \"latin-1\"\n\n- Nicholas Car, 2023\n\"\"\"\n\nfrom __future__ import annotations\n\nimport warnings\nfrom typing import IO, Any, Optional\n\nfrom rdflib.compare import to_canonical_graph\nfrom rdflib.exceptions import Error\nfrom rdflib.graph import Graph, _TripleType\nfrom rdflib.namespace import RDF\nfrom rdflib.term import BNode, Literal, URIRef\n\nfrom .turtle import RecursiveSerializer\n\n__all__ = [\"LongTurtleSerializer\"]\n\nSUBJECT = 0\nVERB = 1\nOBJECT = 2\n\n_GEN_QNAME_FOR_DT = False\n_SPACIOUS_OUTPUT = False\n\n\nclass LongTurtleSerializer(RecursiveSerializer):\n \"\"\"LongTurtle, a Turtle serialization format.\n\n When the optional parameter `canon` is set to `True`, the graph is canonicalized\n before serialization. This normalizes blank node identifiers and allows for\n deterministic serialization of the graph. Useful when consistent outputs are required.\n \"\"\"\n\n short_name = \"longturtle\"\n indentString = \" \"\n\n def __init__(self, store):\n self._ns_rewrite = {}\n self._canon = False\n super(LongTurtleSerializer, self).__init__(store)\n self.keywords = {RDF.type: \"a\"}\n self.reset()\n self.stream = None\n self._spacious: bool = _SPACIOUS_OUTPUT\n\n def addNamespace(self, prefix, namespace):\n # Turtle does not support prefixes that start with _\n # if they occur in the graph, rewrite to p_blah\n # this is more complicated since we need to make sure p_blah\n # does not already exist. And we register namespaces as we go, i.e.\n # we may first see a triple with prefix _9 - rewrite it to p_9\n # and then later find a triple with a \"real\" p_9 prefix\n\n # so we need to keep track of ns rewrites we made so far.\n\n if (prefix > \"\" and prefix[0] == \"_\") or self.namespaces.get(\n prefix, namespace\n ) != namespace:\n if prefix not in self._ns_rewrite:\n p = \"p\" + prefix\n while p in self.namespaces:\n p = \"p\" + p\n self._ns_rewrite[prefix] = p\n\n prefix = self._ns_rewrite.get(prefix, prefix)\n\n super(LongTurtleSerializer, self).addNamespace(prefix, namespace)\n return prefix\n\n def canonize(self):\n \"\"\"Apply canonicalization to the store.\n\n This normalizes blank node identifiers and allows for deterministic\n serialization of the graph.\n \"\"\"\n if not self._canon:\n return\n\n namespace_manager = self.store.namespace_manager\n store = to_canonical_graph(self.store)\n content = store.serialize(format=\"application/n-triples\")\n lines = content.split(\"\\n\")\n lines.sort()\n graph = Graph()\n graph.parse(\n data=\"\\n\".join(lines), format=\"application/n-triples\", skolemize=True\n )\n graph = graph.de_skolemize()\n graph.namespace_manager = namespace_manager\n self.store = graph\n\n def reset(self):\n super(LongTurtleSerializer, self).reset()\n self._shortNames = {}\n self._started = False\n self._ns_rewrite = {}\n self.canonize()\n\n def serialize(\n self,\n stream: IO[bytes],\n base: Optional[str] = None,\n encoding: Optional[str] = None,\n spacious: Optional[bool] = None,\n **kwargs: Any,\n ) -> None:\n self._canon = kwargs.get(\"canon\", False)\n self.reset()\n self.stream = stream\n # if base is given here, use, if not and a base is set for the graph use that\n if base is not None:\n self.base = base\n elif self.store.base is not None:\n self.base = self.store.base\n\n if spacious is not None:\n self._spacious = spacious\n\n self.preprocess()\n subjects_list = self.orderSubjects()\n\n self.startDocument()\n\n firstTime = True\n for subject in subjects_list:\n if self.isDone(subject):\n continue\n if firstTime:\n firstTime = False\n if self.statement(subject) and not firstTime:\n self.write(\"\\n\")\n\n self.endDocument()\n\n self.base = None\n\n def preprocessTriple(self, triple: _TripleType) -> None:\n super(LongTurtleSerializer, self).preprocessTriple(triple)\n for i, node in enumerate(triple):\n if i == VERB:\n if node in self.keywords:\n # predicate is a keyword\n continue\n if (\n self.base is not None\n and isinstance(node, URIRef)\n and node.startswith(self.base)\n and \"#\" not in node.replace(self.base, \"\")\n and \"/\" not in node.replace(self.base, \"\")\n ):\n # predicate corresponds to base namespace\n continue\n # Don't use generated prefixes for subjects and objects\n self.get_pname(node, gen_prefix=(i == VERB))\n if isinstance(node, Literal) and node.datatype:\n self.get_pname(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT)\n p = triple[1]\n if isinstance(p, BNode): # hmm - when is P ever a bnode?\n self._references[p] += 1\n\n def get_pname(self, uri, gen_prefix=True):\n if not isinstance(uri, URIRef):\n return None\n\n try:\n parts = self.store.compute_qname(uri, generate=gen_prefix)\n except Exception:\n # is the uri a namespace in itself?\n pfx = self.store.store.prefix(uri)\n\n if pfx is not None:\n parts = (pfx, uri, \"\")\n else:\n # nothing worked\n return None\n\n prefix, namespace, local = parts\n\n # To understand treatment of % character refer to Productions for terminal PLX at\n # https://www.w3.org/TR/turtle/#grammar-production-PLX\n # Only % NOT followed by two hex chars requires manual backslash escaping\n local = local.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n local = self.LOCALNAME_PECRENT_CHARACTER_REQUIRING_ESCAPE_REGEX.sub(\n \"\\\\%\", local\n )\n\n # PName cannot end with .\n if local.endswith(\".\"):\n return None\n\n prefix = self.addNamespace(prefix, namespace)\n\n return \"%s:%s\" % (prefix, local)\n\n def getQName(self, uri, gen_prefix=True):\n warnings.warn(\n \"LongTurtleSerializer.getQName is deprecated, use LongTurtleSerializer.get_pname instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return self.get_pname(uri, gen_prefix)\n\n def startDocument(self):\n self._started = True\n ns_list = sorted(self.namespaces.items())\n\n if self.base:\n self.write(self.indent() + \"BASE <%s>\\n\" % self.base)\n for prefix, uri in ns_list:\n self.write(self.indent() + \"PREFIX %s: <%s>\\n\" % (prefix, uri))\n if ns_list and self._spacious:\n self.write(\"\\n\")\n\n def endDocument(self):\n if self._spacious:\n self.write(\"\\n\")\n\n def statement(self, subject):\n self.subjectDone(subject)\n return self.s_squared(subject) or self.s_default(subject)\n\n def s_default(self, subject):\n self.write(\"\\n\" + self.indent())\n self.path(subject, SUBJECT)\n self.write(\"\\n\" + self.indent())\n self.predicateList(subject)\n self.write(\"\\n.\")\n return True\n\n def s_squared(self, subject):\n if (self._references[subject] > 0) or not isinstance(subject, BNode):\n return False\n self.write(\"\\n\" + self.indent() + \"[]\")\n self.predicateList(subject, newline=False)\n self.write(\"\\n.\")\n return True\n\n def path(self, node, position, newline=False):\n if not (\n self.p_squared(node, position) or self.p_default(node, position, newline)\n ):\n raise Error(\"Cannot serialize node '%s'\" % (node,))\n\n def p_default(self, node, position, newline=False):\n if position != SUBJECT and not newline:\n self.write(\" \")\n self.write(self.label(node, position))\n return True\n\n def label(self, node, position):\n if node == RDF.nil:\n return \"()\"\n if position is VERB and node in self.keywords:\n return self.keywords[node]\n if isinstance(node, Literal):\n return node._literal_n3(\n use_plain=True,\n qname_callback=lambda dt: self.get_pname(dt, _GEN_QNAME_FOR_DT),\n )\n else:\n node = self.relativize(node)\n\n return self.get_pname(node, position == VERB) or node.n3()\n\n def p_squared(\n self,\n node,\n position,\n ):\n if (\n not isinstance(node, BNode)\n or node in self._serialized\n or self._references[node] > 1\n or position == SUBJECT\n ):\n return False\n\n if self.isValidList(node):\n # this is a list\n self.depth += 2\n self.write(\" (\\n\")\n self.depth -= 2\n self.doList(node)\n self.write(\"\\n\" + self.indent() + \")\")\n else:\n # this is a Blank Node\n self.subjectDone(node)\n self.write(\"\\n\" + self.indent(1) + \"[\\n\")\n self.depth += 1\n self.predicateList(node)\n self.depth -= 1\n self.write(\"\\n\" + self.indent(1) + \"]\")\n\n return True\n\n def isValidList(self, l_):\n \"\"\"\n Checks if l is a valid RDF list, i.e. no nodes have other properties.\n \"\"\"\n try:\n if self.store.value(l_, RDF.first) is None:\n return False\n except Exception:\n return False\n while l_:\n if l_ != RDF.nil and len(list(self.store.predicate_objects(l_))) != 2:\n return False\n l_ = self.store.value(l_, RDF.rest)\n return True\n\n def doList(self, l_):\n i = 0\n while l_:\n item = self.store.value(l_, RDF.first)\n if item is not None:\n if i == 0:\n self.write(self.indent(1))\n else:\n self.write(\"\\n\" + self.indent(1))\n self.path(item, OBJECT, newline=True)\n self.subjectDone(l_)\n l_ = self.store.value(l_, RDF.rest)\n i += 1\n\n def predicateList(self, subject, newline=False):\n properties = self.buildPredicateHash(subject)\n propList = self.sortProperties(properties)\n if len(propList) == 0:\n return\n self.write(self.indent(1))\n self.verb(propList[0], newline=True)\n self.objectList(properties[propList[0]])\n for predicate in propList[1:]:\n self.write(\" ;\\n\" + self.indent(1))\n self.verb(predicate, newline=True)\n self.objectList(properties[predicate])\n self.write(\" ;\")\n\n def verb(self, node, newline=False):\n self.path(node, VERB, newline)\n\n def objectList(self, objects):\n count = len(objects)\n if count == 0:\n return\n depthmod = (count == 1) and 0 or 1\n self.depth += depthmod\n first_nl = False\n if count > 1:\n if not isinstance(objects[0], BNode):\n self.write(\"\\n\" + self.indent(1))\n else:\n self.write(\" \")\n first_nl = True\n self.path(objects[0], OBJECT, newline=first_nl)\n for obj in objects[1:]:\n self.write(\" ,\")\n if not isinstance(obj, BNode):\n self.write(\"\\n\" + self.indent(1))\n self.path(obj, OBJECT, newline=True)\n self.depth -= depthmod\n\n```\n\n### rdflib/plugins/serializers/turtle.py\n```python\n\"\"\"\nTurtle RDF graph serializer for RDFLib.\nSee for syntax specification.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nimport warnings\nfrom collections import defaultdict\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n DefaultDict,\n Dict,\n List,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n TypeVar,\n Union,\n)\n\nfrom rdflib.exceptions import Error\nfrom rdflib.graph import Graph\nfrom rdflib.namespace import RDF, RDFS\nfrom rdflib.serializer import Serializer\nfrom rdflib.term import BNode, Literal, Node, URIRef\n\n_StrT = TypeVar(\"_StrT\", bound=str)\n\nif TYPE_CHECKING:\n from rdflib.graph import _PredicateType, _SubjectType, _TripleType\n\n__all__ = [\"RecursiveSerializer\", \"TurtleSerializer\"]\n\n\nclass RecursiveSerializer(Serializer):\n \"\"\"Base class for recursive serializers.\"\"\"\n\n topClasses = [RDFS.Class]\n predicateOrder = [RDF.type, RDFS.label]\n maxDepth = 10\n indentString = \" \"\n roundtrip_prefixes: Tuple[Any, ...] = ()\n LOCALNAME_PECRENT_CHARACTER_REQUIRING_ESCAPE_REGEX = re.compile(\n r\"%(?![0-9A-Fa-f]{2})\"\n )\n\n def __init__(self, store: Graph):\n super(RecursiveSerializer, self).__init__(store)\n self.stream: Optional[IO[bytes]] = None\n self.reset()\n\n def addNamespace(self, prefix: str, uri: URIRef) -> None:\n if prefix in self.namespaces and self.namespaces[prefix] != uri:\n raise Exception(\n \"Trying to override namespace prefix %s => %s, but it's already bound to %s\"\n % (prefix, uri, self.namespaces[prefix])\n )\n self.namespaces[prefix] = uri\n\n def checkSubject(self, subject: _SubjectType) -> bool:\n \"\"\"Check to see if the subject should be serialized yet\"\"\"\n if (\n (self.isDone(subject))\n or (subject not in self._subjects)\n or ((subject in self._topLevels) and (self.depth > 1))\n or (isinstance(subject, URIRef) and (self.depth >= self.maxDepth))\n ):\n return False\n return True\n\n def isDone(self, subject: _SubjectType) -> bool:\n \"\"\"Return true if subject is serialized\"\"\"\n return subject in self._serialized\n\n def orderSubjects(self) -> List[_SubjectType]:\n seen: Dict[_SubjectType, bool] = {}\n subjects: List[_SubjectType] = []\n\n for classURI in self.topClasses:\n members = list(self.store.subjects(RDF.type, classURI))\n # type error: All overload variants of \"sort\" of \"list\" require at least one argument\n members.sort() # type: ignore[call-overload]\n\n subjects.extend(members)\n for member in members:\n self._topLevels[member] = True\n seen[member] = True\n\n recursable = [\n (isinstance(subject, BNode), self._references[subject], subject)\n for subject in self._subjects\n if subject not in seen\n ]\n\n recursable.sort()\n subjects.extend([subject for (isbnode, refs, subject) in recursable])\n\n return subjects\n\n def preprocess(self) -> None:\n for triple in self.store.triples((None, None, None)):\n self.preprocessTriple(triple)\n\n def preprocessTriple(self, spo: _TripleType) -> None:\n s, p, o = spo\n self._references[o] += 1\n self._subjects[s] = True\n\n def reset(self) -> None:\n self.depth = 0\n # Typed none because nothing is using it ...\n self.lists: Dict[None, None] = {}\n self.namespaces: Dict[str, URIRef] = {}\n self._references: DefaultDict[Node, int] = defaultdict(int)\n self._serialized: Dict[_SubjectType, bool] = {}\n self._subjects: Dict[_SubjectType, bool] = {}\n self._topLevels: Dict[_SubjectType, bool] = {}\n\n if self.roundtrip_prefixes:\n if hasattr(self.roundtrip_prefixes, \"__iter__\"):\n for prefix, ns in self.store.namespaces():\n if prefix in self.roundtrip_prefixes:\n self.addNamespace(prefix, ns)\n else:\n for prefix, ns in self.store.namespaces():\n self.addNamespace(prefix, ns)\n\n def buildPredicateHash(\n self, subject: _SubjectType\n ) -> Mapping[_PredicateType, List[Node]]:\n \"\"\"\n Build a hash key by predicate to a list of objects for the given\n subject\n \"\"\"\n properties: Dict[_PredicateType, List[Node]] = {}\n for s, p, o in self.store.triples((subject, None, None)):\n oList = properties.get(p, [])\n oList.append(o)\n properties[p] = oList\n return properties\n\n def sortProperties(\n self, properties: Mapping[_PredicateType, List[Node]]\n ) -> List[_PredicateType]:\n \"\"\"Take a hash from predicate uris to lists of values.\n Sort the lists of values. Return a sorted list of properties.\"\"\"\n # Sort object lists\n for prop, objects in properties.items():\n # type error: All overload variants of \"sort\" of \"list\" require at least one argument\n objects.sort() # type: ignore[call-overload]\n\n # Make sorted list of properties\n propList: List[_PredicateType] = []\n seen: Dict[_PredicateType, bool] = {}\n for prop in self.predicateOrder:\n if (prop in properties) and (prop not in seen):\n propList.append(prop)\n seen[prop] = True\n props = list(properties.keys())\n # type error: All overload variants of \"sort\" of \"list\" require at least one argument\n props.sort() # type: ignore[call-overload]\n for prop in props:\n if prop not in seen:\n propList.append(prop)\n seen[prop] = True\n return propList\n\n def subjectDone(self, subject: _SubjectType) -> None:\n \"\"\"Mark a subject as done.\"\"\"\n self._serialized[subject] = True\n\n def indent(self, modifier: int = 0) -> str:\n \"\"\"Returns indent string multiplied by the depth\"\"\"\n return (self.depth + modifier) * self.indentString\n\n def write(self, text: str) -> None:\n \"\"\"Write text in given encoding.\"\"\"\n # type error: Item \"None\" of \"Optional[IO[bytes]]\" has no attribute \"write\"\n self.stream.write(text.encode(self.encoding, \"replace\")) # type: ignore[union-attr]\n\n def relativize(self, uri: _StrT) -> Union[_StrT, URIRef]:\n base = self.base\n if (\n base is not None\n and uri.startswith(base)\n and \"#\" not in uri.replace(base, \"\")\n and \"/\" not in uri.replace(base, \"\")\n ):\n # type error: Incompatible types in assignment (expression has type \"str\", variable has type \"Node\")\n uri = URIRef(uri.replace(base, \"\", 1)) # type: ignore[assignment]\n return uri\n\n\nSUBJECT = 0\nVERB = 1\nOBJECT = 2\n\n_GEN_QNAME_FOR_DT = False\n_SPACIOUS_OUTPUT = False\n\n\nclass TurtleSerializer(RecursiveSerializer):\n \"\"\"Turtle RDF graph serializer.\"\"\"\n\n short_name = \"turtle\"\n indentString = \" \"\n LOCALNAME_PECRENT_CHARACTER_REQUIRING_ESCAPE_REGEX = re.compile(\n r\"%(?![0-9A-Fa-f]{2})\"\n )\n\n def __init__(self, store: Graph):\n self._ns_rewrite: Dict[str, str] = {}\n super(TurtleSerializer, self).__init__(store)\n self.keywords: Dict[Node, str] = {RDF.type: \"a\"}\n self.reset()\n self.stream = None\n self._spacious = _SPACIOUS_OUTPUT\n\n # type error: Return type \"str\" of \"addNamespace\" incompatible with return type \"None\" in supertype \"RecursiveSerializer\"\n def addNamespace(self, prefix: str, namespace: URIRef) -> str: # type: ignore[override]\n # Turtle does not support prefix that start with _\n # if they occur in the graph, rewrite to p_blah\n # this is more complicated since we need to make sure p_blah\n # does not already exist. And we register namespaces as we go, i.e.\n # we may first see a triple with prefix _9 - rewrite it to p_9\n # and then later find a triple with a \"real\" p_9 prefix\n\n # so we need to keep track of ns rewrites we made so far.\n\n if (prefix > \"\" and prefix[0] == \"_\") or self.namespaces.get(\n prefix, namespace\n ) != namespace:\n if prefix not in self._ns_rewrite:\n p = \"p\" + prefix\n while p in self.namespaces:\n p = \"p\" + p\n self._ns_rewrite[prefix] = p\n\n prefix = self._ns_rewrite.get(prefix, prefix)\n\n super(TurtleSerializer, self).addNamespace(prefix, namespace)\n return prefix\n\n def reset(self) -> None:\n super(TurtleSerializer, self).reset()\n # typing as Dict[None, None] because nothing seems to be using it\n self._shortNames: Dict[None, None] = {}\n self._started = False\n self._ns_rewrite = {}\n\n def serialize(\n self,\n stream: IO[bytes],\n base: Optional[str] = None,\n encoding: Optional[str] = None,\n spacious: Optional[bool] = None,\n **kwargs: Any,\n ) -> None:\n self.reset()\n self.stream = stream\n # if base is given here, use that, if not and a base is set for the graph use that\n if base is not None:\n self.base = base\n elif self.store.base is not None:\n self.base = self.store.base\n\n if spacious is not None:\n self._spacious = spacious\n\n self.preprocess()\n subjects_list = self.orderSubjects()\n\n self.startDocument()\n\n firstTime = True\n for subject in subjects_list:\n if self.isDone(subject):\n continue\n if firstTime:\n firstTime = False\n if self.statement(subject) and not firstTime:\n self.write(\"\\n\")\n\n self.endDocument()\n stream.write(\"\\n\".encode(\"latin-1\"))\n\n self.base = None\n\n def preprocessTriple(self, triple: _TripleType) -> None:\n super(TurtleSerializer, self).preprocessTriple(triple)\n for i, node in enumerate(triple):\n if i == VERB:\n if node in self.keywords:\n # predicate is a keyword\n continue\n if (\n self.base is not None\n and isinstance(node, URIRef)\n and node.startswith(self.base)\n and \"#\" not in node.replace(self.base, \"\")\n and \"/\" not in node.replace(self.base, \"\")\n ):\n # predicate corresponds to base namespace\n continue\n # Don't use generated prefixes for subjects and objects\n self.get_pname(node, gen_prefix=(i == VERB))\n if isinstance(node, Literal) and node.datatype:\n self.get_pname(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT)\n p = triple[1]\n if isinstance(p, BNode): # hmm - when is P ever a bnode?\n self._references[p] += 1\n\n # Refer to Productions for terminals PNAME_NS and PNAME_LN https://www.w3.org/TR/turtle/#sec-grammar-grammar\n def get_pname(self, uri: Node, gen_prefix: bool = True) -> Optional[str]:\n if not isinstance(uri, URIRef):\n return None\n\n parts = None\n\n try:\n parts = self.store.compute_qname(uri, generate=gen_prefix)\n except Exception:\n # is the uri a namespace in itself?\n pfx = self.store.store.prefix(uri)\n\n if pfx is not None:\n parts = (pfx, uri, \"\")\n else:\n # nothing worked\n return None\n\n prefix, namespace, local = parts\n\n # To understand treatment of % character refer to Productions for terminal PLX at\n # https://www.w3.org/TR/turtle/#grammar-production-PLX\n # Only % NOT followed by two hex chars requires manual backslash escaping\n local = local.replace(r\"(\", r\"\\(\").replace(r\")\", r\"\\)\")\n local = self.LOCALNAME_PECRENT_CHARACTER_REQUIRING_ESCAPE_REGEX.sub(\n \"\\\\%\", local\n )\n\n # PName cannot end with .\n if local.endswith(\".\"):\n return None\n\n prefix = self.addNamespace(prefix, namespace)\n\n return \"%s:%s\" % (prefix, local)\n\n def getQName(self, uri: Node, gen_prefix: bool = True) -> Optional[str]:\n warnings.warn(\n \"TurtleSerializer.getQName is deprecated, use TurtleSerializer.get_pname instead.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return self.get_pname(uri, gen_prefix)\n\n def startDocument(self) -> None:\n self._started = True\n ns_list = sorted(self.namespaces.items())\n\n if self.base:\n self.write(self.indent() + \"@base <%s> .\\n\" % self.base)\n for prefix, uri in ns_list:\n self.write(self.indent() + \"@prefix %s: <%s> .\\n\" % (prefix, uri))\n if ns_list and self._spacious:\n self.write(\"\\n\")\n\n def endDocument(self) -> None:\n if self._spacious:\n self.write(\"\\n\")\n\n def statement(self, subject: _SubjectType) -> bool:\n self.subjectDone(subject)\n return self.s_squared(subject) or self.s_default(subject)\n\n def s_default(self, subject: _SubjectType) -> bool:\n self.write(\"\\n\" + self.indent())\n self.path(subject, SUBJECT)\n self.predicateList(subject)\n self.write(\" .\")\n return True\n\n def s_squared(self, subject: _SubjectType) -> bool:\n if (self._references[subject] > 0) or not isinstance(subject, BNode):\n return False\n self.write(\"\\n\" + self.indent() + \"[]\")\n self.predicateList(subject)\n self.write(\" .\")\n return True\n\n def path(self, node: Node, position: int, newline: bool = False) -> None:\n if not (\n self.p_squared(node, position, newline)\n or self.p_default(node, position, newline)\n ):\n raise Error(\"Cannot serialize node '%s'\" % (node,))\n\n def p_default(self, node: Node, position: int, newline: bool = False) -> bool:\n if position != SUBJECT and not newline:\n self.write(\" \")\n self.write(self.label(node, position))\n return True\n\n def label(self, node: Node, position: int) -> str:\n if node == RDF.nil:\n return \"()\"\n if position is VERB and node in self.keywords:\n return self.keywords[node]\n if isinstance(node, Literal):\n return node._literal_n3(\n use_plain=True,\n qname_callback=lambda dt: self.get_pname(dt, _GEN_QNAME_FOR_DT),\n )\n else:\n node = self.relativize(node) # type: ignore[type-var]\n\n return self.get_pname(node, position == VERB) or node.n3()\n\n def p_squared(self, node: Node, position: int, newline: bool = False) -> bool:\n if (\n not isinstance(node, BNode)\n or node in self._serialized\n or self._references[node] > 1\n or position == SUBJECT\n ):\n return False\n\n if not newline:\n self.write(\" \")\n\n if self.isValidList(node):\n # this is a list\n self.write(\"(\")\n self.depth += 1 # 2\n self.doList(node)\n self.depth -= 1 # 2\n self.write(\" )\")\n else:\n self.subjectDone(node)\n self.depth += 2\n # self.write('[\\n' + self.indent())\n self.write(\"[\")\n self.depth -= 1\n # self.predicateList(node, newline=True)\n self.predicateList(node, newline=False)\n # self.write('\\n' + self.indent() + ']')\n self.write(\" ]\")\n self.depth -= 1\n\n return True\n\n def isValidList(self, l_: Node) -> bool:\n \"\"\"\n Checks if l is a valid RDF list, i.e. no nodes have other properties.\n \"\"\"\n t\n... [truncated 1928 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-b459049af00b", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-b459049af00b", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "29eb45e55fd6a84c7e9754ff74a79090abf83660", "source_files": ["rdflib/plugins/serializers/longturtle.py", "rdflib/plugins/serializers/turtle.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Incorrect Deskolemization of Literals\n\n## Description\nWhen processing logical expressions containing literals, the deskolemization step produces incorrect results. This leads to an inaccurate representation or evaluation of the original expression. The expected behavior is that literals should be deskolemized correctly, maintaining the logical equivalence of the expression.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `747b8d30e6ca` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/graph.py\n```python\n\"\"\"\\\n\nRDFLib defines the following kinds of Graphs:\n\n* :class:`~rdflib.graph.Graph`\n* :class:`~rdflib.graph.QuotedGraph`\n* :class:`~rdflib.graph.ConjunctiveGraph`\n* :class:`~rdflib.graph.Dataset`\n\nGraph\n-----\n\nAn RDF graph is a set of RDF triples. Graphs support the python ``in``\noperator, as well as iteration and some operations like union,\ndifference and intersection.\n\nsee :class:`~rdflib.graph.Graph`\n\nConjunctive Graph\n-----------------\n\n.. warning::\n ConjunctiveGraph is deprecated, use :class:`~rdflib.graph.Dataset` instead.\n\nA Conjunctive Graph is the most relevant collection of graphs that are\nconsidered to be the boundary for closed world assumptions. This\nboundary is equivalent to that of the store instance (which is itself\nuniquely identified and distinct from other instances of\n:class:`~rdflib.store.Store` that signify other Conjunctive Graphs). It is\nequivalent to all the named graphs within it and associated with a\n``_default_`` graph which is automatically assigned a\n:class:`~rdflib.term.BNode` for an identifier - if one isn't given.\n\nsee :class:`~rdflib.graph.ConjunctiveGraph`\n\nQuoted graph\n------------\n\nThe notion of an RDF graph [14] is extended to include the concept of\na formula node. A formula node may occur wherever any other kind of\nnode can appear. Associated with a formula node is an RDF graph that\nis completely disjoint from all other graphs; i.e. has no nodes in\ncommon with any other graph. (It may contain the same labels as other\nRDF graphs; because this is, by definition, a separate graph,\nconsiderations of tidiness do not apply between the graph at a formula\nnode and any other graph.)\n\nThis is intended to map the idea of \"{ N3-expression }\" that is used\nby N3 into an RDF graph upon which RDF semantics is defined.\n\nsee :class:`~rdflib.graph.QuotedGraph`\n\nDataset\n-------\n\nThe RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The\nprimary term is \"graphs in the datasets\" and not \"contexts with quads\"\nso there is a separate method to set/retrieve a graph in a dataset and\nto operate with dataset graphs. As a consequence of this approach,\ndataset graphs cannot be identified with blank nodes, a name is always\nrequired (RDFLib will automatically add a name if one is not provided\nat creation time). This implementation includes a convenience method\nto directly add a single quad to a dataset graph.\n\nsee :class:`~rdflib.graph.Dataset`\n\nWorking with graphs\n===================\n\nInstantiating Graphs with default store (Memory) and default identifier\n(a BNode):\n\n >>> g = Graph()\n >>> g.store.__class__\n \n >>> g.identifier.__class__\n \n\nInstantiating Graphs with a Memory store and an identifier -\n:\n\n >>> g = Graph('Memory', URIRef(\"https://rdflib.github.io\"))\n >>> g.identifier\n rdflib.term.URIRef('https://rdflib.github.io')\n >>> str(g) # doctest: +NORMALIZE_WHITESPACE\n \" a rdfg:Graph;rdflib:storage\n [a rdflib:Store;rdfs:label 'Memory'].\"\n\nCreating a ConjunctiveGraph - The top level container for all named Graphs\nin a \"database\":\n\n >>> g = ConjunctiveGraph()\n >>> str(g.default_context)\n \"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']].\"\n\nAdding / removing reified triples to Graph and iterating over it directly or\nvia triple pattern:\n\n >>> g = Graph()\n >>> statementId = BNode()\n >>> print(len(g))\n 0\n >>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.subject,\n ... URIRef(\"https://rdflib.github.io/store/ConjunctiveGraph\"))) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n )>\n >>> g.add((statementId, RDF.object, Literal(\"Conjunctive Graph\"))) # doctest: +ELLIPSIS\n )>\n >>> print(len(g))\n 4\n >>> for s, p, o in g:\n ... print(type(s))\n ...\n \n \n \n \n\n >>> for s, p, o in g.triples((None, RDF.object, None)):\n ... print(o)\n ...\n Conjunctive Graph\n >>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> print(len(g))\n 3\n\n``None`` terms in calls to :meth:`~rdflib.graph.Graph.triples` can be\nthought of as \"open variables\".\n\nGraph support set-theoretic operators, you can add/subtract graphs, as\nwell as intersection (with multiplication operator g1*g2) and xor (g1\n^ g2).\n\nNote that BNode IDs are kept when doing set-theoretic operations, this\nmay or may not be what you want. Two named graphs within the same\napplication probably want share BNode IDs, two graphs with data from\ndifferent sources probably not. If your BNode IDs are all generated\nby RDFLib they are UUIDs and unique.\n\n >>> g1 = Graph()\n >>> g2 = Graph()\n >>> u = URIRef(\"http://example.com/foo\")\n >>> g1.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n )>\n >>> g1.add([u, namespace.RDFS.label, Literal(\"bar\")]) # doctest: +ELLIPSIS\n )>\n >>> g2.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n )>\n >>> g2.add([u, namespace.RDFS.label, Literal(\"bing\")]) # doctest: +ELLIPSIS\n )>\n >>> len(g1 + g2) # adds bing as label\n 3\n >>> len(g1 - g2) # removes foo\n 1\n >>> len(g1 * g2) # only foo\n 1\n >>> g1 += g2 # now g1 contains everything\n\n\nGraph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within\nthe same store:\n\n >>> store = plugin.get(\"Memory\", Store)()\n >>> g1 = Graph(store)\n >>> g2 = Graph(store)\n >>> g3 = Graph(store)\n >>> stmt1 = BNode()\n >>> stmt2 = BNode()\n >>> stmt3 = BNode()\n >>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n )>\n >>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS\n )>\n >>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.subject,\n ... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS\n )>\n >>> g3.add((stmt3, RDF.object, Literal(\n ... 'The top-level aggregate graph - The sum ' +\n ... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS\n )>\n >>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))\n 3\n >>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(\n ... RDF.type, RDF.Statement)))\n 2\n\nConjunctiveGraphs have a :meth:`~rdflib.graph.ConjunctiveGraph.quads` method\nwhich returns quads instead of triples, where the fourth item is the Graph\n(or subclass thereof) instance in which the triple was asserted:\n\n >>> uniqueGraphNames = set(\n ... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store\n ... ).quads((None, RDF.predicate, None))])\n >>> len(uniqueGraphNames)\n 3\n >>> unionGraph = ReadOnlyGraphAggregate([g1, g2])\n >>> uniqueGraphNames = set(\n ... [graph.identifier for s, p, o, graph in unionGraph.quads(\n ... (None, RDF.predicate, None))])\n >>> len(uniqueGraphNames)\n 2\n\nParsing N3 from a string\n\n >>> g2 = Graph()\n >>> src = '''\n ... @prefix rdf: .\n ... @prefix rdfs: .\n ... [ a rdf:Statement ;\n ... rdf:subject ;\n ... rdf:predicate rdfs:label;\n ... rdf:object \"Conjunctive Graph\" ] .\n ... '''\n >>> g2 = g2.parse(data=src, format=\"n3\")\n >>> print(len(g2))\n 4\n\nUsing Namespace class:\n\n >>> RDFLib = Namespace(\"https://rdflib.github.io/\")\n >>> RDFLib.ConjunctiveGraph\n rdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')\n >>> RDFLib[\"Graph\"]\n rdflib.term.URIRef('https://rdflib.github.io/Graph')\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport pathlib\nimport random\nimport warnings\nfrom io import BytesIO\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n BinaryIO,\n Callable,\n Dict,\n Generator,\n Iterable,\n List,\n Mapping,\n NoReturn,\n Optional,\n Set,\n TextIO,\n Tuple,\n Type,\n TypeVar,\n Union,\n cast,\n overload,\n)\nfrom urllib.parse import urlparse\nfrom urllib.request import url2pathname\n\nimport rdflib.exceptions as exceptions\nimport rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.\nimport rdflib.plugin as plugin\nimport rdflib.query as query\nimport rdflib.util # avoid circular dependency\nfrom rdflib.collection import Collection\nfrom rdflib.exceptions import ParserError\nfrom rdflib.namespace import RDF, Namespace, NamespaceManager\nfrom rdflib.parser import InputSource, Parser, create_input_source\nfrom rdflib.paths import Path\nfrom rdflib.resource import Resource\nfrom rdflib.serializer import Serializer\nfrom rdflib.store import Store\nfrom rdflib.term import (\n BNode,\n Genid,\n IdentifiedNode,\n Identifier,\n Literal,\n Node,\n RDFLibGenid,\n URIRef,\n)\n\nif TYPE_CHECKING:\n import typing_extensions as te\n\n import rdflib.query\n from rdflib.plugins.sparql.sparql import Query, Update\n\n_SubjectType = Node\n_PredicateType = Node\n_ObjectType = Node\n_ContextIdentifierType = IdentifiedNode\n\n_TripleType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\"]\n_QuadType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\", \"_ContextType\"]\n_OptionalQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextType\"]\n]\n_TripleOrOptionalQuadType = Union[\"_TripleType\", \"_OptionalQuadType\"]\n_OptionalIdentifiedQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextIdentifierType\"]\n]\n_TriplePatternType = Tuple[\n Optional[\"_SubjectType\"], Optional[\"_PredicateType\"], Optional[\"_ObjectType\"]\n]\n_TriplePathPatternType = Tuple[Optional[\"_SubjectType\"], Path, Optional[\"_ObjectType\"]]\n_QuadPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[\"_PredicateType\"],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_QuadPathPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Path,\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadPatternType = Union[\"_TriplePatternType\", \"_QuadPatternType\"]\n_TripleOrQuadPathPatternType = Union[\"_TriplePathPatternType\", \"_QuadPathPatternType\"]\n_TripleSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n]\n_QuadSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadSelectorType = Union[\"_TripleSelectorType\", \"_QuadSelectorType\"]\n_TriplePathType = Tuple[\"_SubjectType\", Path, \"_ObjectType\"]\n_TripleOrTriplePathType = Union[\"_TripleType\", \"_TriplePathType\"]\n_TripleChoiceType = Union[\n Tuple[List[_SubjectType], Optional[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], List[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], Optional[_PredicateType], List[_ObjectType]],\n]\n\n_GraphT = TypeVar(\"_GraphT\", bound=\"Graph\")\n_ConjunctiveGraphT = TypeVar(\"_ConjunctiveGraphT\", bound=\"ConjunctiveGraph\")\n_DatasetT = TypeVar(\"_DatasetT\", bound=\"Dataset\")\n\n# type error: Function \"Type[Literal]\" could always be true in boolean contex\nassert Literal # type: ignore[truthy-function] # avoid warning\n# type error: Function \"Type[Namespace]\" could always be true in boolean context\nassert Namespace # type: ignore[truthy-function] # avoid warning\n\nif TYPE_CHECKING:\n from rdflib._type_checking import _NamespaceSetString\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = [\n \"Graph\",\n \"ConjunctiveGraph\",\n \"QuotedGraph\",\n \"Seq\",\n \"ModificationException\",\n \"Dataset\",\n \"UnSupportedAggregateOperation\",\n \"ReadOnlyGraphAggregate\",\n \"BatchAddGraph\",\n \"_ConjunctiveGraphT\",\n \"_ContextIdentifierType\",\n \"_DatasetT\",\n \"_GraphT\",\n \"_ObjectType\",\n \"_OptionalIdentifiedQuadType\",\n \"_OptionalQuadType\",\n \"_PredicateType\",\n \"_QuadPathPatternType\",\n \"_QuadPatternType\",\n \"_QuadSelectorType\",\n \"_QuadType\",\n \"_SubjectType\",\n \"_TripleOrOptionalQuadType\",\n \"_TripleOrTriplePathType\",\n \"_TripleOrQuadPathPatternType\",\n \"_TripleOrQuadPatternType\",\n \"_TripleOrQuadSelectorType\",\n \"_TriplePathPatternType\",\n \"_TriplePathType\",\n \"_TriplePatternType\",\n \"_TripleSelectorType\",\n \"_TripleType\",\n]\n\n# : Transitive closure arg type.\n_TCArgT = TypeVar(\"_TCArgT\")\n\n\nclass Graph(Node):\n \"\"\"An RDF Graph: a Python object containing nodes and relations between them as\n RDF 'triples'.\n\n This is the central RDFLib object class and Graph objects are almost always present\n it all uses of RDFLib.\n\n The basic use is to create a Graph and iterate through or query its content, e.g.:\n\n >>> from rdflib import Graph, URIRef\n >>> g = Graph()\n\n >>> g.add((\n ... URIRef(\"http://example.com/s1\"), # subject\n ... URIRef(\"http://example.com/p1\"), # predicate\n ... URIRef(\"http://example.com/o1\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> g.add((\n ... URIRef(\"http://example.com/s2\"), # subject\n ... URIRef(\"http://example.com/p2\"), # predicate\n ... URIRef(\"http://example.com/o2\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> for triple in sorted(g): # simple looping\n ... print(triple)\n (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))\n (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))\n\n >>> # get the object of the triple with subject s1 and predicate p1\n >>> o = g.value(\n ... subject=URIRef(\"http://example.com/s1\"),\n ... predicate=URIRef(\"http://example.com/p1\")\n ... )\n\n\n The constructor a\n... [truncated 99554 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-f276bd6cc70b", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-f276bd6cc70b", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "747b8d30e6ca12c12fd895f7ae44685a828ff33a", "source_files": ["rdflib/graph.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `Dataset.add()` method has poor performance\n\n## Description\nThe `Dataset.add()` method exhibits significant performance degradation, particularly when adding multiple triples or graphs. This leads to unacceptably long execution times for operations involving frequent additions to a `Dataset`. The expected behavior is for `Dataset.add()` to be performant and efficient, even when handling a large number of additions.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `507a4e1d1a35` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### rdflib/graph.py\n```python\n\"\"\"\nRDFLib defines the following kinds of Graphs:\n\n* [`Graph`][rdflib.graph.Graph]\n* [`QuotedGraph`][rdflib.graph.QuotedGraph]\n* [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph]\n* [`Dataset`][rdflib.graph.Dataset]\n\n## Graph\n\nAn RDF graph is a set of RDF triples. Graphs support the python `in`\noperator, as well as iteration and some operations like union,\ndifference and intersection.\n\nSee [`Graph`][rdflib.graph.Graph]\n\n## Conjunctive Graph\n\n!!! warning \"Deprecation notice\"\n `ConjunctiveGraph` is deprecated, use [`Dataset`][rdflib.graph.Dataset] instead.\n\nA Conjunctive Graph is the most relevant collection of graphs that are\nconsidered to be the boundary for closed world assumptions. This\nboundary is equivalent to that of the store instance (which is itself\nuniquely identified and distinct from other instances of\n[`Store`][rdflib.store.Store] that signify other Conjunctive Graphs). It is\nequivalent to all the named graphs within it and associated with a\n`_default_` graph which is automatically assigned a\n[`BNode`][rdflib.term.BNode] for an identifier - if one isn't given.\n\nSee [`ConjunctiveGraph`][rdflib.graph.ConjunctiveGraph]\n\n## Quoted graph\n\nThe notion of an RDF graph [14] is extended to include the concept of\na formula node. A formula node may occur wherever any other kind of\nnode can appear. Associated with a formula node is an RDF graph that\nis completely disjoint from all other graphs; i.e. has no nodes in\ncommon with any other graph. (It may contain the same labels as other\nRDF graphs; because this is, by definition, a separate graph,\nconsiderations of tidiness do not apply between the graph at a formula\nnode and any other graph.)\n\nThis is intended to map the idea of \"{ N3-expression }\" that is used\nby N3 into an RDF graph upon which RDF semantics is defined.\n\nSee [`QuotedGraph`][rdflib.graph.QuotedGraph]\n\n## Dataset\n\nThe RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The\nprimary term is \"graphs in the datasets\" and not \"contexts with quads\"\nso there is a separate method to set/retrieve a graph in a dataset and\nto operate with dataset graphs. As a consequence of this approach,\ndataset graphs cannot be identified with blank nodes, a name is always\nrequired (RDFLib will automatically add a name if one is not provided\nat creation time). This implementation includes a convenience method\nto directly add a single quad to a dataset graph.\n\nSee [`Dataset`][rdflib.graph.Dataset]\n\n## Working with graphs\n\nInstantiating Graphs with default store (Memory) and default identifier\n(a BNode):\n\n```python\n>>> g = Graph()\n>>> g.store.__class__\n\n>>> g.identifier.__class__\n\n\n```\n\nInstantiating Graphs with a Memory store and an identifier -\n:\n\n```python\n>>> g = Graph('Memory', URIRef(\"https://rdflib.github.io\"))\n>>> g.identifier\nrdflib.term.URIRef('https://rdflib.github.io')\n>>> str(g) # doctest: +NORMALIZE_WHITESPACE\n\" a rdfg:Graph;rdflib:storage\n [a rdflib:Store;rdfs:label 'Memory'].\"\n\n```\n\nCreating a ConjunctiveGraph - The top level container for all named Graphs\nin a \"database\":\n\n```python\n>>> g = ConjunctiveGraph()\n>>> str(g.default_context)\n\"[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'Memory']].\"\n\n```\n\nAdding / removing reified triples to Graph and iterating over it directly or\nvia triple pattern:\n\n```python\n>>> g = Graph()\n>>> statementId = BNode()\n>>> print(len(g))\n0\n>>> g.add((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n)>\n>>> g.add((statementId, RDF.subject,\n... URIRef(\"https://rdflib.github.io/store/ConjunctiveGraph\"))) # doctest: +ELLIPSIS\n)>\n>>> g.add((statementId, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n)>\n>>> g.add((statementId, RDF.object, Literal(\"Conjunctive Graph\"))) # doctest: +ELLIPSIS\n)>\n>>> print(len(g))\n4\n>>> for s, p, o in g:\n... print(type(s))\n...\n\n\n\n\n\n>>> for s, p, o in g.triples((None, RDF.object, None)):\n... print(o)\n...\nConjunctive Graph\n>>> g.remove((statementId, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n)>\n>>> print(len(g))\n3\n\n```\n\n`None` terms in calls to [`triples()`][rdflib.graph.Graph.triples] can be\nthought of as \"open variables\".\n\nGraph support set-theoretic operators, you can add/subtract graphs, as\nwell as intersection (with multiplication operator g1*g2) and xor (g1\n^ g2).\n\nNote that BNode IDs are kept when doing set-theoretic operations, this\nmay or may not be what you want. Two named graphs within the same\napplication probably want share BNode IDs, two graphs with data from\ndifferent sources probably not. If your BNode IDs are all generated\nby RDFLib they are UUIDs and unique.\n\n```python\n>>> g1 = Graph()\n>>> g2 = Graph()\n>>> u = URIRef(\"http://example.com/foo\")\n>>> g1.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n)>\n>>> g1.add([u, namespace.RDFS.label, Literal(\"bar\")]) # doctest: +ELLIPSIS\n)>\n>>> g2.add([u, namespace.RDFS.label, Literal(\"foo\")]) # doctest: +ELLIPSIS\n)>\n>>> g2.add([u, namespace.RDFS.label, Literal(\"bing\")]) # doctest: +ELLIPSIS\n)>\n>>> len(g1 + g2) # adds bing as label\n3\n>>> len(g1 - g2) # removes foo\n1\n>>> len(g1 * g2) # only foo\n1\n>>> g1 += g2 # now g1 contains everything\n\n```\n\nGraph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within\nthe same store:\n\n```python\n>>> store = plugin.get(\"Memory\", Store)()\n>>> g1 = Graph(store)\n>>> g2 = Graph(store)\n>>> g3 = Graph(store)\n>>> stmt1 = BNode()\n>>> stmt2 = BNode()\n>>> stmt3 = BNode()\n>>> g1.add((stmt1, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n)>\n>>> g1.add((stmt1, RDF.subject,\n... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n)>\n>>> g1.add((stmt1, RDF.predicate, namespace.RDFS.label)) # doctest: +ELLIPSIS\n)>\n>>> g1.add((stmt1, RDF.object, Literal('Conjunctive Graph'))) # doctest: +ELLIPSIS\n)>\n>>> g2.add((stmt2, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n)>\n>>> g2.add((stmt2, RDF.subject,\n... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n)>\n>>> g2.add((stmt2, RDF.predicate, RDF.type)) # doctest: +ELLIPSIS\n)>\n>>> g2.add((stmt2, RDF.object, namespace.RDFS.Class)) # doctest: +ELLIPSIS\n)>\n>>> g3.add((stmt3, RDF.type, RDF.Statement)) # doctest: +ELLIPSIS\n)>\n>>> g3.add((stmt3, RDF.subject,\n... URIRef('https://rdflib.github.io/store/ConjunctiveGraph'))) # doctest: +ELLIPSIS\n)>\n>>> g3.add((stmt3, RDF.predicate, namespace.RDFS.comment)) # doctest: +ELLIPSIS\n)>\n>>> g3.add((stmt3, RDF.object, Literal(\n... 'The top-level aggregate graph - The sum ' +\n... 'of all named graphs within a Store'))) # doctest: +ELLIPSIS\n)>\n>>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement)))\n3\n>>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects(\n... RDF.type, RDF.Statement)))\n2\n\n```\n\nConjunctiveGraphs have a [`quads()`][rdflib.graph.ConjunctiveGraph.quads] method\nwhich returns quads instead of triples, where the fourth item is the Graph\n(or subclass thereof) instance in which the triple was asserted:\n\n```python\n>>> uniqueGraphNames = set(\n... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store\n... ).quads((None, RDF.predicate, None))])\n>>> len(uniqueGraphNames)\n3\n>>> unionGraph = ReadOnlyGraphAggregate([g1, g2])\n>>> uniqueGraphNames = set(\n... [graph.identifier for s, p, o, graph in unionGraph.quads(\n... (None, RDF.predicate, None))])\n>>> len(uniqueGraphNames)\n2\n\n```\n\nParsing N3 from a string:\n\n```python\n>>> g2 = Graph()\n>>> src = '''\n... @prefix rdf: .\n... @prefix rdfs: .\n... [ a rdf:Statement ;\n... rdf:subject ;\n... rdf:predicate rdfs:label;\n... rdf:object \"Conjunctive Graph\" ] .\n... '''\n>>> g2 = g2.parse(data=src, format=\"n3\")\n>>> print(len(g2))\n4\n\n```\n\nUsing Namespace class:\n\n```python\n>>> RDFLib = Namespace(\"https://rdflib.github.io/\")\n>>> RDFLib.ConjunctiveGraph\nrdflib.term.URIRef('https://rdflib.github.io/ConjunctiveGraph')\n>>> RDFLib[\"Graph\"]\nrdflib.term.URIRef('https://rdflib.github.io/Graph')\n\n```\n\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport pathlib\nimport random\nimport warnings\nfrom io import BytesIO\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n BinaryIO,\n Callable,\n Dict,\n Generator,\n Iterable,\n List,\n Mapping,\n NoReturn,\n Optional,\n Set,\n TextIO,\n Tuple,\n Type,\n TypeVar,\n Union,\n cast,\n overload,\n)\nfrom urllib.parse import urlparse\nfrom urllib.request import url2pathname\n\nimport rdflib.exceptions as exceptions\nimport rdflib.namespace as namespace # noqa: F401 # This is here because it is used in a docstring.\nimport rdflib.plugin as plugin\nimport rdflib.query as query\nimport rdflib.util # avoid circular dependency\nfrom rdflib.collection import Collection\nfrom rdflib.exceptions import ParserError\nfrom rdflib.namespace import RDF, Namespace, NamespaceManager\nfrom rdflib.parser import InputSource, Parser, create_input_source\nfrom rdflib.paths import Path\nfrom rdflib.resource import Resource\nfrom rdflib.serializer import Serializer\nfrom rdflib.store import Store\nfrom rdflib.term import (\n BNode,\n Genid,\n IdentifiedNode,\n Identifier,\n Literal,\n Node,\n RDFLibGenid,\n URIRef,\n)\n\nif TYPE_CHECKING:\n import typing_extensions as te\n\n import rdflib.query\n from rdflib.plugins.sparql.sparql import Query, Update\n\n_SubjectType = Node\n_PredicateType = Node\n_ObjectType = Node\n_ContextIdentifierType = IdentifiedNode\n\n_TripleType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\"]\n_QuadType = Tuple[\"_SubjectType\", \"_PredicateType\", \"_ObjectType\", \"_ContextType\"]\n_OptionalQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextType\"]\n]\n_TripleOrOptionalQuadType = Union[\"_TripleType\", \"_OptionalQuadType\"]\n_OptionalIdentifiedQuadType = Tuple[\n \"_SubjectType\", \"_PredicateType\", \"_ObjectType\", Optional[\"_ContextIdentifierType\"]\n]\n_TriplePatternType = Tuple[\n Optional[\"_SubjectType\"], Optional[\"_PredicateType\"], Optional[\"_ObjectType\"]\n]\n_TriplePathPatternType = Tuple[Optional[\"_SubjectType\"], Path, Optional[\"_ObjectType\"]]\n_QuadPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[\"_PredicateType\"],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_QuadPathPatternType = Tuple[\n Optional[\"_SubjectType\"],\n Path,\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadPatternType = Union[\"_TriplePatternType\", \"_QuadPatternType\"]\n_TripleOrQuadPathPatternType = Union[\"_TriplePathPatternType\", \"_QuadPathPatternType\"]\n_TripleSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n]\n_QuadSelectorType = Tuple[\n Optional[\"_SubjectType\"],\n Optional[Union[\"Path\", \"_PredicateType\"]],\n Optional[\"_ObjectType\"],\n Optional[\"_ContextType\"],\n]\n_TripleOrQuadSelectorType = Union[\"_TripleSelectorType\", \"_QuadSelectorType\"]\n_TriplePathType = Tuple[\"_SubjectType\", Path, \"_ObjectType\"]\n_TripleOrTriplePathType = Union[\"_TripleType\", \"_TriplePathType\"]\n_TripleChoiceType = Union[\n Tuple[List[_SubjectType], Optional[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], List[_PredicateType], Optional[_ObjectType]],\n Tuple[Optional[_SubjectType], Optional[_PredicateType], List[_ObjectType]],\n]\n\n_GraphT = TypeVar(\"_GraphT\", bound=\"Graph\")\n_ConjunctiveGraphT = TypeVar(\"_ConjunctiveGraphT\", bound=\"ConjunctiveGraph\")\n_DatasetT = TypeVar(\"_DatasetT\", bound=\"Dataset\")\n\n# type error: Function \"Type[Literal]\" could always be true in boolean contex\nassert Literal # type: ignore[truthy-function] # avoid warning\n# type error: Function \"Type[Namespace]\" could always be true in boolean context\nassert Namespace # type: ignore[truthy-function] # avoid warning\n\nif TYPE_CHECKING:\n from rdflib._type_checking import _NamespaceSetString\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = [\n \"Graph\",\n \"ConjunctiveGraph\",\n \"QuotedGraph\",\n \"Seq\",\n \"ModificationException\",\n \"Dataset\",\n \"UnSupportedAggregateOperation\",\n \"ReadOnlyGraphAggregate\",\n \"BatchAddGraph\",\n \"_ConjunctiveGraphT\",\n \"_ContextIdentifierType\",\n \"_DatasetT\",\n \"_GraphT\",\n \"_ObjectType\",\n \"_OptionalIdentifiedQuadType\",\n \"_OptionalQuadType\",\n \"_PredicateType\",\n \"_QuadPathPatternType\",\n \"_QuadPatternType\",\n \"_QuadSelectorType\",\n \"_QuadType\",\n \"_SubjectType\",\n \"_TripleOrOptionalQuadType\",\n \"_TripleOrTriplePathType\",\n \"_TripleOrQuadPathPatternType\",\n \"_TripleOrQuadPatternType\",\n \"_TripleOrQuadSelectorType\",\n \"_TriplePathPatternType\",\n \"_TriplePathType\",\n \"_TriplePatternType\",\n \"_TripleSelectorType\",\n \"_TripleType\",\n]\n\n# : Transitive closure arg type.\n_TCArgT = TypeVar(\"_TCArgT\")\n\n\n# Graph is a node because technically a formula-aware graph\n# take a Graph as subject or object, but we usually use QuotedGraph for that.\nclass Graph(Node):\n \"\"\"An RDF Graph: a Python object containing nodes and relations between them as\n RDF 'triples'.\n\n This is the central RDFLib object class and Graph objects are almost always present\n in all uses of RDFLib.\n\n Example:\n The basic use is to create a Graph and iterate through or query its content:\n\n ```python\n >>> from rdflib import Graph, URIRef\n >>> g = Graph()\n >>> g.add((\n ... URIRef(\"http://example.com/s1\"), # subject\n ... URIRef(\"http://example.com/p1\"), # predicate\n ... URIRef(\"http://example.com/o1\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> g.add((\n ... URIRef(\"http://example.com/s2\"), # subject\n ... URIRef(\"http://example.com/p2\"), # predicate\n ... URIRef(\"http://example.com/o2\"), # object\n ... )) # doctest: +ELLIPSIS\n )>\n\n >>> for triple in sorted(g): # simple looping\n ... print(triple)\n (rdflib.term.URIRef('http://example.com/s1'), rdflib.term.URIRef('http://example.com/p1'), rdflib.term.URIRef('http://example.com/o1'))\n (rdflib.term.URIRef('http://example.com/s2'), rdflib.term.URIRef('http://example.com/p2'), rdflib.term.URIRef('http://example.com/o2'))\n\n >>> # get the object of the triple with subject s1 and predicate p1\n >>> o = g.value(\n ... subject=URIRef(\"http://example.com/s1\"),\n ... predicate=URIRef(\"http://example.com/p1\")\n ... )\n\n ```\n\n\n Args:\n store: The constructor accepts one argument, the \"store\" that will be used to store the\n \n... [truncated 111305 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "RDFLib__rdflib-f64ed99fd17c", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/RDFLib__rdflib-f64ed99fd17c", "repo_key": "RDFLib__rdflib", "repo": "RDFLib/rdflib", "base_commit": "507a4e1d1a35add6e81c0dd8d08d4cc2b6627090", "source_files": ["rdflib/graph.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Corpus extractions produce invalid data\n\n## Description\nWhen performing corpus extractions, the system generates data that is incorrect or malformed. This issue leads to unreliable or unusable output, hindering subsequent data processing or analysis steps.\n\n**Expected behavior:** Corpus extractions should consistently produce valid and correctly structured data.\n**Actual behavior:** Corpus extractions yield invalid results.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `077d0fff5014` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### PERFORMANCE.md\n```python\n# Performance\n\nStatus as of April 2, 2026.\n\n## Results\n\n- Runtime path: deterministic whole-string parse, extraction-first for noisy text, LALR fallback only on misses. Earley is not used at runtime.\n- Test suite: `127 passed in 0.22s`\n- Tight loop: `19.52 us/input` at `10000` rounds\n- Internal path benchmark:\n - `fast exact`: `6.5 us`\n - `fast collection`: `19.5 us`\n - `extract hit`: `46.1 us`\n - `extract miss`: `13.6 us`\n- Cross-library snapshot from `benchmarks/benchmark_baselines.py`:\n - `timefhuman`: `56.1 us/input`, `37/37 ok`, `10/10 exact`\n - `parsedatetime`: `45.0 us/input`, `36/37 ok`, `6/10 exact`\n - `datefinder`: `42.9 us/input`, `23/37 ok`, `5/10 exact`\n - `recurrent`: `195.2 us/input`, `36/37 ok`, `6/10 exact`\n - `ctparse`: `12808.2 us/input`, `37/37 ok`, `3/10 exact`\n - `dateparser`: `49105.3 us/input`, `20/37 ok`, `6/10 exact`\n\n## Reproduce\n\nRun tests:\n\n```bash\n/tmp/timefhuman-bench-venv/bin/python -m pytest -q\n```\n\nRun the cross-library benchmark:\n\n```bash\n/tmp/timefhuman-bench-venv/bin/python benchmarks/benchmark_baselines.py\n```\n\nRun the internal path benchmark:\n\n```bash\n/tmp/timefhuman-bench-venv/bin/python benchmarks/benchmark_paths.py\n```\n\nRun the local tight loop:\n\n```bash\n/tmp/timefhuman-bench-venv/bin/python - <<'PY'\nimport time\nfrom datetime import datetime\nfrom benchmarks.benchmark_baselines import INPUTS\nfrom timefhuman import timefhuman\nfrom timefhuman.main import tfhConfig\n\ncfg = tfhConfig(now=datetime(2018, 8, 4, 14, 0))\nfor rounds in [1000, 5000, 10000]:\n start = time.perf_counter()\n for _ in range(rounds):\n for text in INPUTS:\n timefhuman(text, config=cfg)\n us = (time.perf_counter() - start) / (rounds * len(INPUTS)) * 1e6\n print(rounds, f\"{us:.2f} us/input\")\nPY\n```\n\n## Rule Of Thumb\n\nIf a change makes the LALR parser or noisy extraction run more often, it is probably a slowdown.\n\nThe fastest route is:\n\n1. deterministic whole-string parse for exact expressions\n2. bounded noisy extraction for prose-like inputs\n3. exact whole-string LALR fallback only when needed\n4. LALR extraction rescue only when the fast extractor misses\n\n```\n\n### timefhuman/fastpath.py\n```python\nimport re\nfrom datetime import timedelta\n\nfrom dateutil.relativedelta import relativedelta, weekdays\nimport pytz\n\nfrom timefhuman.inference import infer\nfrom timefhuman.renderers import tfhAmbiguous, tfhDatetime, tfhDate, tfhList, tfhRange, tfhTime, tfhTimedelta\nfrom timefhuman.semantics import (\n DATE_NAME_TO_OFFSET,\n DATE_TIME_NAME_TO_TEMPLATE,\n MODIFIER_TO_OFFSET,\n NUMBER_WORDS,\n POSITION_TO_DELTA,\n TIME_NAME_TO_TEMPLATE,\n UNIT_ALIASES,\n WEEKDAY_ALIASES,\n clone_datetime,\n clone_time,\n month_number,\n normalize_year,\n timedelta_for_unit,\n weekday_index,\n)\nfrom timefhuman.utils import Direction, direction_to_offset, get_timezone_word_lengths, tfhConfig\n\n\n__all__ = (\"parse_fast\",)\n\n\nMERIDIEM_PATTERN = r\"(?:[ap](?:\\.?m\\.?)?)\"\nTIME_PATTERN = re.compile(\n rf\"(?ix)^\"\n rf\"(?P\\d{{1,2}})\"\n rf\"(?::(?P\\d{{1,2}})\"\n rf\"(?::(?P\\d{{1,2}})(?:\\.(?P\\d{{1,6}}))?)?\"\n rf\")?\"\n rf\"\\s*(?P{MERIDIEM_PATTERN})?$\"\n)\nOCLOCK_PATTERN = re.compile(rf\"(?ix)^(?P\\d{{1,2}})\\s*o'?clock\\s*(?P{MERIDIEM_PATTERN})$\")\nNUMERIC_DATE_PATTERN = re.compile(r\"^(?P\\d{1,4})(?P[/-])(?P\\d{1,4})(?:(?P=sep)(?P\\d{1,4}))?$\")\nMONTHNAME_PATTERN = re.compile(\n r\"(?ix)^\"\n r\"(?P[a-z]+)\"\n r\"\\s+\"\n r\"(?P\\d{1,4})\"\n r\"(?Pst|nd|rd|th)?\"\n r\"(?:\\s*,?\\s*(?P\\d{2,4}))?$\"\n)\nDAY_MONTH_PATTERN = re.compile(\n r\"(?ix)^\"\n r\"(?P\\d{1,2})\"\n r\"(?Pst|nd|rd|th)?\"\n r\"\\s+\"\n r\"(?P[a-z]+)\"\n r\"(?:\\s*,?\\s*(?P\\d{2,4}))?$\"\n)\nDAY_YEAR_PATTERN = re.compile(\n r\"(?ix)^\"\n r\"(?P\\d{1,2})\"\n r\"(?Pst|nd|rd|th)?\"\n r\"(?:\\s*,\\s*|\\s+)\"\n r\"(?P\\d{2,4})$\"\n)\nDAY_SUFFIX_PATTERN = re.compile(r\"(?ix)^(?P\\d{1,2})(?:st|nd|rd|th)$\")\nPOSITION_WEEKDAY_MONTH_PATTERN = re.compile(\n r\"(?ix)^(?Pfirst|second|third|fourth|last)\\s+(?P[a-z]+)\\s+(?:of|in)\\s+(?P[a-z]+)$\"\n)\nISO_PATTERN = re.compile(\n r\"^(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})\"\n r\"T\"\n r\"(?P\\d{1,2}):(?P\\d{2})\"\n r\"(?::(?P\\d{2})(?:\\.(?P\\d{1,6}))?)?$\"\n)\nNUMBER_UNIT_PATTERN = re.compile(\n r\"(?ix)\"\n r\"(?P\\d+(?:\\.\\d+)?)\"\n r\"\\s*\"\n r\"(?Pseconds?|secs?|sec|minutes?|mins?|min|hours?|hour|hrs?|hr|days?|day|weeks?|week|wks?|wk|months?|month|mos|years?|year|yrs?|yr|mo|[smhdwy])\"\n)\n\n\ndef parse_fast(text: str, config: tfhConfig, timezone_mapping, start_pos: int = 0):\n stripped, span_start, span_end = _trimmed_span(text, start_pos)\n if not stripped:\n return None\n\n expression = _parse_expression(_normalize_space(stripped), config, timezone_mapping, allow_ambiguous=False)\n if expression is None:\n return None\n\n expression.matched_text_pos = (span_start, span_end)\n return [expression]\ndef _parse_expression(text: str, config: tfhConfig, timezone_mapping, allow_ambiguous: bool):\n if not text:\n return None\n\n if _prefer_collection_parse(text):\n parsers = (_parse_range, _parse_list) if _prefer_range_first(text) else (_parse_list, _parse_range)\n for parser in parsers:\n expression = parser(text, config, timezone_mapping)\n if expression is not None:\n return expression\n\n single = _parse_single(text, config, timezone_mapping, allow_ambiguous=allow_ambiguous)\n if single is not None:\n return single\n\n if not _prefer_collection_parse(text):\n parsers = (_parse_range, _parse_list) if _prefer_range_first(text) else (_parse_list, _parse_range)\n for parser in parsers:\n expression = parser(text, config, timezone_mapping)\n if expression is not None:\n return expression\n\n return None\n\n\ndef _parse_list(text: str, config: tfhConfig, timezone_mapping):\n body, tzinfo = _strip_trailing_timezone(text, timezone_mapping)\n\n patterns = [r\"\\s+or\\s+\"]\n if _supports_comma_list(body, config, timezone_mapping):\n patterns.append(r\"\\s*,\\s*\")\n\n for pattern in patterns:\n parts = [part.strip() for part in re.split(pattern, body) if part.strip()]\n if len(parts) < 2:\n continue\n\n items = []\n for part in parts:\n item = _parse_range_or_single(part, config, timezone_mapping, allow_ambiguous=True)\n if item is None:\n items = []\n break\n items.append(item)\n\n if items:\n result = tfhList(infer(items))\n if tzinfo:\n result.tz = tzinfo\n return result\n\n return None\n\n\ndef _parse_range(text: str, config: tfhConfig, timezone_mapping):\n body, tzinfo = _strip_trailing_timezone(text, timezone_mapping)\n\n if \" to \" in body.lower():\n parts = re.split(r\"(?i)\\s+to\\s+\", body, maxsplit=1)\n if len(parts) == 2:\n result = _build_range(parts[0], parts[1], config, timezone_mapping)\n if result and tzinfo:\n result.tz = tzinfo\n return result\n\n indices = [index for index, char in enumerate(body) if char == \"-\"]\n preferred = [index for index in indices if _looks_like_range_hyphen(body, index)]\n for index in preferred + [item for item in indices if item not in preferred]:\n result = _build_range(body[:index], body[index + 1 :], config, timezone_mapping)\n if result:\n if tzinfo:\n result.tz = tzinfo\n return result\n\n return None\n\n\ndef _build_range(left_text: str, right_text: str, config: tfhConfig, timezone_mapping):\n left = _parse_single(left_text.strip(), config, timezone_mapping, allow_ambiguous=True)\n right = _parse_single(right_text.strip(), config, timezone_mapping, allow_ambiguous=True)\n if left is None or right is None:\n return None\n return tfhRange(infer([left, right]))\n\n\ndef _parse_range_or_single(text: str, config: tfhConfig, timezone_mapping, allow_ambiguous: bool):\n return _parse_range(text, config, timezone_mapping) or _parse_single(\n text, config, timezone_mapping, allow_ambiguous=allow_ambiguous\n )\n\n\ndef _parse_single(text: str, config: tfhConfig, timezone_mapping, allow_ambiguous: bool):\n duration = _parse_duration(text)\n if duration is not None:\n return duration\n\n datetime_like = _parse_datetime(text, config, timezone_mapping)\n if datetime_like is not None:\n return datetime_like\n\n if allow_ambiguous and text.isdigit():\n return tfhAmbiguous(int(text))\n\n return None\n\n\ndef _parse_datetime(text: str, config: tfhConfig, timezone_mapping):\n text = _normalize_space(text)\n if not text:\n return None\n\n body, tzinfo = _strip_trailing_timezone(text, timezone_mapping)\n if not body:\n return None\n\n atomic = _parse_atomic_datetime(body, config, tzinfo)\n if atomic is not None:\n return atomic\n\n lower_body = body.lower()\n for separator, mode in ((\" at \", \"date_time\"), (\" on \", \"time_date\")):\n if separator in lower_body:\n left, right = re.split(rf\"(?i){separator.strip()}\", body, maxsplit=1)\n if mode == \"date_time\":\n date = _parse_date(left, config)\n time = _parse_time_component(right, allow_houronly=True)\n else:\n time = _parse_time_component(left, allow_houronly=True)\n date = _parse_date(right, config)\n if date and time:\n return tfhDatetime(date=date, time=time, tz=tzinfo)\n\n parts = body.split()\n best = None\n best_score = -1\n for index in range(1, len(parts)):\n left = \" \".join(parts[:index])\n right = \" \".join(parts[index:])\n\n date = _parse_date(left, config)\n time = _parse_time_component(right, allow_houronly=True)\n if date and time:\n score = _date_score(date) + _time_score(time)\n if score > best_score:\n best = tfhDatetime(date=date, time=time, tz=tzinfo)\n best_score = score\n\n time = _parse_time_component(left, allow_houronly=True)\n date = _parse_date(right, config)\n if date and time:\n score = _date_score(date) + _time_score(time)\n if score > best_score:\n best = tfhDatetime(date=date, time=time, tz=tzinfo)\n best_score = score\n\n return best\n\n\ndef _parse_atomic_datetime(text: str, config: tfhConfig, tzinfo):\n lower_body = text.lower()\n iso_match = ISO_PATTERN.fullmatch(text)\n if iso_match:\n return tfhDatetime(\n date=tfhDate(\n year=int(iso_match.group(\"year\")),\n month=int(iso_match.group(\"month\")),\n day=int(iso_match.group(\"day\")),\n ),\n time=tfhTime(\n hour=int(iso_match.group(\"hour\")),\n minute=int(iso_match.group(\"minute\")),\n second=int(iso_match.group(\"second\") or 0),\n millisecond=int(iso_match.group(\"millisecond\") or 0),\n ),\n tz=tzinfo,\n )\n\n if lower_body in DATE_TIME_NAME_TO_TEMPLATE:\n value = clone_datetime(DATE_TIME_NAME_TO_TEMPLATE[lower_body])\n value.date = tfhDate.from_object(config.now.date())\n value.tz = tzinfo\n return value\n\n time = _parse_time_component(text, allow_houronly=False)\n if time is not None:\n return tfhDatetime(time=time, tz=tzinfo)\n\n date = _parse_date(text, config)\n if date is not None:\n return tfhDatetime(date=date, tz=tzinfo)\n\n return None\n\n\ndef _parse_date(text: str, config: tfhConfig):\n text = _normalize_space(text)\n if not text:\n return None\n lower = text.lower()\n\n if lower in DATE_NAME_TO_OFFSET:\n return tfhDate.from_object(config.now.date() + timedelta(days=DATE_NAME_TO_OFFSET[lower]))\n\n match = POSITION_WEEKDAY_MONTH_PATTERN.fullmatch(lower)\n if match:\n weekday = _parse_weekday_name(match.group(\"weekday\"))\n month = _parse_month_name(match.group(\"month\"))\n if weekday is None or month is None:\n return None\n return tfhDate(month=month, delta=POSITION_TO_DELTA[match.group(\"position\")](weekdays[weekday]))\n\n tokens = lower.split()\n offset, remainder = _parse_modifier_prefix(tokens)\n if len(remainder) == 1:\n weekday = _parse_weekday_name(remainder[0])\n if weekday is not None:\n if tokens[: len(tokens) - 1]:\n weekday_offset = offset\n else:\n weekday_offset = direction_to_offset(config.direction)\n value = config.now.date() + relativedelta(weekday=weekdays[weekday](weekday_offset))\n return tfhDate.from_object(value)\n\n month = _parse_month_name(remainder[0])\n if month is not None and tokens[: len(tokens) - 1]:\n return tfhDate(month=month, delta=relativedelta(years=offset))\n\n stripped = _strip_leading_weekday(text) if len(tokens) >= 2 else text\n if stripped.lower() in DATE_NAME_TO_OFFSET:\n return tfhDate.from_object(config.now.date() + timedelta(days=DATE_NAME_TO_OFFSET[stripped.lower()]))\n\n numeric = _parse_numeric_date(stripped)\n if numeric is not None:\n return numeric\n\n monthname = _parse_monthname_date(stripped)\n if monthname is not None:\n return monthname\n\n day_month_or_year = _parse_day_month_or_year(stripped)\n if day_month_or_year is not None:\n return day_month_or_year\n\n day_suffix = DAY_SUFFIX_PATTERN.fullmatch(lower)\n if day_suffix:\n return tfhDate(day=int(day_suffix.group(\"day\")))\n\n weekday = _parse_weekday_name(lower)\n if weekday is not None:\n value = config.now.date() + relativedelta(weekday=weekdays[weekday](direction_to_offset(config.direction)))\n return tfhDate.from_object(value)\n\n return None\n\n\ndef _parse_numeric_date(text: str):\n match = NUMERIC_DATE_PATTERN.fullmatch(text)\n if not match:\n return None\n\n first = int(match.group(\"a\"))\n second = int(match.group(\"b\"))\n third = match.group(\"c\")\n\n if third is None:\n if second > 31:\n return tfhDate(month=first, year=normalize_year(second))\n return tfhDate(month=first, day=second)\n\n if len(match.group(\"a\")) == 4:\n return tfhDate(year=first, month=second, day=int(third))\n return tfhDate(month=first, day=second, year=normalize_year(int(third)))\n\n\ndef _parse_monthname_date(text: str):\n match = MONTHNAME_PATTERN.fullmatch(text)\n if not match:\n return None\n\n month = _parse_month_name(match.group(\"month\"))\n if month is None:\n return None\n\n first = int(match.group(\"first\"))\n suffix = match.group(\"suffix\")\n year = match.group(\"year\")\n\n if year is not None:\n return tfhDate(month=month, day=first, year=normalize_year(int(year)))\n if suffix or first <= 31:\n return tfhDate(month=month, day=first)\n return tfhDate(month=month, year=normalize_year(first))\n\n\ndef _parse_day_month_or_year(text: str):\n match = DAY_MONTH_PATTERN.fullmatch(text)\n if match:\n month = _parse_month_name(match.group(\"month\"))\n if month is None:\n return None\n year = match.group(\"year\")\n if year is not None:\n return tfhDate(day=int(match.group(\"day\")), month=month, year=normalize_year(int(year)))\n return tfhDate(day=int(match.group(\"day\")), month=month)\n\n match = DAY_YEAR_PATTERN.fullmatch(text)\n if match:\n return tfhDate(day=int(match.group(\"day\")), year=normalize_year(int(match.group(\"year\"))))\n\n return None\n\n\ndef _parse_time_component(text: str, allow_houronly: bool):\n text = _normalize_space(text)\n if not text:\n return None\n lowered = text.lower()\n if lowered in TIME_NAME_TO_TEMPLATE:\n return clone_time(TIME_NAME_TO_TEMPLATE[lowered])\n\n match = OCLOCK_PATTERN.fullmatch(lowered)\n if match:\n return tfhTime(hour=int(match.group(\"hour\")), meridiem=_parse_meridiem(match.group(\"meridiem\")))\n\n match = TIME_PATTERN.fullmatch(lowered)\n if not match:\n return None\n\n meridiem = _parse_meridiem(match.group(\"meridiem\"))\n if meridiem is None and match.group(\"minute\") is None and not allow_houronly:\n return None\n\n return tfhTime(\n hour=int(match.group(\"hour\")),\n minute=int(match.group(\"minute\") or 0),\n second=int(match.group(\"second\") or 0),\n millisecond=int(match.group(\"millisecond\") or 0),\n meridiem=meridiem,\n )\n\n\ndef _parse_duration(text: str):\n lowered = text.lower()\n direction = Direction.next\n if lowered.startswith(\"in \"):\n lowered = lowered[3:].strip()\n elif lowered.startswith(\"for \"):\n lowered = lowered[4:].strip()\n\n if lowered.endswith(\" ago\"):\n lowered = lowered[:-4].strip()\n direction = Direction.previous\n\n position = 0\n total = timedelta()\n unit = None\n while position < len(lowered):\n while position < len(lowered) and lowered[position] in \" ,\":\n position += 1\n if lowered[position : position + 4] == \"and \":\n position += 4\n continue\n if position >= len(lowered):\n break\n\n numeric_match = NUMBER_UNIT_PATTERN.match(lowered, position)\n if numeric_match:\n amount = float(numeric_match.group(\"number\"))\n normalized_unit = UNIT_ALIASES[numeric_match.group(\"unit\")]\n total += timedelta_for_unit(normalized_unit, amount)\n unit = unit or normalized_unit\n position = numeric_match.end()\n continue\n\n word_match = re.match(r\"[a-z]+(?:\\s+[a-z]+)*\", lowered[position:])\n if not word_match:\n return None\n\n consumed = _consume_word_duration(word_match.group(0))\n if consumed is None:\n return None\n amount, normalized_unit, segment_len = consumed\n total += timedelta_for_unit(normalized_unit, amount)\n unit = unit or normalized_unit\n \n... [truncated 4188 chars]\n\n```\n\n### timefhuman/grammar.lark\n```python\n%import common.WS\n%import common.INT\n%ignore WS\n\n// ----------------------\n// TERMINAL DEFINITIONS\n// ----------------------\n\nMONTHNAME: /(?[a-z]+)\"\n r\"\\s+\"\n r\"(?P\\d{1,4})\"\n r\"(?Pst|nd|rd|th)?\"\n r\"(?:\\s*,?\\s*(?P\\d{2,4}))?$\"\n)\nDAY_ORDINAL_PATTERN = re.compile(r\"(?i)^(?P\\d{1,2})(?:st|nd|rd|th)$\")\n\n\ndef get_lalr_parser():\n global lalr_parsers, timezone_mapping\n if 'default' not in lalr_parsers:\n timezone_mapping = generate_timezone_mapping()\n with open(DIRECTORY / 'grammar.lark', 'r') as file:\n grammar = file.read()\n grammar = grammar.replace('(TIMEZONE_MAPPING)', '|'.join(timezone_mapping.keys()))\n lalr_parsers['default'] = Lark(\n grammar,\n start=\"start\",\n parser=\"lalr\",\n lexer=\"contextual\",\n g_regex_flags=re.IGNORECASE,\n )\n return lalr_parsers['default']\n\n\ndef _trimmed_span(string: str, start_pos: int = 0):\n stripped = string.strip()\n if not stripped:\n return \"\", start_pos, start_pos\n leading = len(string) - len(string.lstrip())\n trailing = len(string.rstrip())\n return stripped, start_pos + leading, start_pos + trailing\n\n\ndef parse_lalr_renderers(string: str, config: tfhConfig, start_pos: int = 0):\n stripped, span_start, span_end = _trimmed_span(string, start_pos)\n if not stripped:\n return None\n\n try:\n tree = get_lalr_parser().parse(stripped)\n except UnexpectedInput:\n return None\n\n renderers = tfhTransformer(config=config).transform(tree)\n for renderer in renderers:\n renderer.matched_text_pos = (span_start, span_end)\n return renderers\n\n\nclass tfhTransformer(Transformer):\n def __init__(self, config: tfhConfig = tfhConfig()):\n self.config = config\n\n def start(self, children):\n return children\n\n def expression(self, children):\n return children[0]\n\n def single(self, children):\n return children[0]\n\n def range_item(self, children):\n return children[0]\n\n def list_item(self, children):\n return children[0]\n\n def range(self, children):\n assert len(children) == 2\n return tfhRange(infer(children))\n\n def list(self, children):\n return tfhList(infer(children))\n\n def duration(self, children):\n config = replace(self.config, infer_datetimes=False)\n direction = Direction.next\n total = timedelta()\n unit = None\n for child in children:\n if hasattr(child, \"type\"):\n if child.type == 'DURATION_PAST':\n direction = Direction.previous\n elif child.type == 'DURATION_FUTURE':\n direction = Direction.next\n else:\n total += child.to_object(config)\n if unit is None:\n unit = child.unit\n\n if direction == Direction.previous:\n total = -total\n return tfhTimedelta.from_object(total, unit=unit)\n\n def duration_part(self, children):\n data = {child.data.value: [_child.value for _child in child.children] for child in children}\n duration_number = float(data['duration_number'][0]) if 'duration_number' in data else sum(\n NUMBER_WORDS[value] for value in data.get('duration_numbername', [])\n )\n duration_unit = UNIT_ALIASES[data.get('duration_unit', data.get('duration_unit_letter', None))[0]]\n return tfhTimedelta.from_object(timedelta_for_unit(duration_unit, duration_number), unit=duration_unit)\n\n def datetime(self, children):\n data = nodes_to_dict(children)\n if 'datetime' in data:\n return data['datetime']\n return tfhDatetime(date=data.get('date'), time=data.get('time'), tz=data.get('timezone'))\n\n def date(self, children):\n data = nodes_to_dict(children)\n\n if 'date' in data:\n return {'date': data['date']}\n\n if 'weekday' in data and all(key not in data for key in ('day', 'month', 'year')):\n return {'date': data['weekday']}\n\n delta = None\n if 'offset' in data and 'month' in data and 'weekday' in data:\n weekday = weekdays[data['weekday'].to_object(self.config).weekday()]\n offset = sum(nodes_to_multidict(children)['offset'])\n if offset == -1:\n delta = relativedelta(day=31, weekday=weekday(-1))\n elif offset == 1:\n delta = relativedelta(day=1, weekday=weekday(+1))\n elif 'offset' in data:\n delta = relativedelta(years=sum(nodes_to_multidict(children)['offset']))\n elif 'position' in data:\n weekday = weekdays[data['weekday'].to_object(self.config).weekday()]\n delta = POSITION_TO_DELTA[data['position']](weekday)\n\n return {'date': tfhDate(\n year=data.get('year'),\n month=data.get('month'),\n day=data.get('day'),\n delta=delta,\n )}\n\n def numeric_date(self, children):\n value = children[0].value\n sep = '/' if '/' in value else '-'\n parts = [int(part) for part in value.split(sep)]\n first, second = parts[0], parts[1]\n\n if len(parts) == 2:\n if second > 31:\n return {'date': tfhDate(month=first, year=normalize_year(second))}\n return {'date': tfhDate(month=first, day=second)}\n\n third = parts[2]\n if first >= 1000:\n return {'date': tfhDate(year=first, month=second, day=third)}\n return {'date': tfhDate(month=first, day=second, year=normalize_year(third))}\n\n def day(self, children):\n return {'day': int(children[0].value)}\n\n def month(self, children):\n return {'month': int(children[0].value)}\n\n def year(self, children):\n return {'year': normalize_year(int(children[0].value))}\n\n def monthname(self, children):\n return {'month': month_number(children[0].value, self.config.now.month)}\n\n def monthname_date(self, children):\n match = MONTHNAME_DATE_PATTERN.fullmatch(children[0].value)\n if match is None:\n raise NotImplementedError(f\"Unknown monthname date: {children[0].value}\")\n\n month = month_number(match.group('month'), self.config.now.month)\n first = int(match.group('first'))\n year = match.group('year')\n\n if year is not None:\n return {'date': tfhDate(month=month, day=first, year=normalize_year(int(year)))}\n if match.group('suffix') or first <= 31:\n return {'date': tfhDate(month=month, day=first)}\n return {'date': tfhDate(month=month, year=normalize_year(first))}\n\n def day_ordinal(self, children):\n match = DAY_ORDINAL_PATTERN.fullmatch(children[0].value)\n if match is None:\n raise NotImplementedError(f\"Unknown day ordinal: {children[0].value}\")\n return {'date': tfhDate(day=int(match.group('day')))}\n\n def modified_month(self, children):\n offset = sum(child['offset'] for child in children[:-1])\n month = month_number(children[-1].value, self.config.now.month)\n return {'month': month, 'offset': offset}\n\n def weekday(self, children):\n target_weekday = weekday_index(children[0].value)\n offset = direction_to_offset(self.config.direction)\n date = self.config.now.date() + relativedelta(weekday=weekdays[target_weekday](offset))\n return {'weekday': tfhDate.from_object(date)}\n\n def modified_weekday(self, children):\n offset = sum(child['offset'] for child in children[:-1])\n target_weekday = weekday_index(children[-1].value)\n date = self.config.now.date() + relativedelta(weekday=weekdays[target_weekday](offset))\n return {'weekday': tfhDate.from_object(date)}\n\n def modifier(self, children):\n value = children[0].value\n if value not in MODIFIER_TO_OFFSET:\n raise NotImplementedError(f\"Unknown modifier: {value}\")\n return {'offset': MODIFIER_TO_OFFSET[value]}\n\n def datename(self, children):\n datename = children[0].value.lower()\n if datename not in DATE_NAME_TO_OFFSET:\n raise NotImplementedError(f\"Unknown datename: {datename}\")\n return {'date': tfhDate.from_object(self.config.now.date() + timedelta(days=DATE_NAME_TO_OFFSET[datename]))}\n\n def dayoryear(self, children):\n if children[0].value.isdigit():\n value = int(children[0].value)\n return {'day': value} if value < 32 else {'year': value}\n raise NotImplementedError(f\"Unknown day or year: {children[0]}\")\n\n def ambiguous(self, children):\n return tfhAmbiguous(int(children[0].value))\n\n def time(self, children):\n data = nodes_to_dict(children)\n\n if 'time' in data:\n return {'time': data['time']}\n\n return {'time': tfhTime(\n hour=int(data.get(\"hour\", 0)),\n minute=int(data.get(\"minute\", 0)),\n second=int(data.get(\"second\", 0)),\n millisecond=int(data.get(\"millisecond\", 0)),\n meridiem=data.get(\"meridiem\", None)\n )}\n\n def meridiem(self, children):\n meridiem = children[0].value.lower()\n if meridiem.startswith('a'):\n return {'meridiem': tfhTime.Meridiem.AM}\n if meridiem.startswith('p'):\n return {'meridiem': tfhTime.Meridiem.PM}\n raise NotImplementedError(f\"Unknown meridiem: {meridiem}\")\n\n def timezone(self, children):\n timezone = children[0].value.lower()\n return {'timezone': pytz.timezone(timezone_mapping[timezone])}\n\n def timename(self, children):\n timename = children[0].value.lower()\n if timename not in TIME_NAME_TO_TEMPLATE:\n raise NotImplementedError(f\"Unknown timename: {timename}\")\n return {'time': clone_time(TIME_NAME_TO_TEMPLATE[timename])}\n\n def houronly(self, children):\n return {'time': tfhTime(hour=int(children[0].value))}\n\n def datetimename(self, children):\n datetimename = children[0].value.lower()\n if datetimename not in DATE_TIME_NAME_TO_TEMPLATE:\n raise NotImplementedError(f\"Unknown datetimename: {datetimename}\")\n value = clone_datetime(DATE_TIME_NAME_TO_TEMPLATE[datetimename])\n value.date = tfhDate.from_object(self.config.now.date())\n return {'datetime': value}\n\n def iso_datetime(self, children):\n value = children[0].value\n date_part, time_part = value.split('T', 1)\n year, month, day = [int(part) for part in date_part.split('-')]\n\n millisecond = 0\n second = 0\n if '.' in time_part:\n time_part, fraction = time_part.split('.', 1)\n millisecond = int(fraction)\n time_parts = [int(part) for part in time_part.split(':')]\n hour, minute = time_parts[:2]\n if len(time_parts) > 2:\n second = time_parts[2]\n\n return {'datetime': tfhDatetime(\n date=tfhDate(year=year, month=month, day=day),\n time=tfhTime(hour=hour, minute=minute, second=second, millisecond=millisecond),\n )}\n\n```\n\n### timefhuman/main.py\n```python\nfrom datetime import datetime\nimport re\n\nfrom dataclasses import replace\nfrom lark import Tree, Token\nfrom timefhuman.extraction import extract_fast, prefer_extraction\nfrom timefhuman.lalr import parse_lalr_renderers as _parse_lalr\nfrom timefhuman.utils import Direction, generate_timezone_mapping, tfhConfig\nfrom timefhuman.fastpath import parse_fast\nfrom timefhuman.renderers import tfhAmbiguous\n\n\n__all__ = (\"timefhuman\", \"tfhConfig\", \"Direction\", \"DEFAULT_CONFIG\")\n\n\nDEFAULT_CONFIG = tfhConfig()\nRAW_TOKEN_PATTERN = re.compile(r\"\\d+(?:[/:.-]\\d+)*(?:[ap](?:\\.?m\\.?)?)?|[a-z]+(?:\\.[a-z]+\\.?)?|\\S\", re.IGNORECASE)\n\n\ndef _build_candidate_parsers(config: tfhConfig):\n timezone_mapping = generate_timezone_mapping()\n\n def parse_fast_candidate(string: str, start_pos: int = 0):\n return parse_fast(string, config=config, timezone_mapping=timezone_mapping, start_pos=start_pos)\n\n def parse_lalr_candidate(string: str, start_pos: int = 0):\n return _parse_lalr(string, config=config, start_pos=start_pos)\n\n return parse_fast_candidate, parse_lalr_candidate\n\n\ndef _parse_renderers(string: str, config: tfhConfig):\n parse_fast_candidate, parse_lalr_candidate = _build_candidate_parsers(config)\n use_extraction = prefer_extraction(string)\n\n if use_extraction:\n for parse_candidate in (parse_fast_candidate, parse_lalr_candidate):\n renderers = extract_fast(string, parse_candidate=parse_candidate)\n if renderers is not None:\n return renderers\n return []\n\n renderers = parse_fast_candidate(string)\n if renderers is not None:\n return renderers\n\n renderers = parse_lalr_candidate(string)\n if renderers is not None:\n return renderers\n\n for parse_candidate in (parse_fast_candidate, parse_lalr_candidate):\n renderers = extract_fast(string, parse_candidate=parse_candidate)\n if renderers is not None:\n return renderers\n\n return []\n\n\ndef _matched_results(string: str, renderers, config: tfhConfig):\n positions = [(renderer.matched_text_pos[0], renderer.matched_text_pos[1]) for renderer in renderers]\n matched_texts = [string[start:end] for start, end in positions]\n datetimes = [renderer.to_object(config) for renderer in renderers]\n return list(zip(matched_texts, positions, datetimes))\n\n\ndef build_raw_tree(string: str, config: tfhConfig):\n match_config = replace(config, return_matched_text=True)\n renderers = _parse_renderers(string, match_config)\n\n children = []\n cursor = 0\n for start, end in [(renderer.matched_text_pos[0], renderer.matched_text_pos[1]) for renderer in renderers]:\n children.extend(_unknown_children(string[cursor:start]))\n children.append(Tree('expression', [Token('MATCH', string[start:end])]))\n cursor = end\n children.extend(_unknown_children(string[cursor:]))\n return Tree('start', children)\n\n\ndef _unknown_children(text: str):\n return [Tree('unknown', [Token('UNKNOWN', match.group(0))]) for match in RAW_TOKEN_PATTERN.finditer(text)]\n\n\ndef timefhuman(string, config: tfhConfig = DEFAULT_CONFIG, raw: bool=False, now: bool=False):\n if not string.strip():\n assert not raw, \"Empty string not allowed when raw=True\"\n return []\n\n config = config if config.now is not None else replace(config, now=datetime.now())\n if now:\n return config.now\n\n if raw:\n return build_raw_tree(string, config)\n\n renderers = [renderer for renderer in _parse_renderers(string, config) if not isinstance(renderer, tfhAmbiguous)]\n\n if config.return_matched_text:\n return _matched_results(string, renderers, config)\n return [renderer.to_object(config) for renderer in renderers]\n\n```\n\n### timefhuman/semantics.py\n```python\nfrom datetime import timedelta\n\nfrom dateutil.relativedelta import relativedelta\n\nfrom timefhuman.renderers import tfhDatetime, tfhTime\nfrom timefhuman.utils import get_month_mapping\n\n\ndef _expand_aliases(groups):\n return {alias: value for value, names in groups for alias in names.split()}\n\n\ndef _time(hour: int, meridiem, minute: int = 0):\n return tfhTime(hour=hour, minute=minute, meridiem=meridiem)\n\n\nTIME_NAME_TO_TEMPLATE = {\n **{name: _time(12, tfhTime.Meridiem.PM) for name in (\"noon\", \"midday\")},\n \"midnight\": _time(0, tfhTime.Meridiem.AM),\n \"morning\": _time(6, tfhTime.Meridiem.AM),\n \"afternoon\": _time(15, tfhTime.Meridiem.PM),\n \"evening\": _time(18, tfhTime.Meridiem.PM),\n \"night\": _time(20, tfhTime.Meridiem.PM),\n}\nDATE_NAME_TO_OFFSET = {\"today\": 0, \"tomorrow\": 1, \"tmw\": 1, \"yesterday\": -1}\nDATE_TIME_NAME_TO_TEMPLATE = {\n \"tonight\": tfhDatetime(date=None, time=_time(20, tfhTime.Meridiem.PM)),\n}\nMODIFIER_TO_OFFSET = _expand_aliases(\n (\n (1, \"next upcoming following\"),\n (-1, \"previous last past preceding\"),\n (0, \"this\"),\n )\n)\nPOSITION_TO_DELTA = {\n \"first\": lambda weekday: relativedelta(day=1, weekday=weekday(+1)),\n \"second\": lambda weekday: relativedelta(day=8, weekday=weekday(+1)),\n \"third\": lambda weekday: relativedelta(day=15, weekday=weekday(+1)),\n \"fourth\": lambda weekday: relativedelta(day=22, weekday=weekday(+1)),\n \"last\": lambda weekday: relativedelta(day=31, weekday=weekday(-1)),\n}\nNUMBER_WORDS = _expand_aliases(\n (\n (1, \"a an one\"),\n (2, \"two\"),\n (3, \"three\"),\n (4, \"four\"),\n (5, \"five\"),\n (6, \"six\"),\n (7, \"seven\"),\n (8, \"eight\"),\n (9, \"nine\"),\n (10, \"ten\"),\n (11, \"eleven\"),\n (12, \"twelve\"),\n (13, \"thirteen\"),\n (14, \"fourteen\"),\n (15, \"fifteen\"),\n (16, \"sixteen\"),\n (17, \"seventeen\"),\n (18, \"eighteen\"),\n (19, \"nineteen\"),\n (20, \"twenty\"),\n (30, \"thirty\"),\n (40, \"forty\"),\n (50, \"fifty\"),\n (60, \"sixty\"),\n (70, \"seventy\"),\n (80, \"eighty\"),\n (90, \"ninety\"),\n )\n)\nUNIT_ALIASES = _expand_aliases(\n (\n (\"seconds\", \"second seconds sec secs s\"),\n (\"minutes\", \"minute minutes min mins m\"),\n (\"hours\", \"hour hours hr hrs h\"),\n (\"days\", \"day days d\"),\n (\"weeks\", \"week weeks wk wks w\"),\n (\"months\", \"month months mos mo\"),\n (\"years\", \"year years yr yrs y\"),\n )\n)\nWEEKDAY_ALIASES = _expand_aliases(\n (\n (0, \"monday mon\"),\n (1, \"tuesday tues tue tu\"),\n (2, \"wednesday wed\"),\n (3, \"thursday thurs thur thu\"),\n (4, \"friday fri\"),\n (5, \"saturday sat\"),\n (6, \"sunday sun\"),\n )\n)\n\n\ndef normalize_year(value: int):\n if 50 < value < 100:\n return 1900 + value\n if 0 < value < 50:\n return 2000 + value\n return value\n\n\ndef clone_time(template: tfhTime):\n return tfhTime(\n hour=template.hour,\n minute=template.minute,\n second=template.second,\n millisecond=template.millisecond,\n meridiem=template.meridiem,\n )\n\n\ndef clone_datetime(template: tfhDatetime):\n return tfhDatetime(date=template.date, time=clone_time(template.time), tz=template.tz)\n\n\ndef month_number(value: str, fallback: int | None = None):\n return get_month_mapping().get(value.lower(), fallback)\n\n\ndef weekday_index(value: str):\n return WEEKDAY_ALIASES.get(value.lower())\n\n\ndef timedelta_for_unit(unit: str, amount: float):\n if unit == \"months\":\n return timedelta(days=30 * amount)\n if unit == \"years\":\n return timedelta(days=365 * amount)\n return timedelta(**{unit: amount})\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "alvinwan__timefhuman-55d713d4352a", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/alvinwan__timefhuman-55d713d4352a", "repo_key": "alvinwan__timefhuman", "repo": "alvinwan/timefhuman", "base_commit": "077d0fff5014d392b1e18193495a193d146f9182", "source_files": ["PERFORMANCE.md", "timefhuman/fastpath.py", "timefhuman/grammar.lark", "timefhuman/lalr.py", "timefhuman/main.py", "timefhuman/semantics.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Timezone information is not handled when a specific time is not provided\n\n## Description\nWhen attempting to use or apply timezone information without explicitly specifying a time component (e.g., providing only a date or a timezone object), the system fails to correctly process the timezone. The expected behavior is that timezone information should be correctly handled, potentially defaulting to a time like midnight, or at least not causing incorrect behavior or errors due to the absence of a specified time.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `6dec2fbf6fce` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### timefhuman/grammar.lark\n```python\n%import common.WS\n%import common.INT\n%ignore WS\n\n// ----------------------\n// TERMINAL DEFINITIONS\n// ----------------------\n\n// Month names as a regex token, case-insensitive\nMONTHNAME: /(?i)(? Union[datetime, 'date', 'time', timedelta]:\n \"\"\"Convert to real datetime, date, or time. Assumes partial fields are filled.\"\"\"\n raise NotImplementedError(\"Subclass must implement to_object()\")\n \n @classmethod\n def from_object(cls, obj: Union[datetime, 'date', 'time', timedelta]):\n raise NotImplementedError(\"Subclass must implement from_object()\")\n\n\nclass tfhCollection(tfhDatelike):\n \"\"\"\n A collection of tfhDatelike objects. Provides direct getters and setters for each\n tfhDatelike property.\n \"\"\"\n def __init__(self, items):\n self.items = items\n \n def getter(key):\n def get(self):\n for item in self.items:\n if getattr(item, key):\n return getattr(item, key)\n return None\n return get\n\n def setter(key):\n def set(self, value):\n for item in self.items:\n setattr(item, key, value)\n return set\n \n date = property(getter('date'), setter('date'))\n time = property(getter('time'), setter('time'))\n year = property(getter('year'), setter('year'))\n month = property(getter('month'), setter('month'))\n day = property(getter('day'), setter('day'))\n meridiem = property(getter('meridiem'), setter('meridiem'))\n tz = property(getter('tz'), setter('tz'))\n\n\nclass tfhRange(tfhCollection):\n def to_object(self, config: tfhConfig = tfhConfig()):\n if config.infer_datetimes:\n _start, _end = self.items\n start, end = _start.to_object(config), _end.to_object(config)\n if start > end and not _end.date:\n end += timedelta(days=1)\n return (start, end)\n return tuple([item.to_object(config) for item in self.items])\n\n def __repr__(self):\n return f\"tfhRange({self.items})\"\n\n\nclass tfhList(tfhCollection):\n def to_object(self, config: tfhConfig = tfhConfig()):\n return list([item.to_object(config) for item in self.items])\n\n def __repr__(self):\n return f\"tfhList({self.items})\"\n\n\nclass tfhTimedelta(tfhMatchable):\n def __init__(self, days: int = 0, seconds: int = 0, unit: Optional[str] = None):\n self.days = days\n self.seconds = seconds\n self.unit = unit\n\n def to_object(self, config: tfhConfig = tfhConfig()):\n return timedelta(days=self.days, seconds=self.seconds)\n \n @classmethod\n def from_object(cls, obj: timedelta, unit: Optional[str] = None):\n return cls(days=obj.days, seconds=obj.seconds, unit=unit)\n \n def __repr__(self):\n return f\"tfhTimedelta(days={self.days}, seconds={self.seconds}, unit='{self.unit}')\"\n\n\nclass tfhDate:\n def __init__(\n self, \n year: Optional[int] = None, \n month: Optional[int] = None, \n day: Optional[int] = None,\n delta: Optional[relativedelta] = None,\n ):\n self.year = year\n self.month = month\n self.day = day\n self.delta = delta\n def to_object(self, config: tfhConfig = tfhConfig()) -> date:\n \"\"\"Convert to a real date. Assumes all fields are filled in.\"\"\"\n # NOTE: This must be here, because we need values for each field\n value = date(self.year or config.now.year, self.month or config.now.month, self.day or 1)\n if self.delta:\n value += self.delta\n return value\n \n @classmethod\n def from_object(cls, obj: date):\n return cls(year=obj.year, month=obj.month, day=obj.day)\n\n def __repr__(self):\n return (f\"tfhDate(\"\n f\"year={self.year}, month={self.month}, day={self.day})\")\n\n\nclass tfhTime:\n Meridiem = Enum('Meridiem', ['AM', 'PM'])\n \n def __init__(\n self, \n hour: Optional[int] = None, \n minute: Optional[int] = None, \n second: Optional[int] = None,\n millisecond: Optional[int] = None,\n meridiem: Optional[Meridiem] = None,\n tz: Optional[pytz.timezone] = None,\n ):\n self.hour = hour\n self.minute = minute\n self.second = second\n self.millisecond = millisecond\n self.meridiem = meridiem\n self.tz = tz\n\n def to_object(self, config: tfhConfig = tfhConfig()) -> time:\n \"\"\"Convert to a real time object. Assumes all fields are filled in.\"\"\"\n if self.meridiem == tfhTime.Meridiem.PM and self.hour < 12:\n self.hour += 12\n elif self.meridiem == tfhTime.Meridiem.AM and self.hour == 12:\n self.hour = 0\n object = time(self.hour, self.minute or 0, self.second or 0, self.millisecond or 0, tzinfo=self.tz)\n return object\n \n @classmethod\n def from_object(cls, obj: time):\n return cls(hour=obj.hour, minute=obj.minute, second=obj.second, millisecond=obj.millisecond, meridiem=obj.meridiem, tz=obj.tz)\n\n def __repr__(self):\n return (f\"tfhTime(\"\n f\"hour={self.hour}, minute={self.minute}, second={self.second}, millisecond={self.millisecond}, meridiem={self.meridiem}, tz={self.tz})\")\n\n\nclass tfhDatetime(tfhDatelike):\n \"\"\"A combination of tfhDate + tfhTime.\"\"\"\n \n def getter(attr, key):\n def get(self):\n obj = getattr(self, attr)\n return getattr(obj, key) if obj else None\n return get\n \n def setter(attr, key):\n def set(self, value):\n obj = getattr(self, attr)\n if obj:\n setattr(obj, key, value)\n return set\n \n year = property(getter('date', 'year'), setter('date', 'year'))\n month = property(getter('date', 'month'), setter('date', 'month'))\n day = property(getter('date', 'day'), setter('date', 'day'))\n meridiem = property(getter('time', 'meridiem'), setter('time', 'meridiem'))\n tz = property(getter('time', 'tz'), setter('time', 'tz'))\n\n def __init__(\n self, \n date: Optional[tfhDate] = None, \n time: Optional[tfhTime] = None\n ):\n self.date = date\n self.time = time\n\n def to_object(self, config: tfhConfig = tfhConfig()) -> Union[datetime, date, time]:\n \"\"\"Convert to real datetime, assumes partial fields are filled.\"\"\"\n if self.date and self.time:\n return datetime.combine(self.date.to_object(config), self.time.to_object(config), tzinfo=self.time.tz)\n elif self.date:\n if config.infer_datetimes:\n return datetime.combine(self.date.to_object(config), time(0, 0))\n return self.date.to_object(config)\n elif self.time:\n if config.infer_datetimes:\n _now = config.now.replace(tzinfo=self.time.tz)\n candidate = datetime.combine(_now.date(), self.time.to_object(config))\n if candidate < _now and config.direction == Direction.next:\n candidate += timedelta(days=1)\n elif candidate > _now and config.direction == Direction.previous:\n candidate -= timedelta(days=1)\n elif config.direction == Direction.this:\n pass\n return candidate\n return self.time.to_object(config)\n raise ValueError(\"Datetime is missing both date and time\")\n \n @classmethod\n def from_object(cls, obj: datetime):\n return cls(date=tfhDate.from_object(obj.date()), time=tfhTime.from_object(obj.time()))\n\n def __repr__(self):\n return f\"tfhDatetime({self.date}, {self.time})\"\n \n\nclass tfhAmbiguous(tfhMatchable):\n \"\"\"Can represent an hour, a day, month, or year.\"\"\"\n \n def __init__(self, value: int):\n self.value = value\n \n def to_object(self, config: tfhConfig = tfhConfig()):\n # NOTE: If the ambiguous token was never resolved, simply return the value as a str\n return str(self.value)\n \n @classmethod\n def from_object(cls, obj: int):\n return cls(obj)\n\n def __repr__(self):\n return f\"tfhAmbiguous({self.value})\"\n\n\nclass tfhUnknown(tfhMatchable):\n def __init__(self, value: str):\n self.value = value\n \n def to_object(self, config: tfhConfig = tfhConfig()):\n return self.value\n \n @classmethod\n def from_object(cls, obj: str):\n return cls(obj)\n\n def __repr__(self):\n return f\"tfhUnknown({self.value})\"\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "alvinwan__timefhuman-88824673eb6d", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/alvinwan__timefhuman-88824673eb6d", "repo_key": "alvinwan__timefhuman", "repo": "alvinwan/timefhuman", "base_commit": "6dec2fbf6fceb3ead237c9811d271db202334fee", "source_files": ["timefhuman/grammar.lark", "timefhuman/main.py", "timefhuman/renderers.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Grammar incorrectly matches subsets of words\n\n## Description\nThe current grammar rules are too broad, leading to unintended matches. When a specific word or phrase is defined, the grammar sometimes incorrectly matches a shorter subset of that word or phrase. This results in inaccurate parsing and recognition. The expected behavior is for the grammar to only match complete, distinct words or phrases as defined, without matching their partial components unless those components are explicitly defined as standalone terms.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `3d9f5f1ba0ea` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### timefhuman/grammar.lark\n```python\n%import common.WS\n%import common.INT\n%ignore WS\n\n// ----------------------\n// TERMINAL DEFINITIONS\n// ----------------------\n\n// Month names as a regex token, case-insensitive\nMONTHNAME: /(?i)(january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|oct|nov|dec)/\n\n// For weekdays, also as a single regex token, case-insensitive\nWEEKDAY: /(?i)(monday|mon|tuesday|tues|tue|tu|wednesday|wed|thursday|thurs|thur|thu|friday|fri|saturday|sat|sunday|sun)/\n\n// Meridiem token (am/pm, with optional dots)\nMERIDIEM: /(?i)([ap](\\.?m\\.?)?)/\n\n// Datename token specifies only day\nDATENAME: /(?i)(today|tomorrow|tmw|yesterday)/\n\n// Timename token specifies only time\nTIMENAME: /(?i)(noon|midday|midnight|morning|afternoon|evening|night)/\n\n// Datetimename token specifies date and time\nDATETIMENAME: /(?i)(tonight)/\n\n// Duration unit (minutes, hours, days, etc.)\nDURATION_UNIT: /(?i)(seconds|second|secs|sec|minutes|mins|min|hours|hour|hrs|hr|h|days|day|weeks|week|wks|wk|months|month|mos|years|year)/\nDURATION_UNIT_LETTER: /(?i)(s|m|h|d|w|mo|y)(?![a-z])/\n\n// Duration number (digits like \"1\", or words like \"an\", \"a\", \"one\", \"two\", etc.)\nDURATION_NUMBER: /(?i)(an|a|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)/\n\n// Day suffix (th, rd, st, nd)\nDAY_SUFFIX: /(?i)(th|rd|st|nd)/\n\nFLOAT_NUMBER: /((\\d+\\.\\d*|\\.\\d+)(e[-+]?\\d+)?|\\d+(e[-+]?\\d+))/i // from lark\n\nTIMEZONE: /(?i)((TIMEZONE_MAPPING))/\n\nMODIFIER: /(?i)(next|last|this|upcoming|previous|past)/\n\nPOSITION: /(?i)(first|second|third|fourth|last)/\n\n// ----------------------\n// PARSER RULES\n// ----------------------\nstart: (expression | unknown)+\n\nexpression: single\n | list\n | range\n\nrange: single (\"to\" | \"-\") single\n\nlist: single ((\",\"|\"or\")+ single)+ \n | range ((\",\"|\"or\")+ range)+\n\nsingle: datetime \n | duration\n | ambiguous\n\n// Only add houronly to specific formats that immediately\n// indicate this is an hour-only time.\ndatetime: date (\"at\" (time | houronly))?\n | date (time | houronly)\n | date \"T\" time // ISO 8601\n | (time | houronly) date\n | (time | houronly) \"on\" date\n | date\n | time\n | datetimename\n\n// NOTE: process month modifiers here since the modifier affects the year, which\n// won't be processed until the date rule. If additional modifiers are added,\n// update the date rule processor to handle them. It currently assumes that only\n// the month can be modified.\ndate: weekday? month \"/\" day \"/\" year\n | weekday? year \"/\" month \"/\" day\n | weekday? month \"/\" dayoryear\n | weekday? month \"-\" day \"-\" year\n | weekday? year \"-\" month \"-\" day\n | weekday? month \"-\" dayoryear\n | weekday? datename\n | weekday? monthname day DAY_SUFFIX? (\",\")? year\n | weekday? monthname day DAY_SUFFIX\n | weekday? day DAY_SUFFIX\n | weekday? monthname dayoryear\n | modifier+ monthname\n | position weekday (\"of\"|\"in\") monthname\n | weekday\n\n// intentionally not allowing int-only time, so that single-integers can be\n// classified as an ambiguous token (in case it's a month, day, year, etc.)\n// However, that means to support single-integer (e.g., hour) times, we need\n// to manually add them to the `datetime` rule above.\ntime: hour \":\" minute (\":\" second (\".\" millisecond)?)? meridiem? timezone?\n | hour (\"o'clock\")? meridiem timezone?\n | timename timezone?\n\nduration: (\"in\"|\"for\")? duration_part ((\"and\"|\",\")? duration_part)* (\"ago\")?\nduration_part: duration_number (duration_unit | duration_unit_letter)\n | duration_numbername \" \" duration_unit\nduration_number: FLOAT_NUMBER | INT\nduration_numbername: DURATION_NUMBER+\nduration_unit: DURATION_UNIT\nduration_unit_letter: DURATION_UNIT_LETTER\n\ndatetimename: DATETIMENAME\n\n// process date modifiers here since the weekday processor fully determines the date\nweekday: (modifier+)? WEEKDAY\nmonthname: (modifier+)? MONTHNAME\ndatename: DATENAME\ndayoryear: INT\n\nday: /0[1-9]|[12][0-9]|3[01]|[1-9]/\nmonth: /0[1-9]|1[0-2]|[1-9]/\nyear: /\\d{4}|(? dict:\n assert isinstance(node, (Tree, dict, Token)), f\"Expected a Tree or dict, got {type(node)} ({node})\"\n if isinstance(node, dict):\n return node\n elif isinstance(node, Tree):\n assert len(node.children) == 1, f\"Expected 1 child for {node.data.value}, got {len(node.children)}\"\n return {node.data.value: node.children[0].value}\n elif isinstance(node, Token):\n return {node.type: node.value}\n raise ValueError(f\"Unknown node type: {type(node)} ({node})\")\n\n\ndef nodes_to_dict(nodes: List[Tree]) -> dict:\n result = {}\n for node in nodes:\n result.update(node_to_dict(node))\n return result\n\n\ndef nodes_to_multidict(nodes: List[Tree]) -> dict:\n result = {}\n for node in nodes:\n for key, value in node_to_dict(node).items():\n if key not in result:\n result[key] = []\n result[key].append(value)\n return result\n\n\ndef direction_to_offset(direction: Direction) -> int:\n if direction == Direction.next:\n return +1\n elif direction == Direction.previous:\n return -1\n else:\n return 0\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "alvinwan__timefhuman-c0dec77bb5f7", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/alvinwan__timefhuman-c0dec77bb5f7", "repo_key": "alvinwan__timefhuman", "repo": "alvinwan/timefhuman", "base_commit": "a5bd07e78928ce00dd93b897c7cb1a09c6fd69f8", "source_files": ["timefhuman/main.py", "timefhuman/utils.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `set_args` fails to interpret dot notation for nested arguments\n\n## Description\nWhen attempting to set arguments for nested configurations using dot notation with `set_args`, the values are not correctly applied to the intended nested paths. Instead, the system either creates a flat key using the full dot-separated string or fails to set the value at all. The expected behavior is for `set_args` to correctly parse the dot notation and set the value at the corresponding nested path within the configuration.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `7a60ee1d0e8c` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### confuse.py\n```python\n# -*- coding: utf-8 -*-\n# This file is part of Confuse.\n# Copyright 2016, Adrian Sampson.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n\"\"\"Worry-free YAML configuration files.\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nimport platform\nimport os\nimport pkgutil\nimport sys\nimport yaml\nimport collections\nimport re\nfrom collections import OrderedDict\n\nUNIX_DIR_VAR = 'XDG_CONFIG_HOME'\nUNIX_DIR_FALLBACK = '~/.config'\nWINDOWS_DIR_VAR = 'APPDATA'\nWINDOWS_DIR_FALLBACK = '~\\\\AppData\\\\Roaming'\nMAC_DIR = '~/Library/Application Support'\n\nCONFIG_FILENAME = 'config.yaml'\nDEFAULT_FILENAME = 'config_default.yaml'\nROOT_NAME = 'root'\n\nYAML_TAB_PROBLEM = \"found character '\\\\t' that cannot start any token\"\n\nREDACTED_TOMBSTONE = 'REDACTED'\n\n\n# Utilities.\n\nPY3 = sys.version_info[0] == 3\nSTRING = str if PY3 else unicode # noqa ignore=F821\nBASESTRING = str if PY3 else basestring # noqa ignore=F821\nNUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa ignore=F821\n\n\ndef iter_first(sequence):\n \"\"\"Get the first element from an iterable or raise a ValueError if\n the iterator generates no values.\n \"\"\"\n it = iter(sequence)\n try:\n return next(it)\n except StopIteration:\n raise ValueError()\n\n\n# Exceptions.\n\nclass ConfigError(Exception):\n \"\"\"Base class for exceptions raised when querying a configuration.\n \"\"\"\n\n\nclass NotFoundError(ConfigError):\n \"\"\"A requested value could not be found in the configuration trees.\n \"\"\"\n\n\nclass ConfigValueError(ConfigError):\n \"\"\"The value in the configuration is illegal.\"\"\"\n\n\nclass ConfigTypeError(ConfigValueError):\n \"\"\"The value in the configuration did not match the expected type.\n \"\"\"\n\n\nclass ConfigTemplateError(ConfigError):\n \"\"\"Base class for exceptions raised because of an invalid template.\n \"\"\"\n\n\nclass ConfigReadError(ConfigError):\n \"\"\"A configuration file could not be read.\"\"\"\n def __init__(self, filename, reason=None):\n self.filename = filename\n self.reason = reason\n\n message = u'file {0} could not be read'.format(filename)\n if isinstance(reason, yaml.scanner.ScannerError) and \\\n reason.problem == YAML_TAB_PROBLEM:\n # Special-case error message for tab indentation in YAML markup.\n message += u': found tab character at line {0}, column {1}'.format(\n reason.problem_mark.line + 1,\n reason.problem_mark.column + 1,\n )\n elif reason:\n # Generic error message uses exception's message.\n message += u': {0}'.format(reason)\n\n super(ConfigReadError, self).__init__(message)\n\n\n# Views and sources.\n\nclass ConfigSource(dict):\n \"\"\"A dictionary augmented with metadata about the source of the\n configuration.\n \"\"\"\n def __init__(self, value, filename=None, default=False):\n super(ConfigSource, self).__init__(value)\n if filename is not None and not isinstance(filename, BASESTRING):\n raise TypeError(u'filename must be a string or None')\n self.filename = filename\n self.default = default\n\n def __repr__(self):\n return 'ConfigSource({0!r}, {1!r}, {2!r})'.format(\n super(ConfigSource, self),\n self.filename,\n self.default,\n )\n\n @classmethod\n def of(cls, value):\n \"\"\"Given either a dictionary or a `ConfigSource` object, return\n a `ConfigSource` object. This lets a function accept either type\n of object as an argument.\n \"\"\"\n if isinstance(value, ConfigSource):\n return value\n elif isinstance(value, dict):\n return ConfigSource(value)\n else:\n raise TypeError(u'source value must be a dict')\n\n\nclass ConfigView(object):\n \"\"\"A configuration \"view\" is a query into a program's configuration\n data. A view represents a hypothetical location in the configuration\n tree; to extract the data from the location, a client typically\n calls the ``view.get()`` method. The client can access children in\n the tree (subviews) by subscripting the parent view (i.e.,\n ``view[key]``).\n \"\"\"\n\n name = None\n \"\"\"The name of the view, depicting the path taken through the\n configuration in Python-like syntax (e.g., ``foo['bar'][42]``).\n \"\"\"\n\n def resolve(self):\n \"\"\"The core (internal) data retrieval method. Generates (value,\n source) pairs for each source that contains a value for this\n view. May raise ConfigTypeError if a type error occurs while\n traversing a source.\n \"\"\"\n raise NotImplementedError\n\n def first(self):\n \"\"\"Return a (value, source) pair for the first object found for\n this view. This amounts to the first element returned by\n `resolve`. If no values are available, a NotFoundError is\n raised.\n \"\"\"\n pairs = self.resolve()\n try:\n return iter_first(pairs)\n except ValueError:\n raise NotFoundError(u\"{0} not found\".format(self.name))\n\n def exists(self):\n \"\"\"Determine whether the view has a setting in any source.\n \"\"\"\n try:\n self.first()\n except NotFoundError:\n return False\n return True\n\n def add(self, value):\n \"\"\"Set the *default* value for this configuration view. The\n specified value is added as the lowest-priority configuration\n data source.\n \"\"\"\n raise NotImplementedError\n\n def set(self, value):\n \"\"\"*Override* the value for this configuration view. The\n specified value is added as the highest-priority configuration\n data source.\n \"\"\"\n raise NotImplementedError\n\n def root(self):\n \"\"\"The RootView object from which this view is descended.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n return '<{}: {}>'.format(self.__class__.__name__, self.name)\n\n def __iter__(self):\n \"\"\"Iterate over the keys of a dictionary view or the *subviews*\n of a list view.\n \"\"\"\n # Try getting the keys, if this is a dictionary view.\n try:\n keys = self.keys()\n for key in keys:\n yield key\n\n except ConfigTypeError:\n # Otherwise, try iterating over a list.\n collection = self.get()\n if not isinstance(collection, (list, tuple)):\n raise ConfigTypeError(\n u'{0} must be a dictionary or a list, not {1}'.format(\n self.name, type(collection).__name__\n )\n )\n\n # Yield all the indices in the list.\n for index in range(len(collection)):\n yield self[index]\n\n def __getitem__(self, key):\n \"\"\"Get a subview of this view.\"\"\"\n return Subview(self, key)\n\n def __setitem__(self, key, value):\n \"\"\"Create an overlay source to assign a given key under this\n view.\n \"\"\"\n self.set({key: value})\n\n def __contains__(self, key):\n return self[key].exists()\n\n def set_args(self, namespace):\n \"\"\"Overlay parsed command-line arguments, generated by a library\n like argparse or optparse, onto this view's value.\n \"\"\"\n args = {}\n for key, value in namespace.__dict__.items():\n if value is not None: # Avoid unset options.\n args[key] = value\n self.set(args)\n\n # Magical conversions. These special methods make it possible to use\n # View objects somewhat transparently in certain circumstances. For\n # example, rather than using ``view.get(bool)``, it's possible to\n # just say ``bool(view)`` or use ``view`` in a conditional.\n\n def __str__(self):\n \"\"\"Get the value for this view as a bytestring.\n \"\"\"\n if PY3:\n return self.__unicode__()\n else:\n return bytes(self.get())\n\n def __unicode__(self):\n \"\"\"Get the value for this view as a Unicode string.\n \"\"\"\n return STRING(self.get())\n\n def __nonzero__(self):\n \"\"\"Gets the value for this view as a boolean. (Python 2 only.)\n \"\"\"\n return self.__bool__()\n\n def __bool__(self):\n \"\"\"Gets the value for this view as a boolean. (Python 3 only.)\n \"\"\"\n return bool(self.get())\n\n # Dictionary emulation methods.\n\n def keys(self):\n \"\"\"Returns a list containing all the keys available as subviews\n of the current views. This enumerates all the keys in *all*\n dictionaries matching the current view, in contrast to\n ``view.get(dict).keys()``, which gets all the keys for the\n *first* dict matching the view. If the object for this view in\n any source is not a dict, then a ConfigTypeError is raised. The\n keys are ordered according to how they appear in each source.\n \"\"\"\n keys = []\n\n for dic, _ in self.resolve():\n try:\n cur_keys = dic.keys()\n except AttributeError:\n raise ConfigTypeError(\n u'{0} must be a dict, not {1}'.format(\n self.name, type(dic).__name__\n )\n )\n\n for key in cur_keys:\n if key not in keys:\n keys.append(key)\n\n return keys\n\n def items(self):\n \"\"\"Iterates over (key, subview) pairs contained in dictionaries\n from *all* sources at this view. If the object for this view in\n any source is not a dict, then a ConfigTypeError is raised.\n \"\"\"\n for key in self.keys():\n yield key, self[key]\n\n def values(self):\n \"\"\"Iterates over all the subviews contained in dictionaries from\n *all* sources at this view. If the object for this view in any\n source is not a dict, then a ConfigTypeError is raised.\n \"\"\"\n for key in self.keys():\n yield self[key]\n\n # List/sequence emulation.\n\n def all_contents(self):\n \"\"\"Iterates over all subviews from collections at this view from\n *all* sources. If the object for this view in any source is not\n iterable, then a ConfigTypeError is raised. This method is\n intended to be used when the view indicates a list; this method\n will concatenate the contents of the list from all sources.\n \"\"\"\n for collection, _ in self.resolve():\n try:\n it = iter(collection)\n except TypeError:\n raise ConfigTypeError(\n u'{0} must be an iterable, not {1}'.format(\n self.name, type(collection).__name__\n )\n )\n for value in it:\n yield value\n\n # Validation and conversion.\n\n def flatten(self, redact=False):\n \"\"\"Create a hierarchy of OrderedDicts containing the data from\n this view, recursively reifying all views to get their\n represented values.\n\n If `redact` is set, then sensitive values are replaced with\n the string \"REDACTED\".\n \"\"\"\n od = OrderedDict()\n for key, view in self.items():\n if redact and view.redact:\n od[key] = REDACTED_TOMBSTONE\n else:\n try:\n od[key] = view.flatten(redact=redact)\n except ConfigTypeError:\n od[key] = view.get()\n return od\n\n def get(self, template=None):\n \"\"\"Retrieve the value for this view according to the template.\n\n The `template` against which the values are checked can be\n anything convertible to a `Template` using `as_template`. This\n means you can pass in a default integer or string value, for\n example, or a type to just check that something matches the type\n you expect.\n\n May raise a `ConfigValueError` (or its subclass,\n `ConfigTypeError`) or a `NotFoundError` when the configuration\n doesn't satisfy the template.\n \"\"\"\n return as_template(template).value(self, template)\n\n # Shortcuts for common templates.\n\n def as_filename(self):\n \"\"\"Get the value as a path. Equivalent to `get(Filename())`.\n \"\"\"\n return self.get(Filename())\n\n def as_choice(self, choices):\n \"\"\"Get the value from a list of choices. Equivalent to\n `get(Choice(choices))`.\n \"\"\"\n return self.get(Choice(choices))\n\n def as_number(self):\n \"\"\"Get the value as any number type: int or float. Equivalent to\n `get(Number())`.\n \"\"\"\n return self.get(Number())\n\n def as_str_seq(self):\n \"\"\"Get the value as a sequence of strings. Equivalent to\n `get(StrSeq())`.\n \"\"\"\n return self.get(StrSeq())\n\n def as_str(self):\n \"\"\"Get the value as a (Unicode) string. Equivalent to\n `get(unicode)` on Python 2 and `get(str)` on Python 3.\n \"\"\"\n return self.get(String())\n\n # Redaction.\n\n @property\n def redact(self):\n \"\"\"Whether the view contains sensitive information and should be\n redacted from output.\n \"\"\"\n return () in self.get_redactions()\n\n @redact.setter\n def redact(self, flag):\n self.set_redaction((), flag)\n\n def set_redaction(self, path, flag):\n \"\"\"Add or remove a redaction for a key path, which should be an\n iterable of keys.\n \"\"\"\n raise NotImplementedError()\n\n def get_redactions(self):\n \"\"\"Get the set of currently-redacted sub-key-paths at this view.\n \"\"\"\n raise NotImplementedError()\n\n\nclass RootView(ConfigView):\n \"\"\"The base of a view hierarchy. This view keeps track of the\n sources that may be accessed by subviews.\n \"\"\"\n def __init__(self, sources):\n \"\"\"Create a configuration hierarchy for a list of sources. At\n least one source must be provided. The first source in the list\n has the highest priority.\n \"\"\"\n self.sources = list(sources)\n self.name = ROOT_NAME\n self.redactions = set()\n\n def add(self, obj):\n self.sources.append(ConfigSource.of(obj))\n\n def set(self, value):\n self.sources.insert(0, ConfigSource.of(value))\n\n def resolve(self):\n return ((dict(s), s) for s in self.sources)\n\n def clear(self):\n \"\"\"Remove all sources (and redactions) from this\n configuration.\n \"\"\"\n del self.sources[:]\n self.redactions.clear()\n\n def root(self):\n return self\n\n def set_redaction(self, path, flag):\n if flag:\n self.redactions.add(path)\n elif path in self.redactions:\n self.redactions.remove(path)\n\n def get_redactions(self):\n return self.redactions\n\n\nclass Subview(ConfigView):\n \"\"\"A subview accessed via a subscript of a parent view.\"\"\"\n def __init__(self, parent, key):\n \"\"\"Make a subview of a parent view for a given subscript key.\n \"\"\"\n self.parent = parent\n self.key = key\n\n # Choose a human-readable name for this view.\n if isinstance(self.parent, RootView):\n self.name = ''\n else:\n self.name = self.parent.name\n if not isinstance(self.key, int):\n self.name += '.'\n if isinstance(self.key, int):\n self.name += u'#{0}'.format(se\n... [truncated 32786 chars]\n\n```\n\n### docs/index.rst\n```python\nConfuse: Painless Configuration\n===============================\n\n`Confuse`_ is a straightforward, full-featured configuration system\nfor Python.\n\n.. _Confuse: https://github.com/sampsyo/confuse\n\n\nUsing Confuse\n-------------\n\nSet up your Configuration object, which provides unified access to\nall of your application\u2019s config settings::\n\n config = confuse.Configuration('MyGreatApp', __name__)\n\nThe first parameter is required; it\u2019s the name of your application that\nwill be used to search the system for config files. The second parameter\nis optional: it\u2019s the name of a module that will guide the search for a\n*defaults* file. Use this if you want to include a\n``config_default.yaml`` file inside your package. (The included\n``example`` package does exactly this.)\n\nNow, you can access your configuration data as if it were a simple\nstructure consisting of nested dicts and lists\u2014except that you need to\ncall the method ``.get()`` on the leaf of this tree to get the result as\na value::\n\n value = config['foo'][2]['bar'].get()\n\nUnder the hood, accessing items in your configuration tree builds up a\n*view* into your app\u2019s configuration. Then, ``get()`` flattens this view\ninto a file, performing a search through each configuration data source\nto find an answer. More on view later.\n\nIf you know that a configuration value should have a specific type, just\npass that type to ``get()``::\n\n int_value = config['number_of_goats'].get(int)\n\nThis way, Confuse will either give you an integer or raise a\n``ConfigTypeError`` if the user has messed up the configuration. You\u2019re\nsafe to assume after this call that ``int_value`` has the right type. If\nthe key doesn\u2019t exist in any configuration file, Confuse will raise a\n``NotFoundError``. Together, catching these exceptions (both subclasses\nof ``confuse.ConfigError``) lets you painlessly validate the user\u2019s\nconfiguration as you go.\n\n\nView Theory\n-----------\n\nThe Confuse API is based on the concept of *views*. You can think of a\nview as a *place to look* in a config file: for example, one view might\nsay \u201cget the value for key ``number_of_goats``\u201d. Another might say \u201cget\nthe value at index 8 inside the sequence for key ``animal_counts``\u201d. To\nget the value for a given view, you *resolve* it by calling the\n``get()`` method.\n\nThis concept separates the specification of a location from the\nmechanism for retrieving data from a location. (In this sense, it\u2019s a\nlittle like `XPath`_: you specify a path to data you want and *then* you\nretrieve it.)\n\nUsing views, you can write ``config['animal_counts'][8]`` and know that\nno exceptions will be raised until you call ``get()``, even if the\n``animal_counts`` key does not exist. More importantly, it lets you\nwrite a single expression to search many different data sources without\npreemtively merging all sources together into a single data structure.\n\nViews also solve an important problem with overriding collections.\nImagine, for example, that you have a dictionary called\n``deliciousness`` in your config file that maps food names to tastiness\nratings. If the default configuration gives carrots a rating of 8 and\nthe user\u2019s config rates them a 10, then clearly\n``config['deliciousness']['carrots'].get()`` should return 10. But what\nif the two data sources have different sets of vegetables? If the user\nprovides a value for broccoli and zucchini but not carrots, should\ncarrots have a default deliciousness value of 8 or should Confuse just\nthrow an exception? With Confuse\u2019s views, the application gets to decide.\n\nThe above expression, ``config['deliciousness']['carrots'].get()``,\nreturns 10 (falling back on the default). However, you can also write\n``config['deliciousness'].get()``. This expression will cause the\n*entire* user-specified mapping to override the default one, providing a\ndict object like ``{'broccoli': 7, 'zucchini': 9}``. As a rule, then,\nresolve a view at the same granularity you want config files to override\neach other.\n\n.. _XPath: http://www.w3.org/TR/xpath/\n\n\nValidation\n----------\n\nWe saw above that you can easily assert that a configuration value has a\ncertain type by passing that type to ``get()``. But sometimes you need\nto do more than just type checking. For this reason, Confuse provides a\nfew methods on views that perform fancier validation or even\nconversion:\n\n* ``as_filename()``: Normalize a filename, substituting tildes and\n absolute-ifying relative paths. The filename is relative to the source\n that provided it. That is, a relative path in a config file refers to\n the directory containing the config file. A relative path in the\n defaults refers to the application's config directory\n (``config.config_dir()``, as described below). A relative path from\n any other source (e.g., command-line options) is relative to the\n working directory.\n* ``as_choice(choices)``: Check that a value is one of the provided\n choices. The argument should be a sequence of possible values. If the\n sequence is a ``dict``, then this method returns the associated value\n instead of the key.\n* ``as_number()``: Raise an exception unless the value is of a numeric\n type.\n* ``as_pairs()``: Get a collection as a list of pairs. The collection\n should be a list of elements that are either pairs (i.e., two-element\n lists) already or single-entry dicts. This can be helpful because, in\n YAML, lists of single-element mappings have a simple syntax (``- key:\n value``) and, unlike real mappings, preserve order.\n* ``as_str_seq()``: Given either a string or a list of strings, return a list\n of strings. A single string is split on whitespace.\n\nFor example, ``config['path'].as_filename()`` ensures that you get a\nreasonable filename string from the configuration. And calling\n``config['direction'].as_choice(['up', 'down'])`` will raise a\n``ConfigValueError`` unless the ``direction`` value is either \"up\" or\n\"down\".\n\n\nCommand-Line Options\n--------------------\n\nArguments to command-line programs can be seen as just another *source*\nfor configuration options. Just as options in a user-specific\nconfiguration file should override those from a system-wide config,\ncommand-line options should take priority over all configuration files.\n\nYou can use the `argparse`_ and `optparse`_ modules from the standard\nlibrary with Confuse to accomplish this. Just call the ``set_args``\nmethod on any view and pass in the object returned by the command-line\nparsing library. Values from the command-line option namespace object\nwill be added to the overlay for the view in question. For example, with\nargparse::\n\n args = parser.parse_args()\n config.set_args(args)\n\nCorrespondingly, with optparse::\n\n options, args = parser.parse_args()\n config.set_args(options)\n\nThis call will turn all of the command-line options into a top-level\nsource in your configuration. The key associated with each option in the\nparser will become a key available in your configuration. For example,\nconsider this argparse script::\n\n config = confuse.Configuration('myapp')\n parser = argparse.ArgumentParser()\n parser.add_argument('--foo', help='a parameter')\n args = parser.parse_args()\n config.set_args(args)\n print(config['foo'].get())\n\nThis will allow the user to override the configured value for key\n``foo`` by passing ``--foo `` on the command line.\n\n.. _argparse: http://docs.python.org/dev/library/argparse.html\n.. _parse_args: http://docs.python.org/library/argparse.html#the-parse-args-method\n.. _optparse: http://docs.python.org/library/optparse.html\n\nNote that, while you can use the full power of your favorite\ncommand-line parsing library, you'll probably want to avoid specifying\ndefaults in your argparse or optparse setup. This way, Confuse can use\nother configuration sources---possibly your\n``config_default.yaml``---to fill in values for unspecified\ncommand-line switches. Otherwise, the argparse/optparse default value\nwill hide options configured elsewhere.\n\n\nSearch Paths\n------------\n\nConfuse looks in a number of locations for your application's\nconfigurations. The locations are determined by the platform. For each\nplatform, Confuse has a list of directories in which it looks for a\ndirectory named after the application. For example, the first search\nlocation on Unix-y systems is ``$XDG_CONFIG_HOME/AppName`` for an\napplication called ``AppName``.\n\nHere are the default search paths for each platform:\n\n* OS X: ``~/.config/app`` and ``~/Library/Application Support/app``\n* Other Unix: ``$XDG_CONFIG_HOME/app`` and ``~/.config/app``\n* Windows: ``%APPDATA%\\app`` where the `APPDATA` environment variable falls\n back to ``%HOME%\\AppData\\Roaming`` if undefined\n\nUsers can also add an override configuration directory with an\nenvironment variable. The variable name is the application name in\ncapitals with \"DIR\" appended: for an application named ``AppName``, the\nenvironment variable is ``APPNAMEDIR``.\n\n\nYour Application Directory\n--------------------------\n\nConfuse provides a simple helper, ``Configuration.config_dir()``, that\ngives you a directory used to store your application's configuration. If\na configuration file exists in any of the searched locations, then the\nhighest-priority directory containing a config file is used. Otherwise,\na directory is created for you and returned. So you can always expect\nthis method to give you a directory that actually exists.\n\nAs an example, you may want to migrate a user's settings to Confuse from\nan older configuration system such as `ConfigParser`_. Just do something\nlike this::\n\n config_filename = os.path.join(config.config_dir(),\n confuse.CONFIG_FILENAME)\n with open(config_filename, 'w') as f:\n yaml.dump(migrated_config, f)\n\n.. _ConfigParser: http://docs.python.org/library/configparser.html\n\n\nDynamic Updates\n---------------\n\nOccasionally, a program will need to modify its configuration while it's\nrunning. For example, an interactive prompt from the user might cause\nthe program to change a setting for the current execution only. Or the\nprogram might need to add a *derived* configuration value that the user\ndoesn't specify.\n\nTo facilitate this, Confuse lets you *assign* to view objects using\nordinary Python assignment. Assignment will add an overlay source that\nprecedes all other configuration sources in priority. Here's an example\nof programmatically setting a configuration value based on a ``DEBUG``\nconstant::\n\n if DEBUG:\n config['verbosity'] = 100\n ...\n my_logger.setLevel(config['verbosity'].get(int))\n\nThis example allows the constant to override the default verbosity\nlevel, which would otherwise come from a configuration file.\n\nAssignment works be creating a new \"source\" for configuration data at\nthe top of the stack. This new source takes priority over all other,\npreviously-loaded sources. You can cause this explicitly by calling the\n``set()`` method on any view. A related method, ``add()``, works\nsimilarly but instead adds a new *lowest-priority* source to the bottom\nof the stack. This can be used to provide defaults for options that may\nbe overridden by previously-loaded configuration files.\n\n\nYAML Tweaks\n-----------\n\nConfuse uses the `PyYAML`_ module to parse YAML configuration files. However, it\ndeviates very slightly from the official YAML specification to provide a few\nniceties suited to human-written configuration files. Those tweaks are:\n\n.. _pyyaml: http://pyyaml.org/\n\n- All strings are returned as Python Unicode objects.\n- YAML maps are parsed as Python `OrderedDict`_ objects. This means that you\n can recover the order that the user wrote down a dictionary.\n- Bare strings can begin with the % character. In stock PyYAML, this will throw\n a parse error.\n\n.. _OrderedDict: http://docs.python.org/2/library/collections.html#collections.OrderedDict\n\nTo produce a YAML file reflecting a configuration, just call\n``config.dump()``. If you supply a filename, the YAML will be written to the\nfile; otherwise, a string is returned. This does not cleanly round-trip YAML,\nbut it does play some tricks to preserve comments and spacing in the original\nfile.\n\n\nConfiguring Large Programs\n--------------------------\n\nOne problem that must be solved by a configuration system is the issue\nof global configuration for complex applications. In a large program\nwith many components and many config options, it can be unwieldy to\nexplicitly pass configuration values from component to component. You\nquickly end up with monstrous function signatures with dozens of keyword\narguments, decreasing code legibility and testability.\n\nIn such systems, one option is to pass a single `Configuration` object\nthrough to each component. To avoid even this, however, it's sometimes\nappropriate to use a little bit of shared global state. As evil as\nshared global state usually is, configuration is (in my opinion) one\nvalid use: since configuration is mostly read-only, it's relatively\nunlikely to cause the sorts of problems that global values sometimes\ncan. And having a global repository for configuration option can vastly\nreduce the amount of boilerplate threading-through needed to explicitly\npass configuration from call to call.\n\nTo use global configuration, consider creating a configuration object in\na well-known module (say, the root of a package). But since this object\nwill be initialized at module load time, Confuse provides a `LazyConfig`\nobject that loads your configuration files on demand instead of when the\nobject is constructed. (Doing complicated stuff like parsing YAML at\nmodule load time is generally considered a Bad Idea.)\n\nGlobal state can cause problems for unit testing. To alleviate this,\nconsider adding code to your test fixtures (e.g., `setUp`_ in the\n`unittest`_ module) that clears out the global configuration before each\ntest is run. Something like this::\n\n config.clear()\n config.read(user=False)\n\nThese lines will empty out the current configuration and then re-load\nthe defaults (but not the user's configuration files). Your tests can\nthen modify the global configuration values without affecting other\ntests since these modifications will be cleared out before the next test\nruns.\n\n.. _unittest: http://docs.python.org/2/library/unittest.html\n.. _setUp: http://docs.python.org/2/library/unittest.html#unittest.TestCase.setUp\n\n\nRedaction\n---------\n\nYou can also mark certain configuration values as \"sensitive\" and avoid\nincluding them in output. Just set the `redact` flag::\n\n config['key'].redact = True\n\nThen flatten or dump the configuration like so::\n\n config.dump(redact=True)\n\nThe resulting YAML will contain \"key: REDACTED\" instead of the original data.\n\n```\n\n### example/__init__.py\n```python\n\"\"\"An example application using Confuse for configuration.\"\"\"\nfrom __future__ import division, absolute_import, print_function\nimport confuse\nimport argparse\n\n\ntemplate = {\n 'library': confuse.Filename(),\n 'import_write': confuse.OneOf([bool, 'ask', 'skip']),\n 'ignore': confuse.StrSeq(),\n 'plugins': list,\n\n 'paths': {\n 'directory': confuse.Filename(),\n 'default': confuse.Filename(relative_to='directory'),\n }\n}\n\nconfig = confuse.LazyConfig('ConfuseExample', __name__)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='example Confuse program')\n parser.add_argument('--library', '-l', dest='library', metavar='LIBPATH',\n help='library database file')\n parser.add_argument('--directory', '-d', dest='directory',\n metavar='DIRECTORY',\n help='destination music directory')\n parser.add_argument('--verbose', '-v', dest='verbose', action='store_true',\n help='print debugging messages')\n\n args = parser.parse_args()\n config.set_args(args)\n\n print('configuration directory is', config.config_dir())\n\n # Use a boolean flag and the transient overlay.\n if config['verbose']:\n print('verbose mode')\n config['log']['level'] = 2\n else:\n config['log']['level'] = 0\n print('logging level is', config['log']['level'].get(int))\n\n valid = config.get(template)\n\n # Some validated/converted values.\n print('library is', valid.library)\n print('directory is', valid.paths.directory)\n print('paths.default is', valid.paths.default)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "beetbox__confuse-34cb3b91f309", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/beetbox__confuse-34cb3b91f309", "repo_key": "beetbox__confuse", "repo": "beetbox/confuse", "base_commit": "7a60ee1d0e8c6d40d512f2d86de7ab4933e57c6a", "source_files": ["confuse.py", "docs/index.rst", "example/__init__.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Sequence validator raises AttributeError when validating a mapping\n\n## Description\nWhen a field is typed as `Sequence[T]` and a mapping (e.g., a dictionary) is provided as input for that field, the validation process incorrectly raises an `AttributeError`. The expected behavior is for the validator to either successfully validate the mapping if it conforms to a sequence, or to raise a more appropriate validation error indicating a type mismatch, rather than an `AttributeError`.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `200203f9c4a5` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### confuse/templates.py\n```python\nfrom __future__ import division, absolute_import, print_function\n\nimport os\nimport re\nimport sys\n\nfrom . import util\nfrom . import exceptions\n\ntry:\n import enum\n SUPPORTS_ENUM = True\nexcept ImportError:\n SUPPORTS_ENUM = False\n\ntry:\n import pathlib\n SUPPORTS_PATHLIB = True\nexcept ImportError:\n SUPPORTS_PATHLIB = False\n\nif sys.version_info >= (3, 3):\n from collections import abc\nelse:\n import collections as abc\n\n\nREQUIRED = object()\n\"\"\"A sentinel indicating that there is no default value and an exception\nshould be raised when the value is missing.\n\"\"\"\n\n\nclass Template(object):\n \"\"\"A value template for configuration fields.\n\n The template works like a type and instructs Confuse about how to\n interpret a deserialized YAML value. This includes type conversions,\n providing a default value, and validating for errors. For example, a\n filepath type might expand tildes and check that the file exists.\n \"\"\"\n def __init__(self, default=REQUIRED):\n \"\"\"Create a template with a given default value.\n\n If `default` is the sentinel `REQUIRED` (as it is by default),\n then an error will be raised when a value is missing. Otherwise,\n missing values will instead return `default`.\n \"\"\"\n self.default = default\n\n def __call__(self, view):\n \"\"\"Invoking a template on a view gets the view's value according\n to the template.\n \"\"\"\n return self.value(view, self)\n\n def value(self, view, template=None):\n \"\"\"Get the value for a `ConfigView`.\n\n May raise a `NotFoundError` if the value is missing (and the\n template requires it) or a `ConfigValueError` for invalid values.\n \"\"\"\n try:\n value, _ = view.first()\n return self.convert(value, view)\n except exceptions.NotFoundError:\n pass\n\n # Get default value, or raise if required.\n return self.get_default_value(view.name)\n\n def get_default_value(self, key_name='default'):\n \"\"\"Get the default value to return when the value is missing.\n\n May raise a `NotFoundError` if the value is required.\n \"\"\"\n if not hasattr(self, 'default') or self.default is REQUIRED:\n # The value is required. A missing value is an error.\n raise exceptions.NotFoundError(u\"{} not found\".format(key_name))\n # The value is not required.\n return self.default\n\n def convert(self, value, view):\n \"\"\"Convert the YAML-deserialized value to a value of the desired\n type.\n\n Subclasses should override this to provide useful conversions.\n May raise a `ConfigValueError` when the configuration is wrong.\n \"\"\"\n # Default implementation does no conversion.\n return value\n\n def fail(self, message, view, type_error=False):\n \"\"\"Raise an exception indicating that a value cannot be\n accepted.\n\n `type_error` indicates whether the error is due to a type\n mismatch rather than a malformed value. In this case, a more\n specific exception is raised.\n \"\"\"\n exc_class = (\n exceptions.ConfigTypeError if type_error\n else exceptions.ConfigValueError)\n raise exc_class(u'{0}: {1}'.format(view.name, message))\n\n def __repr__(self):\n return '{0}({1})'.format(\n type(self).__name__,\n '' if self.default is REQUIRED else repr(self.default),\n )\n\n\nclass Integer(Template):\n \"\"\"An integer configuration value template.\n \"\"\"\n def convert(self, value, view):\n \"\"\"Check that the value is an integer. Floats are rounded.\n \"\"\"\n if isinstance(value, int):\n return value\n elif isinstance(value, float):\n return int(value)\n else:\n self.fail(u'must be a number', view, True)\n\n\nclass Number(Template):\n \"\"\"A numeric type: either an integer or a floating-point number.\n \"\"\"\n def convert(self, value, view):\n \"\"\"Check that the value is an int or a float.\n \"\"\"\n if isinstance(value, util.NUMERIC_TYPES):\n return value\n else:\n self.fail(\n u'must be numeric, not {0}'.format(type(value).__name__),\n view,\n True\n )\n\n\nclass MappingTemplate(Template):\n \"\"\"A template that uses a dictionary to specify other types for the\n values for a set of keys and produce a validated `AttrDict`.\n \"\"\"\n def __init__(self, mapping):\n \"\"\"Create a template according to a dict (mapping). The\n mapping's values should themselves either be Types or\n convertible to Types.\n \"\"\"\n subtemplates = {}\n for key, typ in mapping.items():\n subtemplates[key] = as_template(typ)\n self.subtemplates = subtemplates\n\n def value(self, view, template=None):\n \"\"\"Get a dict with the same keys as the template and values\n validated according to the value types.\n \"\"\"\n out = AttrDict()\n for key, typ in self.subtemplates.items():\n out[key] = typ.value(view[key], self)\n return out\n\n def __repr__(self):\n return 'MappingTemplate({0})'.format(repr(self.subtemplates))\n\n\nclass Sequence(Template):\n \"\"\"A template used to validate lists of similar items,\n based on a given subtemplate.\n \"\"\"\n def __init__(self, subtemplate):\n \"\"\"Create a template for a list with items validated\n on a given subtemplate.\n \"\"\"\n self.subtemplate = as_template(subtemplate)\n\n def value(self, view, template=None):\n \"\"\"Get a list of items validated against the template.\n \"\"\"\n out = []\n for item in view:\n out.append(self.subtemplate.value(item, self))\n return out\n\n def __repr__(self):\n return 'Sequence({0})'.format(repr(self.subtemplate))\n\n\nclass MappingValues(Template):\n \"\"\"A template used to validate mappings of similar items,\n based on a given subtemplate applied to the values.\n\n All keys in the mapping are considered valid, but values\n must pass validation by the subtemplate. Similar to the\n Sequence template but for mappings.\n \"\"\"\n def __init__(self, subtemplate):\n \"\"\"Create a template for a mapping with variable keys\n and item values validated on a given subtemplate.\n \"\"\"\n self.subtemplate = as_template(subtemplate)\n\n def value(self, view, template=None):\n \"\"\"Get a dict with the same keys as the view and the\n value of each item validated against the subtemplate.\n \"\"\"\n out = {}\n for key, item in view.items():\n out[key] = self.subtemplate.value(item, self)\n return out\n\n def __repr__(self):\n return 'MappingValues({0})'.format(repr(self.subtemplate))\n\n\nclass String(Template):\n \"\"\"A string configuration value template.\n \"\"\"\n def __init__(self, default=REQUIRED, pattern=None, expand_vars=False):\n \"\"\"Create a template with the added optional `pattern` argument,\n a regular expression string that the value should match.\n \"\"\"\n super(String, self).__init__(default)\n self.pattern = pattern\n self.expand_vars = expand_vars\n if pattern:\n self.regex = re.compile(pattern)\n\n def __repr__(self):\n args = []\n\n if self.default is not REQUIRED:\n args.append(repr(self.default))\n\n if self.pattern is not None:\n args.append('pattern=' + repr(self.pattern))\n\n return 'String({0})'.format(', '.join(args))\n\n def convert(self, value, view):\n \"\"\"Check that the value is a string and matches the pattern.\n \"\"\"\n if not isinstance(value, util.BASESTRING):\n self.fail(u'must be a string', view, True)\n\n if self.pattern and not self.regex.match(value):\n self.fail(\n u\"must match the pattern {0}\".format(self.pattern),\n view\n )\n\n if self.expand_vars:\n return os.path.expandvars(value)\n else:\n return value\n\n\nclass Choice(Template):\n \"\"\"A template that permits values from a sequence of choices.\n \"\"\"\n def __init__(self, choices, default=REQUIRED):\n \"\"\"Create a template that validates any of the values from the\n iterable `choices`.\n\n If `choices` is a map, then the corresponding value is emitted.\n Otherwise, the value itself is emitted.\n\n If `choices` is a `Enum`, then the enum entry with the value is\n emitted.\n \"\"\"\n super(Choice, self).__init__(default)\n self.choices = choices\n\n def convert(self, value, view):\n \"\"\"Ensure that the value is among the choices (and remap if the\n choices are a mapping).\n \"\"\"\n if (SUPPORTS_ENUM and isinstance(self.choices, type)\n and issubclass(self.choices, enum.Enum)):\n try:\n return self.choices(value)\n except ValueError:\n self.fail(\n u'must be one of {0!r}, not {1!r}'.format(\n [c.value for c in self.choices], value\n ),\n view\n )\n\n if value not in self.choices:\n self.fail(\n u'must be one of {0!r}, not {1!r}'.format(\n list(self.choices), value\n ),\n view\n )\n\n if isinstance(self.choices, abc.Mapping):\n return self.choices[value]\n else:\n return value\n\n def __repr__(self):\n return 'Choice({0!r})'.format(self.choices)\n\n\nclass OneOf(Template):\n \"\"\"A template that permits values complying to one of the given templates.\n \"\"\"\n def __init__(self, allowed, default=REQUIRED):\n super(OneOf, self).__init__(default)\n self.allowed = list(allowed)\n\n def __repr__(self):\n args = []\n\n if self.allowed is not None:\n args.append('allowed=' + repr(self.allowed))\n\n if self.default is not REQUIRED:\n args.append(repr(self.default))\n\n return 'OneOf({0})'.format(', '.join(args))\n\n def value(self, view, template):\n self.template = template\n return super(OneOf, self).value(view, template)\n\n def convert(self, value, view):\n \"\"\"Ensure that the value follows at least one template.\n \"\"\"\n is_mapping = isinstance(self.template, MappingTemplate)\n\n for candidate in self.allowed:\n try:\n if is_mapping:\n if isinstance(candidate, Filename) and \\\n candidate.relative_to:\n next_template = candidate.template_with_relatives(\n view,\n self.template\n )\n\n next_template.subtemplates[view.key] = as_template(\n candidate\n )\n else:\n next_template = MappingTemplate({view.key: candidate})\n\n return view.parent.get(next_template)[view.key]\n else:\n return view.get(candidate)\n except exceptions.ConfigTemplateError:\n raise\n except exceptions.ConfigError:\n pass\n except ValueError as exc:\n raise exceptions.ConfigTemplateError(exc)\n\n self.fail(\n u'must be one of {0}, not {1}'.format(\n repr(self.allowed), repr(value)\n ),\n view\n )\n\n\nclass StrSeq(Template):\n \"\"\"A template for values that are lists of strings.\n\n Validates both actual YAML string lists and single strings. Strings\n can optionally be split on whitespace.\n \"\"\"\n def __init__(self, split=True, default=REQUIRED):\n \"\"\"Create a new template.\n\n `split` indicates whether, when the underlying value is a single\n string, it should be split on whitespace. Otherwise, the\n resulting value is a list containing a single string.\n \"\"\"\n super(StrSeq, self).__init__(default)\n self.split = split\n\n def _convert_value(self, x, view):\n if isinstance(x, util.STRING):\n return x\n elif isinstance(x, bytes):\n return x.decode('utf-8', 'ignore')\n else:\n self.fail(u'must be a list of strings', view, True)\n\n def convert(self, value, view):\n if isinstance(value, bytes):\n value = value.decode('utf-8', 'ignore')\n\n if isinstance(value, util.STRING):\n if self.split:\n value = value.split()\n else:\n value = [value]\n else:\n try:\n value = list(value)\n except TypeError:\n self.fail(u'must be a whitespace-separated string or a list',\n view, True)\n return [self._convert_value(v, view) for v in value]\n\n\nclass Pairs(StrSeq):\n \"\"\"A template for ordered key-value pairs.\n\n This can either be given with the same syntax as for `StrSeq` (i.e. without\n values), or as a list of strings and/or single-element mappings such as::\n\n - key: value\n - [key, value]\n - key\n\n The result is a list of two-element tuples. If no value is provided, the\n `default_value` will be returned as the second element.\n \"\"\"\n\n def __init__(self, default_value=None):\n \"\"\"Create a new template.\n\n `default` is the dictionary value returned for items that are not\n a mapping, but a single string.\n \"\"\"\n super(Pairs, self).__init__(split=True)\n self.default_value = default_value\n\n def _convert_value(self, x, view):\n try:\n return (super(Pairs, self)._convert_value(x, view),\n self.default_value)\n except exceptions.ConfigTypeError:\n if isinstance(x, abc.Mapping):\n if len(x) != 1:\n self.fail(u'must be a single-element mapping', view, True)\n k, v = util.iter_first(x.items())\n elif isinstance(x, abc.Sequence):\n if len(x) != 2:\n self.fail(u'must be a two-element list', view, True)\n k, v = x\n else:\n # Is this even possible? -> Likely, if some !directive cause\n # YAML to parse this to some custom type.\n self.fail(u'must be a single string, mapping, or a list'\n u'' + str(x),\n view, True)\n return (super(Pairs, self)._convert_value(k, view),\n super(Pairs, self)._convert_value(v, view))\n\n\nclass Filename(Template):\n \"\"\"A template that validates strings as filenames.\n\n Filenames are returned as absolute, tilde-free paths.\n\n Relative paths are relative to the template's `cwd` argument\n when it is specified, then the configuration directory (see\n the `config_dir` method) if they come from a file. Otherwise,\n they are relative to the current working directory. This helps\n attain the expected behavior when using command-line options.\n \"\"\"\n def __init__(self, default=REQUIRED, cwd=None, relative_to=None,\n in_app_dir=False):\n \"\"\"`relative_to` is the name of a sibling value that is\n being validated at the same time.\n\n `in_app_dir` indicates whether the path should be resolved\n inside the application's config directory (even when the setting\n does not come from a file).\n \"\"\"\n super(Filename, self).__init__(default)\n self.cwd = cwd\n self.relative_to = relative_to\n self.in_app_dir = in_app_dir\n\n def __repr__(self):\n args = []\n\n if self.default is not REQUIRED:\n args.append(repr(self.default))\n\n if sel\n... [truncated 8171 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "beetbox__confuse-697e96cd08ad", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/beetbox__confuse-697e96cd08ad", "repo_key": "beetbox__confuse", "repo": "beetbox/confuse", "base_commit": "200203f9c4a5cbff31357c8382aab8fbc2e5152f", "source_files": ["confuse/templates.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Filename defaults and relative paths behave unexpectedly\n\n## Description\nCurrently, `Filename.default` values are strictly validated as if they were final filenames, preventing the use of template-like default values. This restricts the flexibility of defining default filename patterns. Additionally, it's not possible to define a `Filename` that is relative to another `Filename` if the parent `Filename` is only defined via a default value and not explicitly present in the configuration.\n\nThe expected behavior is for `Filename.default` to accept any template-like string, and for relative `Filename` definitions to correctly resolve against parent `Filename`s that have default values, even if those parents are not explicitly configured.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `72eb9a44f398` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### confit.py\n```python\n# This file is part of Confit.\n# Copyright 2014, Adrian Sampson.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n\"\"\"Worry-free YAML configuration files.\n\"\"\"\nfrom __future__ import unicode_literals\nimport platform\nimport os\nimport pkgutil\nimport sys\nimport yaml\nimport types\nimport collections\nimport re\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict\n\nUNIX_DIR_VAR = 'XDG_CONFIG_HOME'\nUNIX_DIR_FALLBACK = '~/.config'\nWINDOWS_DIR_VAR = 'APPDATA'\nWINDOWS_DIR_FALLBACK = '~\\\\AppData\\\\Roaming'\nMAC_DIR = '~/Library/Application Support'\n\nCONFIG_FILENAME = 'config.yaml'\nDEFAULT_FILENAME = 'config_default.yaml'\nROOT_NAME = 'root'\n\nYAML_TAB_PROBLEM = \"found character '\\\\t' that cannot start any token\"\n\n\n# Utilities.\n\nPY3 = sys.version_info[0] == 3\nSTRING = str if PY3 else unicode\nBASESTRING = str if PY3 else basestring\nNUMERIC_TYPES = (int, float) if PY3 else (int, float, long)\nTYPE_TYPES = (type,) if PY3 else (type, types.ClassType)\n\n\ndef iter_first(sequence):\n \"\"\"Get the first element from an iterable or raise a ValueError if\n the iterator generates no values.\n \"\"\"\n it = iter(sequence)\n try:\n if PY3:\n return next(it)\n else:\n return it.next()\n except StopIteration:\n raise ValueError()\n\n\n# Exceptions.\n\nclass ConfigError(Exception):\n \"\"\"Base class for exceptions raised when querying a configuration.\n \"\"\"\n\n\nclass NotFoundError(ConfigError):\n \"\"\"A requested value could not be found in the configuration trees.\n \"\"\"\n\n\nclass ConfigValueError(ConfigError):\n \"\"\"The value in the configuration is illegal.\"\"\"\n\n\nclass ConfigTypeError(ConfigValueError):\n \"\"\"The value in the configuration did not match the expected type.\n \"\"\"\n\n\nclass ConfigTemplateError(ConfigError):\n \"\"\"Base class for exceptions raised because of an invalid template.\n \"\"\"\n\n\nclass ConfigReadError(ConfigError):\n \"\"\"A configuration file could not be read.\"\"\"\n def __init__(self, filename, reason=None):\n self.filename = filename\n self.reason = reason\n\n message = 'file {0} could not be read'.format(filename)\n if isinstance(reason, yaml.scanner.ScannerError) and \\\n reason.problem == YAML_TAB_PROBLEM:\n # Special-case error message for tab indentation in YAML markup.\n message += ': found tab character at line {0}, column {1}'.format(\n reason.problem_mark.line + 1,\n reason.problem_mark.column + 1,\n )\n elif reason:\n # Generic error message uses exception's message.\n message += ': {0}'.format(reason)\n\n super(ConfigReadError, self).__init__(message)\n\n\n# Views and sources.\n\nclass ConfigSource(dict):\n \"\"\"A dictionary augmented with metadata about the source of the\n configuration.\n \"\"\"\n def __init__(self, value, filename=None, default=False):\n super(ConfigSource, self).__init__(value)\n if filename is not None and not isinstance(filename, BASESTRING):\n raise TypeError('filename must be a string or None')\n self.filename = filename\n self.default = default\n\n def __repr__(self):\n return 'ConfigSource({0}, {1}, {2})'.format(\n super(ConfigSource, self).__repr__(),\n repr(self.filename),\n repr(self.default)\n )\n\n @classmethod\n def of(self, value):\n \"\"\"Given either a dictionary or a `ConfigSource` object, return\n a `ConfigSource` object. This lets a function accept either type\n of object as an argument.\n \"\"\"\n if isinstance(value, ConfigSource):\n return value\n elif isinstance(value, dict):\n return ConfigSource(value)\n else:\n raise TypeError('source value must be a dict')\n\n\nclass ConfigView(object):\n \"\"\"A configuration \"view\" is a query into a program's configuration\n data. A view represents a hypothetical location in the configuration\n tree; to extract the data from the location, a client typically\n calls the ``view.get()`` method. The client can access children in\n the tree (subviews) by subscripting the parent view (i.e.,\n ``view[key]``).\n \"\"\"\n\n name = None\n \"\"\"The name of the view, depicting the path taken through the\n configuration in Python-like syntax (e.g., ``foo['bar'][42]``).\n \"\"\"\n\n def resolve(self):\n \"\"\"The core (internal) data retrieval method. Generates (value,\n source) pairs for each source that contains a value for this\n view. May raise ConfigTypeError if a type error occurs while\n traversing a source.\n \"\"\"\n raise NotImplementedError\n\n def first(self):\n \"\"\"Return a (value, source) pair for the first object found for\n this view. This amounts to the first element returned by\n `resolve`. If no values are available, a NotFoundError is\n raised.\n \"\"\"\n pairs = self.resolve()\n try:\n return iter_first(pairs)\n except ValueError:\n raise NotFoundError(\"{0} not found\".format(self.name))\n\n def exists(self):\n \"\"\"Determine whether the view has a setting in any source.\n \"\"\"\n try:\n self.first()\n except NotFoundError:\n return False\n return True\n\n def add(self, value):\n \"\"\"Set the *default* value for this configuration view. The\n specified value is added as the lowest-priority configuration\n data source.\n \"\"\"\n raise NotImplementedError\n\n def set(self, value):\n \"\"\"*Override* the value for this configuration view. The\n specified value is added as the highest-priority configuration\n data source.\n \"\"\"\n raise NotImplementedError\n\n def root(self):\n \"\"\"The RootView object from which this view is descended.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n return '' % self.name\n\n def __getitem__(self, key):\n \"\"\"Get a subview of this view.\"\"\"\n return Subview(self, key)\n\n def __setitem__(self, key, value):\n \"\"\"Create an overlay source to assign a given key under this\n view.\n \"\"\"\n self.set({key: value})\n\n def set_args(self, namespace):\n \"\"\"Overlay parsed command-line arguments, generated by a library\n like argparse or optparse, onto this view's value.\n \"\"\"\n args = {}\n for key, value in namespace.__dict__.items():\n if value is not None: # Avoid unset options.\n args[key] = value\n self.set(args)\n\n # Magical conversions. These special methods make it possible to use\n # View objects somewhat transparently in certain circumstances. For\n # example, rather than using ``view.get(bool)``, it's possible to\n # just say ``bool(view)`` or use ``view`` in a conditional.\n\n def __str__(self):\n \"\"\"Gets the value for this view as a byte string.\"\"\"\n return str(self.get())\n\n def __unicode__(self):\n \"\"\"Gets the value for this view as a unicode string. (Python 2\n only.)\n \"\"\"\n return unicode(self.get())\n\n def __nonzero__(self):\n \"\"\"Gets the value for this view as a boolean. (Python 2 only.)\n \"\"\"\n return self.__bool__()\n\n def __bool__(self):\n \"\"\"Gets the value for this view as a boolean. (Python 3 only.)\n \"\"\"\n return bool(self.get())\n\n # Dictionary emulation methods.\n\n def keys(self):\n \"\"\"Returns a list containing all the keys available as subviews\n of the current views. This enumerates all the keys in *all*\n dictionaries matching the current view, in contrast to\n ``view.get(dict).keys()``, which gets all the keys for the\n *first* dict matching the view. If the object for this view in\n any source is not a dict, then a ConfigTypeError is raised. The\n keys are ordered according to how they appear in each source.\n \"\"\"\n keys = []\n\n for dic, _ in self.resolve():\n try:\n cur_keys = dic.keys()\n except AttributeError:\n raise ConfigTypeError(\n '{0} must be a dict, not {1}'.format(\n self.name, type(dic).__name__\n )\n )\n\n for key in cur_keys:\n if key not in keys:\n keys.append(key)\n\n return keys\n\n def items(self):\n \"\"\"Iterates over (key, subview) pairs contained in dictionaries\n from *all* sources at this view. If the object for this view in\n any source is not a dict, then a ConfigTypeError is raised.\n \"\"\"\n for key in self.keys():\n yield key, self[key]\n\n def values(self):\n \"\"\"Iterates over all the subviews contained in dictionaries from\n *all* sources at this view. If the object for this view in any\n source is not a dict, then a ConfigTypeError is raised.\n \"\"\"\n for key in self.keys():\n yield self[key]\n\n # List/sequence emulation.\n\n def all_contents(self):\n \"\"\"Iterates over all subviews from collections at this view from\n *all* sources. If the object for this view in any source is not\n iterable, then a ConfigTypeError is raised. This method is\n intended to be used when the view indicates a list; this method\n will concatenate the contents of the list from all sources.\n \"\"\"\n for collection, _ in self.resolve():\n try:\n it = iter(collection)\n except TypeError:\n raise ConfigTypeError(\n '{0} must be an iterable, not {1}'.format(\n self.name, type(collection).__name__\n )\n )\n for value in it:\n yield value\n\n # Validation and conversion.\n\n def flatten(self):\n \"\"\"Create a hierarchy of OrderedDicts containing the data from\n this view, recursively reifying all views to get their\n represented values.\n \"\"\"\n od = OrderedDict()\n for key, view in self.items():\n try:\n od[key] = view.flatten()\n except ConfigTypeError:\n od[key] = view.get()\n return od\n\n def get(self, template=None):\n \"\"\"Retrieve the value for this view according to the template.\n\n The `template` against which the values are checked can be\n anything convertible to a `Template` using `as_template`. This\n means you can pass in a default integer or string value, for\n example, or a type to just check that something matches the type\n you expect.\n\n May raise a `ConfigValueError` (or its subclass,\n `ConfigTypeError`) or a `NotFoundError` when the configuration\n doesn't satisfy the template.\n \"\"\"\n return as_template(template).value(self, template)\n\n # Old validation methods (deprecated).\n\n def as_filename(self):\n return self.get(Filename())\n\n def as_choice(self, choices):\n return self.get(Choice(choices))\n\n def as_number(self):\n return self.get(Number())\n\n def as_str_seq(self):\n return self.get(StrSeq())\n\n\nclass RootView(ConfigView):\n \"\"\"The base of a view hierarchy. This view keeps track of the\n sources that may be accessed by subviews.\n \"\"\"\n def __init__(self, sources):\n \"\"\"Create a configuration hierarchy for a list of sources. At\n least one source must be provided. The first source in the list\n has the highest priority.\n \"\"\"\n self.sources = list(sources)\n self.name = ROOT_NAME\n\n def add(self, obj):\n self.sources.append(ConfigSource.of(obj))\n\n def set(self, value):\n self.sources.insert(0, ConfigSource.of(value))\n\n def resolve(self):\n return ((dict(s), s) for s in self.sources)\n\n def clear(self):\n \"\"\"Remove all sources from this configuration.\"\"\"\n del self.sources[:]\n\n def root(self):\n return self\n\n\nclass Subview(ConfigView):\n \"\"\"A subview accessed via a subscript of a parent view.\"\"\"\n def __init__(self, parent, key):\n \"\"\"Make a subview of a parent view for a given subscript key.\n \"\"\"\n self.parent = parent\n self.key = key\n\n # Choose a human-readable name for this view.\n if isinstance(self.parent, RootView):\n self.name = ''\n else:\n self.name = self.parent.name\n if not isinstance(self.key, int):\n self.name += '.'\n if isinstance(self.key, int):\n self.name += '#{0}'.format(self.key)\n elif isinstance(self.key, BASESTRING):\n self.name += '{0}'.format(self.key)\n else:\n self.name += '{0}'.format(repr(self.key))\n\n def resolve(self):\n for collection, source in self.parent.resolve():\n try:\n value = collection[self.key]\n except IndexError:\n # List index out of bounds.\n continue\n except KeyError:\n # Dict key does not exist.\n continue\n except TypeError:\n # Not subscriptable.\n raise ConfigTypeError(\n \"{0} must be a collection, not {1}\".format(\n self.parent.name, type(collection).__name__\n )\n )\n yield value, source\n\n def set(self, value):\n self.parent.set({self.key: value})\n\n def add(self, value):\n self.parent.add({self.key: value})\n\n def root(self):\n return self.parent.root()\n\n\n# Config file paths, including platform-specific paths and in-package\n# defaults.\n\n# Based on get_root_path from Flask by Armin Ronacher.\ndef _package_path(name):\n \"\"\"Returns the path to the package containing the named module or\n None if the path could not be identified (e.g., if\n ``name == \"__main__\"``).\n \"\"\"\n loader = pkgutil.get_loader(name)\n if loader is None or name == '__main__':\n return None\n\n if hasattr(loader, 'get_filename'):\n filepath = loader.get_filename(name)\n else:\n # Fall back to importing the specified module.\n __import__(name)\n filepath = sys.modules[name].__file__\n\n return os.path.dirname(os.path.abspath(filepath))\n\n\ndef config_dirs():\n \"\"\"Return a platform-specific list of candidates for user\n configuration directories on the system.\n\n The candidates are in order of priority, from highest to lowest. The\n last element is the \"fallback\" location to be used when no\n higher-priority config file exists.\n \"\"\"\n paths = []\n\n if platform.system() == 'Darwin':\n paths.append(MAC_DIR)\n paths.append(UNIX_DIR_FALLBACK)\n if UNIX_DIR_VAR in os.environ:\n paths.append(os.environ[UNIX_DIR_VAR])\n\n elif platform.system() == 'Windows':\n paths.append(WINDOWS_DIR_FALLBACK)\n if WINDOWS_DIR_VAR in os.environ:\n paths.append(os.environ[WINDOWS_DIR_VAR])\n\n else:\n # Assume Unix.\n paths.append(UNIX_DIR_FALLBACK)\n if UNIX_DIR_VAR in os.environ:\n paths.append(os.environ[UNIX_DIR_VAR])\n\n # Expand and deduplicate paths.\n out = []\n for path in paths:\n path = os.path.abspath(os.path.e\n... [truncated 26131 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "beetbox__confuse-d08fb659732c", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/beetbox__confuse-d08fb659732c", "repo_key": "beetbox__confuse", "repo": "beetbox/confuse", "base_commit": "72eb9a44f3986b54cf0692efc7cd7a0fdc65919f", "source_files": ["confit.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Application does not load configuration from XDG_CONFIG_DIRS\n\n## Description\nThe application fails to discover and load configuration files located in directories specified by the `XDG_CONFIG_DIRS` environment variable.\n\n**Reproduction:**\n1. Set `XDG_CONFIG_DIRS` to a path like `/etc/xdg:/usr/local/etc/xdg`.\n2. Place a relevant configuration file (e.g., `myapp.conf`) in `/etc/xdg/myapp.conf`.\n3. Run the application.\n\n**Expected behavior:**\nThe application should load `myapp.conf` from `/etc/xdg/myapp.conf`.\n\n**Actual behavior:**\nThe application does not find or apply the configuration from `/etc/xdg/myapp.conf`.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `d4ab55771649` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### confuse.py\n```python\n# -*- coding: utf-8 -*-\n# This file is part of Confuse.\n# Copyright 2016, Adrian Sampson.\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n\n\"\"\"Worry-free YAML configuration files.\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\ntry:\n import enum\n SUPPORTS_ENUM = True\nexcept ImportError:\n SUPPORTS_ENUM = False\n\nimport argparse\nimport optparse\nimport platform\nimport os\nimport pkgutil\nimport sys\nimport yaml\nimport collections\nimport re\nfrom collections import OrderedDict\n\nUNIX_DIR_VAR = 'XDG_CONFIG_HOME'\nUNIX_DIR_FALLBACK = '~/.config'\nWINDOWS_DIR_VAR = 'APPDATA'\nWINDOWS_DIR_FALLBACK = '~\\\\AppData\\\\Roaming'\nMAC_DIR = '~/Library/Application Support'\n\nCONFIG_FILENAME = 'config.yaml'\nDEFAULT_FILENAME = 'config_default.yaml'\nROOT_NAME = 'root'\n\nYAML_TAB_PROBLEM = \"found character '\\\\t' that cannot start any token\"\n\nREDACTED_TOMBSTONE = 'REDACTED'\n\n\n# Utilities.\n\nPY3 = sys.version_info[0] == 3\nSTRING = str if PY3 else unicode # noqa ignore=F821\nBASESTRING = str if PY3 else basestring # noqa ignore=F821\nNUMERIC_TYPES = (int, float) if PY3 else (int, float, long) # noqa ignore=F821\n\n\ndef iter_first(sequence):\n \"\"\"Get the first element from an iterable or raise a ValueError if\n the iterator generates no values.\n \"\"\"\n it = iter(sequence)\n try:\n return next(it)\n except StopIteration:\n raise ValueError()\n\n\ndef namespace_to_dict(obj):\n \"\"\"If obj is argparse.Namespace or optparse.Values we'll return\n a dict representation of it, else return the original object.\n\n Redefine this method if using other parsers.\n\n :param obj: *\n :return:\n :rtype: dict or *\n \"\"\"\n if isinstance(obj, (argparse.Namespace, optparse.Values)):\n return vars(obj)\n return obj\n\n\n# Exceptions.\n\nclass ConfigError(Exception):\n \"\"\"Base class for exceptions raised when querying a configuration.\n \"\"\"\n\n\nclass NotFoundError(ConfigError):\n \"\"\"A requested value could not be found in the configuration trees.\n \"\"\"\n\n\nclass ConfigValueError(ConfigError):\n \"\"\"The value in the configuration is illegal.\"\"\"\n\n\nclass ConfigTypeError(ConfigValueError):\n \"\"\"The value in the configuration did not match the expected type.\n \"\"\"\n\n\nclass ConfigTemplateError(ConfigError):\n \"\"\"Base class for exceptions raised because of an invalid template.\n \"\"\"\n\n\nclass ConfigReadError(ConfigError):\n \"\"\"A configuration file could not be read.\"\"\"\n def __init__(self, filename, reason=None):\n self.filename = filename\n self.reason = reason\n\n message = u'file {0} could not be read'.format(filename)\n if isinstance(reason, yaml.scanner.ScannerError) and \\\n reason.problem == YAML_TAB_PROBLEM:\n # Special-case error message for tab indentation in YAML markup.\n message += u': found tab character at line {0}, column {1}'.format(\n reason.problem_mark.line + 1,\n reason.problem_mark.column + 1,\n )\n elif reason:\n # Generic error message uses exception's message.\n message += u': {0}'.format(reason)\n\n super(ConfigReadError, self).__init__(message)\n\n\n# Views and sources.\n\nclass ConfigSource(dict):\n \"\"\"A dictionary augmented with metadata about the source of the\n configuration.\n \"\"\"\n def __init__(self, value, filename=None, default=False):\n super(ConfigSource, self).__init__(value)\n if filename is not None and not isinstance(filename, BASESTRING):\n raise TypeError(u'filename must be a string or None')\n self.filename = filename\n self.default = default\n\n def __repr__(self):\n return 'ConfigSource({0!r}, {1!r}, {2!r})'.format(\n super(ConfigSource, self),\n self.filename,\n self.default,\n )\n\n @classmethod\n def of(cls, value):\n \"\"\"Given either a dictionary or a `ConfigSource` object, return\n a `ConfigSource` object. This lets a function accept either type\n of object as an argument.\n \"\"\"\n if isinstance(value, ConfigSource):\n return value\n elif isinstance(value, dict):\n return ConfigSource(value)\n else:\n raise TypeError(u'source value must be a dict')\n\n\nclass ConfigView(object):\n \"\"\"A configuration \"view\" is a query into a program's configuration\n data. A view represents a hypothetical location in the configuration\n tree; to extract the data from the location, a client typically\n calls the ``view.get()`` method. The client can access children in\n the tree (subviews) by subscripting the parent view (i.e.,\n ``view[key]``).\n \"\"\"\n\n name = None\n \"\"\"The name of the view, depicting the path taken through the\n configuration in Python-like syntax (e.g., ``foo['bar'][42]``).\n \"\"\"\n\n def resolve(self):\n \"\"\"The core (internal) data retrieval method. Generates (value,\n source) pairs for each source that contains a value for this\n view. May raise ConfigTypeError if a type error occurs while\n traversing a source.\n \"\"\"\n raise NotImplementedError\n\n def first(self):\n \"\"\"Return a (value, source) pair for the first object found for\n this view. This amounts to the first element returned by\n `resolve`. If no values are available, a NotFoundError is\n raised.\n \"\"\"\n pairs = self.resolve()\n try:\n return iter_first(pairs)\n except ValueError:\n raise NotFoundError(u\"{0} not found\".format(self.name))\n\n def exists(self):\n \"\"\"Determine whether the view has a setting in any source.\n \"\"\"\n try:\n self.first()\n except NotFoundError:\n return False\n return True\n\n def add(self, value):\n \"\"\"Set the *default* value for this configuration view. The\n specified value is added as the lowest-priority configuration\n data source.\n \"\"\"\n raise NotImplementedError\n\n def set(self, value):\n \"\"\"*Override* the value for this configuration view. The\n specified value is added as the highest-priority configuration\n data source.\n \"\"\"\n raise NotImplementedError\n\n def root(self):\n \"\"\"The RootView object from which this view is descended.\n \"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n return '<{}: {}>'.format(self.__class__.__name__, self.name)\n\n def __iter__(self):\n \"\"\"Iterate over the keys of a dictionary view or the *subviews*\n of a list view.\n \"\"\"\n # Try getting the keys, if this is a dictionary view.\n try:\n keys = self.keys()\n for key in keys:\n yield key\n\n except ConfigTypeError:\n # Otherwise, try iterating over a list.\n collection = self.get()\n if not isinstance(collection, (list, tuple)):\n raise ConfigTypeError(\n u'{0} must be a dictionary or a list, not {1}'.format(\n self.name, type(collection).__name__\n )\n )\n\n # Yield all the indices in the list.\n for index in range(len(collection)):\n yield self[index]\n\n def __getitem__(self, key):\n \"\"\"Get a subview of this view.\"\"\"\n return Subview(self, key)\n\n def __setitem__(self, key, value):\n \"\"\"Create an overlay source to assign a given key under this\n view.\n \"\"\"\n self.set({key: value})\n\n def __contains__(self, key):\n return self[key].exists()\n\n @classmethod\n def _build_namespace_dict(cls, obj, dots=False):\n \"\"\"Recursively replaces all argparse.Namespace and optparse.Values\n with dicts and drops any keys with None values.\n\n Additionally, if dots is True, will expand any dot delimited\n keys.\n\n :param obj: Namespace, Values, or dict to iterate over. Other\n values will simply be returned.\n :type obj: argparse.Namespace or optparse.Values or dict or *\n :param dots: If True, any properties on obj that contain dots (.)\n will be broken down into child dictionaries.\n :return: A new dictionary or the value passed if obj was not a\n dict, Namespace, or Values.\n :rtype: dict or *\n \"\"\"\n # We expect our root object to be a dict, but it may come in as\n # a namespace\n obj = namespace_to_dict(obj)\n # We only deal with dictionaries\n if not isinstance(obj, dict):\n return obj\n\n # Get keys iterator\n keys = obj.keys() if PY3 else obj.iterkeys()\n if dots:\n # Dots needs sorted keys to prevent parents from\n # clobbering children\n keys = sorted(list(keys))\n\n output = {}\n for key in keys:\n value = obj[key]\n if value is None: # Avoid unset options.\n continue\n\n save_to = output\n result = cls._build_namespace_dict(value, dots)\n if dots:\n # Split keys by dots as this signifies nesting\n split = key.split('.')\n if len(split) > 1:\n # The last index will be the key we assign result to\n key = split.pop()\n # Build the dict tree if needed and change where\n # we're saving to\n for child_key in split:\n if child_key in save_to and \\\n isinstance(save_to[child_key], dict):\n save_to = save_to[child_key]\n else:\n # Clobber or create\n save_to[child_key] = {}\n save_to = save_to[child_key]\n\n # Save\n if key in save_to:\n save_to[key].update(result)\n else:\n save_to[key] = result\n return output\n\n def set_args(self, namespace, dots=False):\n \"\"\"Overlay parsed command-line arguments, generated by a library\n like argparse or optparse, onto this view's value.\n\n :param namespace: Dictionary or Namespace to overlay this config with.\n Supports nested Dictionaries and Namespaces.\n :type namespace: dict or Namespace\n :param dots: If True, any properties on namespace that contain dots (.)\n will be broken down into child dictionaries.\n :Example:\n\n {'foo.bar': 'car'}\n # Will be turned into\n {'foo': {'bar': 'car'}}\n :type dots: bool\n \"\"\"\n self.set(self._build_namespace_dict(namespace, dots))\n\n # Magical conversions. These special methods make it possible to use\n # View objects somewhat transparently in certain circumstances. For\n # example, rather than using ``view.get(bool)``, it's possible to\n # just say ``bool(view)`` or use ``view`` in a conditional.\n\n def __str__(self):\n \"\"\"Get the value for this view as a bytestring.\n \"\"\"\n if PY3:\n return self.__unicode__()\n else:\n return bytes(self.get())\n\n def __unicode__(self):\n \"\"\"Get the value for this view as a Unicode string.\n \"\"\"\n return STRING(self.get())\n\n def __nonzero__(self):\n \"\"\"Gets the value for this view as a boolean. (Python 2 only.)\n \"\"\"\n return self.__bool__()\n\n def __bool__(self):\n \"\"\"Gets the value for this view as a boolean. (Python 3 only.)\n \"\"\"\n return bool(self.get())\n\n # Dictionary emulation methods.\n\n def keys(self):\n \"\"\"Returns a list containing all the keys available as subviews\n of the current views. This enumerates all the keys in *all*\n dictionaries matching the current view, in contrast to\n ``view.get(dict).keys()``, which gets all the keys for the\n *first* dict matching the view. If the object for this view in\n any source is not a dict, then a ConfigTypeError is raised. The\n keys are ordered according to how they appear in each source.\n \"\"\"\n keys = []\n\n for dic, _ in self.resolve():\n try:\n cur_keys = dic.keys()\n except AttributeError:\n raise ConfigTypeError(\n u'{0} must be a dict, not {1}'.format(\n self.name, type(dic).__name__\n )\n )\n\n for key in cur_keys:\n if key not in keys:\n keys.append(key)\n\n return keys\n\n def items(self):\n \"\"\"Iterates over (key, subview) pairs contained in dictionaries\n from *all* sources at this view. If the object for this view in\n any source is not a dict, then a ConfigTypeError is raised.\n \"\"\"\n for key in self.keys():\n yield key, self[key]\n\n def values(self):\n \"\"\"Iterates over all the subviews contained in dictionaries from\n *all* sources at this view. If the object for this view in any\n source is not a dict, then a ConfigTypeError is raised.\n \"\"\"\n for key in self.keys():\n yield self[key]\n\n # List/sequence emulation.\n\n def all_contents(self):\n \"\"\"Iterates over all subviews from collections at this view from\n *all* sources. If the object for this view in any source is not\n iterable, then a ConfigTypeError is raised. This method is\n intended to be used when the view indicates a list; this method\n will concatenate the contents of the list from all sources.\n \"\"\"\n for collection, _ in self.resolve():\n try:\n it = iter(collection)\n except TypeError:\n raise ConfigTypeError(\n u'{0} must be an iterable, not {1}'.format(\n self.name, type(collection).__name__\n )\n )\n for value in it:\n yield value\n\n # Validation and conversion.\n\n def flatten(self, redact=False):\n \"\"\"Create a hierarchy of OrderedDicts containing the data from\n this view, recursively reifying all views to get their\n represented values.\n\n If `redact` is set, then sensitive values are replaced with\n the string \"REDACTED\".\n \"\"\"\n od = OrderedDict()\n for key, view in self.items():\n if redact and view.redact:\n od[key] = REDACTED_TOMBSTONE\n else:\n try:\n od[key] = view.flatten(redact=redact)\n except ConfigTypeError:\n od[key] = view.get()\n return od\n\n def get(self, template=None):\n \"\"\"Retrieve the value for this view according to the template.\n\n The `template` against which the values are checked can be\n anything convertible to a `Template` using `as_template`. This\n means you can pass in a default integer or string value, for\n example, or a type to just check that something matches the type\n you expect.\n\n May raise a `ConfigValueError` (or its subclass,\n `ConfigTypeError`) or a `NotFoundError` when the configuration\n doesn't satisfy the template.\n \"\"\"\n return as_template(template).value(self, template)\n\n # Shortc\n... [truncated 37417 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "beetbox__confuse-d182a8c39c53", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/beetbox__confuse-d182a8c39c53", "repo_key": "beetbox__confuse", "repo": "beetbox/confuse", "base_commit": "d4ab55771649c21e1650331382b97d8cc9f956c1", "source_files": ["confuse.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** \"Payment not received\" failed-SIP rows are not classified as REVERSAL\n\n## Description\nWhen processing SIP rows, entries that have both the status \"Payment not received\" and are marked as \"failed-SIP\" are not being correctly classified. Currently, these specific rows are not categorized as `REVERSAL`. The expected behavior is for all rows matching these criteria to be classified as `REVERSAL`.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `220edcfd7a16` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 1.0.0\n\nMajor release. The parsing backend was rewritten from scratch on\n[pypdfium2](https://github.com/pypdfium2-team/pypdfium2) (Apache-2.0 /\nBSD-3) and the four supported CAS issuers now each have a dedicated\nparser tuned to their template family.\n\n### Breaking changes\n\n- **pdfminer.six and PyMuPDF backends removed.** `casparser.read_cas_pdf`\n no longer dispatches between them. The `mupdf` / `fast` extras in\n `pyproject.toml` are gone. The `--force-pdfminer` CLI flag and the\n `force_pdfminer=` kwarg on `read_cas_pdf` are kept as no-ops; the\n kwarg emits a `DeprecationWarning` and is otherwise ignored.\n- **License simplified to pure MIT.** With the GPL/AGPL-licensed\n PyMuPDF dependency gone, the `licenses/` directory of GPL/AGPL\n copies has been removed. pypdfium2 is dual Apache-2.0 / BSD-3 and\n doesn't impose any copyleft obligation on users of casparser.\n- **Minimum Python is now 3.11.** 3.9 / 3.10 classifiers dropped from\n `pyproject.toml`.\n- **`CASData.investor_info` is now `Optional[InvestorInfo]`** (matches\n the `NSDLCASData.investor_info` shape that already existed). It is\n populated on every supported issuer, but consumers should still\n guard against the `None` case for unfamiliar templates.\n- **Internal `casparser.process` package removed.** The two helpers\n downstream code still imports from it are now at\n `casparser.parsers._classify` (`get_parsed_scheme_name`,\n `get_transaction_type`) and `casparser.parsers._isin` (`isin_search`).\n\n### New\n\n- **First-class NSDL and CDSL parsers.** Drops the regex-on-text\n approach the 0.8 NSDL/CDSL code used; the new parsers consume\n structured `Block`/`Cell` records directly from `pypdfium2`. Several\n bugs the v0.8 NSDL/CDSL code shipped with are no longer in scope\n (misplaced-UCC-as-folio on NSDL MF Holdings, space-merged\n folio+units cells on CDSL, the silently-dropped NSDL HDFC\n subaccount on CDSL multi-account statements, `Optional[Decimal]`\n comma-strip miss in the `MutualFund` validator).\n- **CAMS / KFin 2026 templates supported** out of the box. The newer\n CAMS SUMMARY template added an ISIN column the v0.8 regex didn't\n match; v1.0 parses all rows. The newer KFin SUMMARY template emits\n zero-balance schemes with single-space-separated trio cells that\n the v0.8 regex required `\\t\\t` between; v1.0 picks them up too.\n- **AMC-header detection extended** to include the `Fund House`\n suffix. v0.8's regex only matched `Mutual Fund` / `MF` suffixes,\n so schemes from a few newer AMCs whose names end in `Fund House`\n ended up bucketed under the previous AMC.\n- **ISIN / AMFI enrichment has a direct-ISIN fallback** path via\n `MFISINDb.direct_isin_lookup` for the case where multi-line\n `Registrar:` rendering corrupts the RTA token.\n- **Schedule 112A column 1b** (\"Share/Unit Transferred\") is emitted\n for FY2024-25 onward, per the AY 2025-26 ITR utility template. The\n Finance (No. 2) Act 2024 split the equity-LTCG regime on\n 23-Jul-2024; the 112A CSV now flags each transfer `BE`/`AE` against\n that date and splits an after-31-Jan-2018-acquired fund into\n separate rows when it was sold on both sides of the cutoff. Older\n FYs keep the 14-column layout their utility expects.\n- **Cost Inflation Index extended to FY2025-26 (376)** and the\n FY2024-25 value corrected from `365` to the CBDT-notified `363`\n (the wrong value slightly mis-indexed debt-fund LTCG cost of\n acquisition for FY2024-25 sales).\n\n### Fixed\n\n- **CAMS SUMMARY `valuation.date` no longer mis-parses to year 201**\n (was a column-boundary bug \u2014 the NAVDate column treated as\n right-aligned with a 42pt width clipped the trailing year digit,\n then Pydantic mis-coerced the `01-Jan-201` string).\n- **CDSL multi-account statements** (5+ demat accounts on one PDF) are\n now parsed correctly. Earlier the page-3+ scan only kicked in from\n page 8, dropping holdings sections that landed on pages 4-7.\n- **CDSL MF holdings** rows with `DIRECT` (or any non-`ARN-XXXX`\n distribution-mode token) now correctly populate `pnl` and `return_`.\n- **Leading-dot decimals** (`.196`, `-.5`) are now recognised as\n numeric by the NSDL / CDSL cell classifier. CDSL occasionally\n drops the leading zero on sub-unit balances; under the old regex\n those cells were mis-bucketed as text, shifting the row layout\n and producing a silent `\u03a3holdings \u2260 balance` mismatch.\n- **KFin `... - Reversed` transaction rows** (e.g. the Franklin\n wound-up debt schemes' `Payment - Units Extinguished-Reversed`\n entries) had their units cell printed with cosmetic parentheses\n even though the semantic sign is the opposite of the original.\n A new running-balance cross-check in the CAMS / KFin DETAILED\n parser flips the sign (and matching amount) on any single-row\n mis-parse and reclassifies the transaction type via the\n positive-units branch of `get_transaction_type`. Acts as a\n self-validating safety net for the entire transaction stream,\n not just the Franklin case.\n- **Stamp-duty allocation on split lots.** When a single purchase\n lot is consumed across N disposals the `FIFOUnits.sell` re-queue\n carried the *full* original stamp duty on every remaining slice,\n so the proportional allocation re-claimed the same paid stamp\n on each disposal \u2014 total stamp claimed grew unboundedly with\n split depth. (Worked example: 300-unit lot with \u20b91.25 stamp,\n split 100/100/100 \u2192 total claimed \u20b92.29 vs \u20b91.25 paid, an 84%\n over-claim that further widens for deeper splits.) The lot is\n now re-queued with the *unallocated remainder* (`purchase_tax -\n stamp_duty`), so the invariant `\u03a3(stamp_claimed) == stamp_paid`\n holds exactly across any number of partial consumptions. Section\n 48 only permits deducting the stamp actually paid as a\n transfer expense, so the prior behaviour over-stated the\n deduction on Schedule 112A.\n- **Soft-hyphen-wrapped tokens in NSDL / CDSL holdings.** Some CAS\n generators insert a `U+00AD` soft hyphen at the point where a long\n token (notably a 12-char ISIN) wraps across two display lines, e.g.\n `INF179K01WN9`. The block/cell extractor now treats a trailing\n soft hyphen as a continuation marker (splicing the next fragment on\n with no separator) and strips any embedded soft hyphens, so the\n token is reconstructed intact. Previously the wrapped ISIN matched\n neither the anchored ISIN regex nor its leftover, and the holding\n was silently dropped. (Reconstruction works when the wrapped\n fragments fall in the same row block; ISINs split across blocks by\n a non-standard page scale are not covered.)\n\n## 0.9.0 - 2026-05-22\n- Add support for CDSL statements\n- Drop support for Python 3.9 and 3.10; minimum supported version is now 3.11\n- Support PyMuPDF >= 1.25 (1.27.x tested). Older `<1.25` pin removed.\n- Bump `casparser-isin` to `>= 2026.5.1` (new DB format v2 with\n `sebi_category`/`last_seen` columns; ISIN-first lookup priority).\n- Relax other dependency pins (click, colorama, rich, pdfminer.six).\n- Fix `MutualFund.fix_float` pydantic validator so the aliased `return`\n field (Python attribute `return_`) also gets the comma-stripping\n treatment; previously NSDL MF folio rows with a return value of\n 1 lakh or more would fail Decimal validation.\n- Parser robustness fixes for PyMuPDF 1.25+ text extraction quirks\n (all superseded in 1.0.0 by the pypdfium2 rewrite, kept here for\n the historical record).\n\n## 0.8.1 - 2025-09-21\n- NSDL parser bug fixes\n\n## 0.8.0 - 2025-02-26\n- NSDL support: first version\n- various bug fixes\n\n## 0.7.4 - 2023-10-04\n- (fix) fix broken scheme names\n\n## 0.7.3 - 2023-09-26\n- (new) Add support for parsing nominee details (available in `Folio.nominees`)\n- (fix) fix empty PAN in certain cases\n\n## 0.7.2 - 2023-09-19\n- Bug fixes\n - Exclude short term capital gains (STCG) from 112A reports\n - Fix advisor code parsing\n\n# 0.7.1 - 2023-09-06\n- fix bug where long scheme names were getting truncated\n\n## 0.7.0 - 2023-09-03\n- update pydantic to v2\n\n## 0.6.1 - 2023-04-04\n- update CII data till FY2022-23\n- bug fixes\n\n## 0.6.0 - 2023-02-20\n- use pydantic models for better data validation\n\n## 0.5.5 - 2022-08-06\n- bug fix with MuPDF parser\n\n## 0.5.4 - 2022-02-01\n- bug fix in CAS summary statement parser\n\n## 0.5.3 - 2021-08-21\n- support for generating csv files for capital gains in 112A format for income tax filing\n- various bug fixes\n\n## 0.5.2 - 2021-08-11\n- fix crash while generating capital gains reports on dividend payout funds\n- rework capital gains algorithm\n- add `advisor` column in transactions csv\n- various bug fixes\n\n## 0.5.1 - 2021-07-21\n- gains: PnL report\n- support for migration of Franklin Templeton funds to CAMS RTA\n- various bug fixes\n\n## 0.5.0 - 2021-07-02\n- Support for calculating capital gains from detailed CAS statements\n- support for parsing Tax Deducted at Source (`TDS`) transactions\n\n## 0.4.8 - 2021-06-27\n- `REVERSAL` TransactionType to indicate reverted/rejected transactions\n- convert all enums to strEnums for better readability [(#35)](https://github.com/codereverser/casparser/pull/35)\n- fix issue with parsing multi-line transactions\n\n## 0.4.7 - 2021-06-01\n\n- Minor bug fixes in summary-statement parser.\n- cli now uses [rich](http://rich.readthedocs.io/) for console output.\n- Use poetry for dependency management and deployment.\n- **BREAKING CHANGE**: Table output choices have been removed.\n `-s/--summary` is a flag and doesn't accept any additional arguments.\n- Support for folios without PAN (#28).\n- add support for new style dividend transactions after IDCW renaming.\n- improved parser for transaction entries.\n\n## 0.4.6 - 2021-04-04\n\n- New `sort_transactions` option in `casparser.read_cas_pdf` (and `--sort` flag in CLI)\n to fix transactions (and balances) for schemes with non-chronological order.\n- support negative balances in transactions\n\n## 0.4.5 - 2021-03-20\n\n- Support for segregated portfolio transactions [ credits: [abhishekjain-qb](https://github.com/abhishekjain-qb) ]\n\n## 0.4.4 - 2021-02-07\n\n- CSV output fixes\n - better csv output format for summary CAS statements.\n - option to output only summary information for detailed statements\n (`-s fancy_grid -o output.csv`)\n\n## 0.4.3 - 2021-01-30\n\n- ISIN, AMFI code mapping for schemes (**beta**)\n\n## 0.4.2 - 2021-01-22\n\n- fixes unicode issues in windows\n- supports negative scheme balances\n- better scheme name parsing\n- fixes dividend transaction parsing\n\n\n## 0.4.1 - 2021-01-13\n\n- hotfix for parsing folios without KYC details\n\n## 0.4.0 - 2021-01-08\n\n- adds support for parsing summary statements from CAMS/KARVY (**beta**)\n- minor bug fixes in CSV file generation\n\n## 0.3.9 - 2021-01-01\n\n- Support for classifying transactions\n\n## 0.3.8 - 2020-12-29\n\n- Support for parsing folios without PAN/KYC details\n\n## 0.3.7 - 2020-12-24\n\n- Support for parsing dividend transactions\n\n## 0.3.6 - 2020-12-21\n\n- Support for parsing folios without advisor\n\n## 0.3.5 - 2020-11-13\n\n- Support for parsing scheme's latest nav\n- Replaced `texttable` with `tabulate` for more cli output formats\n- Added more test cases\n\n## 0.3.4 - 2020-11-08\n\n- Support for parsing scheme valuation\n- Parser code refactor (transparent to user)\n\n## 0.3.3 - 2020-10-31\n\n- Added `balance` to Transaction\n- Added test cases with travis-ci and codecov support\n- minor bug fixes while parsing kfintech cas files\n\n## 0.3.2 - 2020-10-29\n\n- minor bug fixes\n\n## 0.3.1 - 2020-10-26\n\n- re-release 0.3.0 : Minor bug fix\n\n## 0.3.0 - 2020-10-25\n\n- **Breaking Change**: In order to preserve the order of entries, during format\n conversion to other data types like json., `folios` is a list instead of dict.\n- Added a second parser based on [PyMuPDF](https://github.com/pymupdf/PyMuPDF) /\n[MuPDF](https://mupdf.com/) - ~15-20x faster compared to pure-python pdfminer.\n- Added AMC detection (accessible via `amc` property of folio)\n- CLI summary now includes the number of transactions processed.\n\n## 0.2.1 - 2020-10-23\n\n- `read_cas_pdf` now supports more input types\n- better cli summary output\n- fixed investor info parsing where mobile numbers don't have country code\n- updated dependencies\n\n## 0.2.0 - 2020-10-15\n\n- removed support for python versions <3.8\n- Better investor info parser\n\n## 0.1.2 - 2020-10-14\n\n- Support for parsing investor info\n\n## 0.1.1 - 2020-10-14\n\n- Support for parsing folios without PAN\n\n## 0.1.0 - 2020-10-11\n\n- Initial release\n\n```\n\n### casparser/parsers/_classify.py\n```python\n\"\"\"Classification helpers shared across the CAMS / KFin parsers.\n\nTwo pure utilities:\n\n- `get_transaction_type` maps a transaction description + signed units\n count to a `TransactionType` enum, also extracting the dividend rate\n for IDCW / dividend lines.\n- `get_parsed_scheme_name` normalises a raw scheme name (drops\n `(formerly ...)`, `(erstwhile ...)`, `(Demat ...)` trailers, collapses\n whitespace).\n\nThese are pulled out of the old `casparser.process.cas_detailed` module\nbecause the pypdfium2 DETAILED parser still needs them but the rest of\nthat module's text-rendering machinery is now gone.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom decimal import Decimal\nfrom typing import Optional, Tuple\n\nfrom casparser.enums import TransactionType\n\n# Matches an IDCW / dividend transaction description. Captures the\n# \"reinvest\" hint (if present) and the per-unit rupee value.\nDIVIDEND_RE = re.compile(\n r\"(?:div\\.|dividend|idcw).+?(reinvest)*.*?@\\s*Rs\\.\\s*([\\d\\.]+)(?:\\s+per\\s+unit)?\",\n re.I | re.DOTALL,\n)\n\n\ndef get_transaction_type(\n description: str, units: Optional[Decimal]\n) -> Tuple[TransactionType, Optional[Decimal]]:\n \"\"\"Classify a transaction by its description + units sign.\n\n Returns `(transaction_type, dividend_rate_or_None)`. The dividend\n rate is only set for IDCW / dividend transactions.\n \"\"\"\n dividend_rate: Optional[Decimal] = None\n description = description.lower()\n if div_match := DIVIDEND_RE.search(description):\n reinvest_flag, dividend_str = div_match.groups()\n dividend_rate = Decimal(dividend_str)\n txn_type = (\n TransactionType.DIVIDEND_REINVEST if reinvest_flag else TransactionType.DIVIDEND_PAYOUT\n )\n elif units is None:\n if \"stt\" in description:\n txn_type = TransactionType.STT_TAX\n elif \"stamp\" in description:\n txn_type = TransactionType.STAMP_DUTY_TAX\n elif \"tds\" in description:\n txn_type = TransactionType.TDS_TAX\n else:\n txn_type = TransactionType.MISC\n elif units > 0:\n if \"switch\" in description:\n txn_type = (\n TransactionType.SWITCH_IN_MERGER\n if \"merger\" in description\n else TransactionType.SWITCH_IN\n )\n elif \"segregat\" in description:\n txn_type = TransactionType.SEGREGATION\n elif (\n \"sip\" in description\n or \"systematic\" in description\n or re.search(r\"instal+ment\", description, re.I)\n or re.search(r\"sys.+?invest\", description, re.I | re.DOTALL)\n ):\n txn_type = TransactionType.PURCHASE_SIP\n else:\n txn_type = TransactionType.PURCHASE\n elif units < 0:\n if re.search(\n r\"reversal|rejection|dishonoured|mismatch|insufficient\\s+balance\",\n description,\n re.I,\n ):\n txn_type = TransactionType.REVERSAL\n elif \"switch\" in description:\n txn_type = (\n TransactionType.SWITCH_OUT_MERGER\n if \"merger\" in description\n else TransactionType.SWITCH_OUT\n )\n else:\n txn_type = TransactionType.REDEMPTION\n else:\n txn_type = TransactionType.UNKNOWN\n\n return txn_type, dividend_rate\n\n\ndef get_parsed_scheme_name(scheme: str) -> str:\n \"\"\"Strip `(formerly ...)`, `(erstwhile ...)`, `(Demat ...)`,\n `(Non-Demat ...)` trailers; collapse whitespace; trim trailing\n punctuation.\"\"\"\n scheme = re.sub(\n r\"\\((formerly|erstwhile).+?\\)\",\n \"\",\n scheme,\n flags=re.I | re.DOTALL,\n ).strip()\n scheme = re.sub(\n r\"\\((Demat|Non-Demat).*\",\n \"\",\n scheme,\n flags=re.I | re.DOTALL,\n ).strip()\n scheme = re.sub(r\"\\s+\", \" \", scheme).strip()\n return re.sub(r\"[^a-zA-Z0-9_)]+$\", \"\", scheme).strip()\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-0a52e7fcc85f", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-0a52e7fcc85f", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "220edcfd7a16552acbd604fe5892051e73fb30cb", "source_files": ["CHANGELOG.md", "casparser/parsers/_classify.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** PDF documents not closed, and CDSL MF folio numbers incorrectly parsed\n\n## Description\nWhen processing PDF documents using `read_cas_pdf`, `pypdfium` reports \"objects still open\" warnings during application teardown, indicating that PDF documents are not being properly closed after use. PDF documents should be closed to prevent resource leaks and avoid these warnings.\n\nAdditionally, when parsing CDSL Mutual Fund holdings, folio numbers that span across columns (e.g., \"910121125\" in one column and \"82/0\" in an adjacent column) are incorrectly parsed. The \"82/0\" portion is currently misinterpreted as a separate \"mode\" column, leading to the truncation of the actual folio number. The full folio number, such as \"91012112582/0\", should be correctly assembled and parsed as a single entity.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `789865de12b2` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### casparser/parsers/__init__.py\n```python\n\"\"\"Top-level dispatcher for `casparser.read_cas_pdf`.\n\nv1.0 reorganisation: pdfminer.six and PyMuPDF are gone. Everything\nruns on pypdfium2 with parsers that consume structured page-object\ndata directly (no text-rendering / regex round-trip for NSDL+CDSL,\ncolumn-aware layout reading for CAMS+KFin).\n\nThe four issuer-specific parsers live alongside this file:\n\n cams_detailed.py \u2192 CAMS / KFin DETAILED statements\n cams_summary.py \u2192 CAMS / KFin SUMMARY statements\n nsdl.py \u2192 NSDL Consolidated Account Statement\n cdsl.py \u2192 CDSL Consolidated Account Statement\n\n`read_cas_pdf` sniffs the issuer + statement variant from the PDF's\nfirst page, dispatches to the right parser, optionally sorts\ntransactions chronologically, and returns either `CASData` (CAMS/KFin)\nor `NSDLCASData` (NSDL/CDSL).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport io\nimport warnings\nfrom typing import Union\n\nfrom casparser.enums import CASFileType, FileType\nfrom casparser.exceptions import CASParseError\nfrom casparser.types import CASData, NSDLCASData\n\nfrom .detect import _open_document, detect_cas_type, detect_file_type\nfrom .utils import cas2csv, cas2json\n\n\ndef _sort_transactions(data: CASData) -> CASData:\n \"\"\"For each scheme, sort transactions by date and re-compute the\n running balance from the opening balance.\"\"\"\n for folio in data.folios:\n for idx, scheme in enumerate(folio.schemes):\n dates = [x.date for x in scheme.transactions]\n if dates == sorted(dates):\n continue\n sorted_txns = []\n balance = scheme.open\n for txn in sorted(scheme.transactions, key=lambda x: x.date):\n balance += txn.units or 0\n txn.balance = balance\n sorted_txns.append(txn)\n scheme.transactions = sorted_txns\n folio.schemes[idx] = scheme\n return data\n\n\ndef read_cas_pdf(\n filename: Union[str, io.IOBase],\n password: str,\n output: str = \"dict\",\n sort_transactions: bool = True,\n force_pdfminer: bool = False,\n):\n \"\"\"Parse a Consolidated Account Statement PDF.\n\n :param filename: path to the CAS PDF (or an open file-like object).\n :param password: PDF password (most CAS PDFs are encrypted with the\n investor's PAN).\n :param output: `\"dict\"` (default) returns the typed model directly,\n `\"json\"` returns its JSON serialisation, `\"csv\"`\n returns a CSV string of transactions or holdings.\n :param sort_transactions: For CAMS / KFin DETAILED statements, sort\n each scheme's transactions by date and\n re-compute the running balance. Default\n `True`.\n :param force_pdfminer: **Deprecated.** v1.0 dropped pdfminer in\n favour of pypdfium2. Setting this to True\n emits a `DeprecationWarning` and is otherwise\n ignored.\n :return: `CASData` for CAMS/KFin issuers, `NSDLCASData` for\n NSDL/CDSL issuers, or a serialised form of either when\n `output` is `\"json\"` / `\"csv\"`.\n \"\"\"\n if force_pdfminer:\n warnings.warn(\n \"force_pdfminer is deprecated in casparser 1.0 \u2014 pdfminer \"\n \"is no longer a supported backend.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n # Open the PDF exactly once and thread it through the detect /\n # parser / investor extractor calls \u2014 every pypdfium2 open re-runs\n # the password decrypt + content-stream parse, so the savings on\n # multi-page detailed statements are significant.\n doc = _open_document(filename, password)\n\n file_type = detect_file_type(filename, password, _doc=doc)\n if file_type == FileType.UNKNOWN:\n raise CASParseError(\n \"Could not identify the CAS issuer. Supported issuers are \"\n \"CAMS, KFintech, NSDL, and CDSL.\"\n )\n\n if file_type in (FileType.CAMS, FileType.KFINTECH):\n cas_type = detect_cas_type(filename, password, _doc=doc)\n if cas_type == CASFileType.DETAILED:\n from . import cams_detailed\n\n data: Union[CASData, NSDLCASData] = cams_detailed.parse(\n filename,\n password,\n file_type=file_type,\n _doc=doc,\n )\n elif cas_type == CASFileType.SUMMARY:\n from . import cams_summary\n\n data = cams_summary.parse(\n filename,\n password,\n file_type=file_type,\n _doc=doc,\n )\n else:\n raise CASParseError(\n \"Could not identify whether this is a DETAILED or \" \"SUMMARY CAMS / KFin statement.\"\n )\n if sort_transactions and isinstance(data, CASData):\n data = _sort_transactions(data)\n elif file_type == FileType.NSDL:\n from . import nsdl\n\n data = nsdl.parse_nsdl(\n filename,\n password,\n file_type=FileType.NSDL,\n _doc=doc,\n )\n elif file_type == FileType.CDSL:\n from . import cdsl\n\n data = cdsl.parse_cdsl(\n filename,\n password,\n file_type=FileType.CDSL,\n _doc=doc,\n )\n else: # pragma: no cover \u2014 handled above\n raise CASParseError(f\"Unsupported file type: {file_type}\")\n\n if output == \"dict\":\n return data\n if output == \"csv\":\n return cas2csv(data)\n return cas2json(data)\n\n\n__all__ = [\"read_cas_pdf\"]\n\n```\n\n### casparser/parsers/cdsl.py\n```python\n\"\"\"Dedicated CDSL parser.\n\nLike `nsdl_parser`, this consumes structured `Block`/`Cell` data from\n`pageobj.extract_blocks` and emits an `NSDLCASData` directly \u2014 no\ndetour through PROD's `process_cdsl_text`.\n\nCDSL CAS layout (in document order; absolute page numbers vary by\nholding count):\n\n - **Cover + account roster** \u2014 investor address block followed by the\n \"Account Type / Account Details / ISINs / Value\" summary table that\n enumerates each demat account and the MF-folios pseudo-account.\n - **Per-MF-folio descriptive blocks** \u2014 AMC Name, Scheme Name,\n Folio No, KYC, ISIN/UCC/RTA, one block group per folio. No\n balances here.\n - **Per-account transaction sections + holdings tables** \u2014 each\n section starts with `DP Name : ... BO ID :\n `, followed by transactions, then a\n `HOLDING STATEMENT AS ON` header and the holdings table itself\n (9-10 cells per row).\n - **`MUTUAL FUND UNITS HELD AS ON` table** \u2014 one row per MF folio\n with full P&L (scheme name, ISIN, folio, ARN code, units, NAV,\n invested, current value, TER, commission, profit, return%).\n - **Notes / footer** at the end.\n\nSome CDSL PDFs ship with a heavy Hindi-font overlay that makes\nroughly half the table cells unreadable by content-stream extraction\n(PROD fails on them too). The atom-level overlay filter in\n`extract.py` recovers most of these; the remainder need a smarter\nfont-aware extractor and are out of scope here.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom decimal import Decimal, InvalidOperation\nfrom typing import Dict, List, Optional, Tuple\n\nfrom casparser.enums import FileType\nfrom casparser.types import (\n DematAccount,\n DematOwner,\n Equity,\n MutualFund,\n NSDLCASData,\n StatementPeriod,\n)\n\nfrom . import pageobj\nfrom ._investor import extract_nsdl_cdsl_investor\nfrom .pageobj import Block\n\n# --- patterns ---\n\nISIN_RE = re.compile(r\"^[A-Z]{2}[0-9A-Z]{9}\\d$\")\nINF_ISIN_RE = re.compile(r\"^INF[0-9A-Z]{8}\\d$\")\nINE_ISIN_RE = re.compile(r\"^IN[E9][0-9A-Z]{8}\\d$\")\n# CDSL sometimes drops the leading zero on fractional values (e.g. a\n# `0.196` unit balance prints as `.196`), so the integer part is\n# optional when a decimal part is present.\nNUMERIC_RE = re.compile(r\"^-?(?:[\\d,]+(?:\\.\\d+)?|\\.\\d+)$\")\n\nPERIOD_RE = re.compile(\n r\"(?:for\\s+the\\s+period\\s+from|statement\\s+for\\s+the\\s+period\\s+from)\\s+\"\n r\"(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\\s+to\\s+(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\",\n re.I,\n)\n\nDEMAT_TYPE_RE = re.compile(r\"^(CDSL|NSDL)\\s+Demat\\s+Account\\s*$\", re.I)\nPAN_RE = re.compile(r\"(.+?)\\s*\\(\\s*PAN\\s*:\\s*([^)]+?)\\s*\\)\", re.I)\n\n# Page-2 summary row carries `DP Id: Client Id : `\n# (whitespace around the colons varies).\nSUMMARY_DPC_RE = re.compile(\n r\"DP\\s*Id\\s*:\\s*(\\S+?)\\s+Client\\s*Id\\s*:\\s*(\\d+)\",\n re.I,\n)\n# Per-account holdings header: `DP Name : DP ID : \n# CLIENT ID : `.\nSECTION_DPC_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+DP\\s*ID\\s*:\\s*(\\S+)\\s+CLIENT\\s*ID\\s*:\\s*(\\S+)\",\n re.I | re.S,\n)\n# Transaction-page header: `DP Name : BO ID : <16-char id>`.\n# The id concatenates DP ID + Client ID, both 8 chars. CDSL DP IDs are\n# numeric, NSDL DP IDs start with `IN`, so the 16-char field can be all\n# digits (CDSL) or two letters + 14 digits (NSDL).\nSECTION_BOID_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+(?:BO\\s*ID|DPID)\\s*:\\s*([A-Z0-9]{16})\",\n re.I | re.S,\n)\n\n\n# --- decimal helpers ---\n\n\ndef _to_decimal(text) -> Decimal:\n if text is None:\n return Decimal(0)\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return Decimal(0)\n try:\n return Decimal(s)\n except InvalidOperation:\n return Decimal(0)\n\n\ndef _opt_decimal(text) -> Optional[Decimal]:\n if text is None:\n return None\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return None\n try:\n return Decimal(s)\n except InvalidOperation:\n return None\n\n\ndef _looks_numeric(text: str) -> bool:\n s = text.strip()\n if not s:\n return False\n return bool(NUMERIC_RE.match(s))\n\n\n# --- account key utilities ---\n\n\ndef _full_type(type_word: str) -> str:\n return f\"{type_word.upper()} Demat Account\"\n\n\ndef _account_key(type_word: str, dp_id: str, client_id: str) -> Tuple[str, str, str]:\n return (type_word.upper(), dp_id.strip(), client_id.strip())\n\n\ndef _split_bo_id(bo_id: str) -> Tuple[str, str, str]:\n \"\"\"16-char BO ID \u2192 `(type_word, dp_id, client_id)`.\n\n NSDL DP IDs start with `IN` (8 chars total), CDSL DP IDs are pure\n digits. Both followed by an 8-digit Client ID.\"\"\"\n if len(bo_id) != 16:\n return \"\", \"\", \"\"\n if bo_id[:2].upper() == \"IN\":\n return \"NSDL\", bo_id[:8], bo_id[8:]\n if bo_id.isdigit():\n return \"CDSL\", bo_id[:8], bo_id[8:]\n return \"\", \"\", \"\"\n\n\n# --- parser entry point ---\n\n\ndef parse_cdsl(\n pdf_path: str,\n password: str,\n file_type: FileType = FileType.CDSL,\n *,\n _doc=None,\n) -> NSDLCASData:\n atoms = pageobj.extract_atoms(pdf_path, password, _doc=_doc)\n blocks = pageobj.blocks_from_atoms(atoms)\n period = _find_period(blocks) or StatementPeriod(**{\"from\": \"\", \"to\": \"\"})\n\n # Phase 1: account roster from page 2 summary.\n accounts_by_key: Dict[Tuple[str, str, str], DematAccount] = {}\n ordered_accounts: List[DematAccount] = []\n mf_folios_account: Optional[DematAccount] = None\n pending_owners: List[DematOwner] = []\n\n for b in blocks:\n if b.page != 2:\n continue\n txt = b.text()\n ltxt = txt.lower()\n if \"in the single name of\" in ltxt or \"in the joint name\" in ltxt:\n pending_owners = []\n continue\n if PAN_RE.search(txt) and \"Mutual\" not in txt:\n for m in PAN_RE.finditer(txt):\n pending_owners.append(\n DematOwner(\n name=m.group(1).strip(),\n PAN=m.group(2).strip(),\n )\n )\n continue\n if _is_summary_demat_row(b):\n ac, key = _account_from_summary_row(b, pending_owners)\n if key not in accounts_by_key:\n accounts_by_key[key] = ac\n ordered_accounts.append(ac)\n continue\n if _is_summary_mf_folios_row(b):\n if mf_folios_account is None:\n mf_folios_account = _mf_folios_account_from_summary(b, pending_owners)\n ordered_accounts.append(mf_folios_account)\n continue\n\n # Phase 2: scheme-code \u2192 (ISIN, UCC, folio, name) map from the\n # descriptive MF blocks that follow the roster page. Their page\n # span depends on how many MF folios the investor holds; we\n # bound-scan from page 3 up to the start of the per-account\n # transaction section (detected via the `BO ID :` / `DPID :`\n # marker), and only consume blocks that match the descriptive\n # template (Scheme Name + Scheme Code + ISIN + UCC).\n scheme_meta: Dict[str, Dict[str, str]] = {}\n pending_scheme: Dict[str, str] = {}\n for b in blocks:\n if b.page < 3:\n continue\n if SECTION_BOID_RE.search(b.text()):\n break\n txt = b.text()\n if \"Scheme Name :\" in txt and \"Scheme Code :\" in txt:\n sm = re.search(\n r\"Scheme\\s*Name\\s*:\\s*(.+?)\\s+Scheme\\s*Code\\s*:\\s*(\\S+)\",\n txt,\n re.S,\n )\n if sm:\n pending_scheme = {\n \"scheme_name\": sm.group(1).replace(\"\\n\", \" \").strip(),\n \"scheme_code\": sm.group(2).strip(),\n }\n elif \"Folio No :\" in txt:\n fm = re.search(r\"Folio\\s*No\\s*:\\s*(\\S+)\", txt)\n if fm:\n pending_scheme[\"folio\"] = fm.group(1)\n elif \"ISIN :\" in txt and \"UCC\" in txt:\n im = re.search(r\"ISIN\\s*:\\s*(\\S+)\", txt)\n um = re.search(r\"UCC\\s*:\\s*([\\w/]+)?\", txt)\n if im and pending_scheme.get(\"scheme_code\"):\n pending_scheme[\"isin\"] = im.group(1)\n if um and um.group(1):\n pending_scheme[\"ucc\"] = um.group(1)\n scheme_meta[pending_scheme[\"scheme_code\"]] = dict(pending_scheme)\n pending_scheme = {}\n\n # Phase 3: walk all post-cover pages for holdings tables.\n # We skip pages 1-2 (cover + roster) because the roster lines\n # contain CDSL/NSDL identifiers that would otherwise look like\n # section headers; the dispatch logic below handles the rest.\n cur_account: Optional[DematAccount] = None\n cur_mode: Optional[str] = None # 'equities' | 'mf_holdings'\n\n for b in blocks:\n if b.page < 3:\n continue\n txt = b.text()\n ltxt = txt.lower()\n\n # Per-account section header \u2014 `DP Name : ... BO ID : ...`\n # or `DP Name : ... DPID : ...` (NSDL variant) form.\n m = SECTION_BOID_RE.search(txt)\n if m:\n broker = m.group(1).strip()\n bo_id = m.group(2)\n type_word, dp_id, client_id = _split_bo_id(bo_id)\n if type_word:\n ac_key = _account_key(type_word, dp_id, client_id)\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Or \"DP Name : ... DP ID : ... CLIENT ID : ...\"\n m = SECTION_DPC_RE.search(txt)\n if m:\n type_word = \"CDSL\"\n if \"NSDL\" in txt.upper() and \"CDSL\" not in txt.upper():\n type_word = \"NSDL\"\n broker, dp_id, client_id = m.groups()\n ac_key = _account_key(type_word, dp_id.strip(), client_id.strip())\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Transaction-statement section \u2014 switch OFF holdings mode so\n # transaction rows aren't parsed as equity rows.\n if \"statement of transactions\" in ltxt:\n cur_mode = None\n continue\n\n # Holdings section markers\n if \"holding statement\" in ltxt and \"as on\" in ltxt:\n cur_mode = \"equities\"\n continue\n if \"mutual fund units held as on\" in ltxt:\n cur_account = mf_folios_account\n cur_mode = \"mf_holdings\"\n continue\n\n # Skip column-header rows\n if _is_holdings_header(b) or _is_total_row(b):\n continue\n\n # Holdings rows\n if cur_account is None or cur_mode is None:\n continue\n if cur_mode == \"equities\":\n row = _parse_holdings_row(b)\n if row is None:\n pass\n else:\n isin, name, num_shares, price, value = row\n # CDSL Demat statements list ETFs (ISIN starting with\n # INF) in the same holdings table as equities, but\n # they're semantically mutual-fund units. Route them\n # to the mutual_funds list to mirror PROD's\n # classification.\n if INF_ISIN_RE.match(isin):\n cur_account.mutual_funds.append(\n MutualFund(\n name=name,\n isin=isin,\n balance=num_shares,\n nav=price,\n value=value,\n )\n )\n else:\n cur_account.equities.append(\n Equity(\n name=name,\n isin=isin,\n num_shares=num_shares,\n price=price,\n value=value,\n )\n )\n elif cur_mode == \"mf_holdings\":\n mf = _parse_mf_holdings_row(b, scheme_meta)\n if mf:\n cur_account.mutual_funds.append(mf)\n\n return NSDLCASData(\n statement_period=period,\n accounts=ordered_accounts,\n investor_info=extract_nsdl_cdsl_investor(\n pdf_path,\n password,\n _atoms=atoms,\n ),\n file_type=file_type,\n )\n\n\n# --- summary-row recognisers (page 2) ---\n\n\ndef _is_summary_demat_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n if not DEMAT_TYPE_RE.match(block.cells[0].text.strip()):\n return False\n return bool(SUMMARY_DPC_RE.search(block.cells[1].text))\n\n\ndef _is_summary_mf_folios_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n return bool(re.match(r\"^Mutual\\s+Fund\\s+Folios\", block.cells[0].text.strip(), re.I))\n\n\ndef _account_from_summary_row(\n block: Block, owners: List[DematOwner]\n) -> Tuple[DematAccount, Tuple[str, str, str]]:\n type_word = DEMAT_TYPE_RE.match(block.cells[0].text.strip()).group(1).upper()\n broker_dp = block.cells[1].text\n lines = [ln.strip() for ln in broker_dp.split(\"\\n\") if ln.strip()]\n broker = lines[0] if lines else \"\"\n dpc = SUMMARY_DPC_RE.search(broker_dp)\n dp_id = dpc.group(1) if dpc else \"\"\n client_id = dpc.group(2) if dpc else \"\"\n folios = int(_to_decimal(block.cells[2].text))\n balance = _to_decimal(block.cells[3].text)\n ac = DematAccount(\n name=broker,\n type=_full_type(type_word),\n dp_id=dp_id,\n client_id=client_id,\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n return ac, _account_key(type_word, dp_id, client_id)\n\n\ndef _mf_folios_account_from_summary(block: Block, owners: List[DematOwner]) -> DematAccount:\n folios_m = re.search(r\"(\\d+)\", block.cells[1].text)\n folios = int(folios_m.group(1)) if folios_m else 0\n balance = _to_decimal(block.cells[3].text)\n return DematAccount(\n name=\"Mutual Fund Folios\",\n type=\"Mutual Fund Folios\",\n dp_id=\"\",\n client_id=\"\",\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n\n\n# --- helpers ---\n\n\ndef _find_period(blocks: List[Block]) -> Optional[StatementPeriod]:\n for b in blocks:\n m = PERIOD_RE.search(b.text())\n if m:\n return StatementPeriod(**{\"from\": m.group(1), \"to\": m.group(2)})\n return None\n\n\ndef _is_holdings_header(block: Block) -> bool:\n \"\"\"Block has no ISIN and looks like a column-label row.\"\"\"\n txt = block.text()\n if re.search(r\"\\b(IN[EF9][0-9A-Z]{8}\\d)\\b\", txt, re.I):\n return False\n ltxt = txt.lower().replace(\"\\n\", \" \").replace(\"\\t\\t\", \" \")\n if \"isin\" in ltxt and (\"security\" in ltxt or \"scheme name\" in ltxt):\n return True\n if \"current\" in ltxt and \"bal\" in ltxt and \"market\" in ltxt:\n return True\n return False\n\n\ndef _is_total_row(block: Block) -> bool:\n first = block.cells[0].text.strip().lower() if block.cells else \"\"\n return first in (\"sub total\", \"total\", \"grand total\")\n\n\n# --- equity holdings row ---\n\n\ndef _parse_holdings_row(block: Block) -> Optional[Tuple[str, str, Decimal, Decimal, Decimal]]:\n \"\"\"CDSL holdings row \u2192 `(isin, name, num_shares, price, value)`.\n\n Column layout (post-`HOLDING STATEMENT`):\n ISIN | Security | Current Bal | Frozen Bal | Pledge Bal |\n Pledge Setup Bal | Free Bal | Market Price | Value (`)\n\n A few rows have a leading '@' marker cell between ISIN and name\n (suspended issue notation). Rows with all-`--` quantity cells\n (rights entitlements that haven't been exercised) are still\n parsed \u2014 `_to_decimal` maps `--` to 0. We use position-based\n assignment, not the last-three-numerics heuristic, because some\n rows have only 2 numeric cells (price + value) when all balance\n columns are `--`.\"\"\"\n if not block.cells:\n return None\n first = block.cells[0].text.strip()\n if not ISIN_RE.match(first):\n return None\n isin = first\n\n \n... [truncated 4662 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-220edcfd7a16", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-220edcfd7a16", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "789865de12b2162a72cb44a98268de713ab4163e", "source_files": ["casparser/parsers/__init__.py", "casparser/parsers/cdsl.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** STP is not classified as a switch across RTAs\n\n## Description\nWhen STP (Spanning Tree Protocol) is present, the system fails to classify it as a switch. This misclassification occurs consistently across both RTAs.\nExpected behavior: STP should be correctly identified and classified as a switch.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `8dcabe8aeec4` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 1.2.0\n\n### New\n\n- **Gift (inter-folio transfer) transactions.** Adds `GIFT_IN` / `GIFT_OUT`\n transaction types, classified on the `\"gift\"` keyword together with the units\n sign. Closes #134.\n- **`TransactionData.gift_folio`.** Carries the counterparty folio named in a\n gift row's description, so a donor's statement can be linked to the donee's\n across two CAS files. `None` for all other transaction types.\n\n### Fixed\n\n- Gift row mistaken for a folio boundary.\n\n## 1.1.0\n\n### New\n\n- **`CASData.parse_warnings`.** The CAMS/KFin DETAILED parser now reconciles each\n scheme's transactions against its printed running `Unit Balance` column \u2014 the\n statement's own checksum \u2014 and records a non-fatal warning on any\n discontinuity (`prev_balance + units != printed balance`) or closing-balance\n mismatch. A non-empty list means a transaction row was likely dropped or\n mis-parsed; the parse still returns, but that scheme's data should not be\n trusted blindly. The region-based header parser additionally warns when a\n scheme-header region is discarded without its `Opening Unit Balance` anchor\n (folio/AMC boundary, end of document, or an unparseable header) \u2014 previously\n such a scheme and all its transactions vanished silently. Warnings are printed\n by the CLI after a successful parse.\n- **JSON Schemas for the output models.** `schema/CASData.schema.json` and\n `schema/NSDLCASData.schema.json` are generated from the Pydantic models\n (`scripts/generate_schema.py`); the README shape documentation was reworked\n around them.\n\n### Fixed\n\n- **Dividend reinvest misclassification.** `DIVIDEND_RE` carried an inline\n `(reinvest)*` group inside two lazy quantifiers that never backtracked to\n capture, so `\"Reinvestment of IDCW @ Rs\u2026\"` and `\"IDCW - Reinvest @ Rs\u2026\"` were\n classified as `DIVIDEND_PAYOUT`. Reinvest is now detected with a separate\n substring search.\n- **Folio collisions across AMCs.** Folios were keyed by folio number alone, but\n folio numbers are RTA-scoped, not globally unique \u2014 two AMCs sharing one\n silently merged the second AMC's schemes into the first's folio. Now keyed by\n `(amc, folio_no)`.\n- **Advisor-wrap header mis-parsed as a bogus `ARN` scheme.** A wrapped\n `(Advisor: ARN-xxxxx)` continuation line could anchor a spurious scheme whose\n RTA code parsed as `ARN`, splitting one holding into an empty stub plus a\n mis-coded duplicate.\n\n### Changed\n\n- **Scheme-header parsing rewritten as anchor-delimited regions.** The CAMS/KFin\n DETAILED parser no longer stitches headers by line-local proximity\n (`Y_BAND` / `consumed_below` lookahead). It accumulates the lines between the\n folio line (or the previous scheme's footer) and the next `Opening Unit\n Balance` into one region and parses fields from it once \u2014 bounded by the\n document's reliable single-line anchors, so it tolerates arbitrary header wrap\n distance and stitches headers across page breaks (which the old code could\n not). Output is compatible with 1.0.1; the only changes on the private corpus\n are cleaner scheme names (interleaved-ISIN IDCW names keep their\n `Payout` / `Reinvest` qualifier; leaked advisor / ISIN fragments are removed).\n\n## 1.0.1\n\n### New\n\n- **Demat equity holdings now carry `symbol` + `exchange`.** NSDL/CDSL\n statements identify an equity by ISIN only, so `Equity` rows used to lack an\n exchange trading ticker. The NSE symbol + exchange are now backfilled from the\n ISIN database after parsing (`parsers._isin.batch_equity_symbols`,\n `_enrich_demat_equities`), mirroring the existing MF `amfi` / `type`\n enrichment \u2014 so a demat holding identified only by ISIN can be priced via a\n symbol-keyed feed. Unresolvable ISINs stay `None`. Requires\n `casparser-isin>=2026.6.9` (ships the symbol columns + `ISINDb.batch_isin_lookup`).\n\n## 1.0.0\n\nMajor release. The parsing backend was rewritten from scratch on\n[pypdfium2](https://github.com/pypdfium2-team/pypdfium2) (Apache-2.0 /\nBSD-3) and the four supported CAS issuers now each have a dedicated\nparser tuned to their template family.\n\n### Breaking changes\n\n- **pdfminer.six and PyMuPDF backends removed.** `casparser.read_cas_pdf`\n no longer dispatches between them. The `mupdf` / `fast` extras in\n `pyproject.toml` are gone. The `--force-pdfminer` CLI flag and the\n `force_pdfminer=` kwarg on `read_cas_pdf` are kept as no-ops; the\n kwarg emits a `DeprecationWarning` and is otherwise ignored.\n- **License simplified to pure MIT.** With the GPL/AGPL-licensed\n PyMuPDF dependency gone, the `licenses/` directory of GPL/AGPL\n copies has been removed. pypdfium2 is dual Apache-2.0 / BSD-3 and\n doesn't impose any copyleft obligation on users of casparser.\n- **Minimum Python is now 3.11.** 3.9 / 3.10 classifiers dropped from\n `pyproject.toml`.\n- **`CASData.investor_info` is now `Optional[InvestorInfo]`** (matches\n the `NSDLCASData.investor_info` shape that already existed). It is\n populated on every supported issuer, but consumers should still\n guard against the `None` case for unfamiliar templates.\n- **Internal `casparser.process` package removed.** The two helpers\n downstream code still imports from it are now at\n `casparser.parsers._classify` (`get_parsed_scheme_name`,\n `get_transaction_type`) and `casparser.parsers._isin` (`isin_search`).\n\n### New\n\n- **Demat MF holdings now carry `amfi` + `type`.** NSDL/CDSL statements\n identify a mutual-fund holding by ISIN only, so `MutualFund` rows used\n to lack the AMFI code and scheme type that RTA (CAMS/KFin) `Scheme`\n rows have. Both are now backfilled from the ISIN database in a single\n batched lookup after parsing (`parsers._isin.batch_isin_metadata`), so\n the same fund parsed from a depository CAS and an RTA CAS reconciles on\n `amfi` / `type` when imported together. Unresolvable ISINs stay `None`.\n- **First-class NSDL and CDSL parsers.** Drops the regex-on-text\n approach the 0.8 NSDL/CDSL code used; the new parsers consume\n structured `Block`/`Cell` records directly from `pypdfium2`. Several\n bugs the v0.8 NSDL/CDSL code shipped with are no longer in scope\n (misplaced-UCC-as-folio on NSDL MF Holdings, space-merged\n folio+units cells on CDSL, the silently-dropped NSDL HDFC\n subaccount on CDSL multi-account statements, `Optional[Decimal]`\n comma-strip miss in the `MutualFund` validator).\n- **CAMS / KFin 2026 templates supported** out of the box. The newer\n CAMS SUMMARY template added an ISIN column the v0.8 regex didn't\n match; v1.0 parses all rows. The newer KFin SUMMARY template emits\n zero-balance schemes with single-space-separated trio cells that\n the v0.8 regex required `\\t\\t` between; v1.0 picks them up too.\n- **AMC-header detection extended** to include the `Fund House`\n suffix. v0.8's regex only matched `Mutual Fund` / `MF` suffixes,\n so schemes from a few newer AMCs whose names end in `Fund House`\n ended up bucketed under the previous AMC.\n- **ISIN / AMFI enrichment has a direct-ISIN fallback** path via\n `MFISINDb.direct_isin_lookup` for the case where multi-line\n `Registrar:` rendering corrupts the RTA token.\n- **Schedule 112A column 1b** (\"Share/Unit Transferred\") is emitted\n for FY2024-25 onward, per the AY 2025-26 ITR utility template. The\n Finance (No. 2) Act 2024 split the equity-LTCG regime on\n 23-Jul-2024; the 112A CSV now flags each transfer `BE`/`AE` against\n that date and splits an after-31-Jan-2018-acquired fund into\n separate rows when it was sold on both sides of the cutoff. Older\n FYs keep the 14-column layout their utility expects.\n- **Cost Inflation Index extended to FY2025-26 (376)** and the\n FY2024-25 value corrected from `365` to the CBDT-notified `363`\n (the wrong value slightly mis-indexed debt-fund LTCG cost of\n acquisition for FY2024-25 sales).\n\n### Fixed\n\n- **CAMS SUMMARY `valuation.date` no longer mis-parses to year 201**\n (was a column-boundary bug \u2014 the NAVDate column treated as\n right-aligned with a 42pt width clipped the trailing year digit,\n then Pydantic mis-coerced the `01-Jan-201` string).\n- **CDSL multi-account statements** (5+ demat accounts on one PDF) are\n now parsed correctly. Earlier the page-3+ scan only kicked in from\n page 8, dropping holdings sections that landed on pages 4-7.\n- **CDSL MF holdings** rows with `DIRECT` (or any non-`ARN-XXXX`\n distribution-mode token) now correctly populate `pnl` and `return_`.\n- **Leading-dot decimals** (`.196`, `-.5`) are now recognised as\n numeric by the NSDL / CDSL cell classifier. CDSL occasionally\n drops the leading zero on sub-unit balances; under the old regex\n those cells were mis-bucketed as text, shifting the row layout\n and producing a silent `\u03a3holdings \u2260 balance` mismatch.\n- **KFin `... - Reversed` transaction rows** (e.g. the Franklin\n wound-up debt schemes' `Payment - Units Extinguished-Reversed`\n entries) had their units cell printed with cosmetic parentheses\n even though the semantic sign is the opposite of the original.\n A new running-balance cross-check in the CAMS / KFin DETAILED\n parser flips the sign (and matching amount) on any single-row\n mis-parse and reclassifies the transaction type via the\n positive-units branch of `get_transaction_type`. Acts as a\n self-validating safety net for the entire transaction stream,\n not just the Franklin case.\n- **Failed-SIP `Payment not received` rows** are now classified as\n `REVERSAL` instead of `REDEMPTION`. These carry negative units (the\n provisional purchase is being undone) with a correct sign, so the\n running-balance validator leaves them untouched \u2014 only the\n description keyword distinguishes them, and it was missing from the\n reversal pattern. Misclassifying them as redemptions injected a\n phantom capital-gains event into the gains analysis.\n- **Stamp-duty allocation on split lots.** When a single purchase\n lot is consumed across N disposals the `FIFOUnits.sell` re-queue\n carried the *full* original stamp duty on every remaining slice,\n so the proportional allocation re-claimed the same paid stamp\n on each disposal \u2014 total stamp claimed grew unboundedly with\n split depth. (Worked example: 300-unit lot with \u20b91.25 stamp,\n split 100/100/100 \u2192 total claimed \u20b92.29 vs \u20b91.25 paid, an 84%\n over-claim that further widens for deeper splits.) The lot is\n now re-queued with the *unallocated remainder* (`purchase_tax -\n stamp_duty`), so the invariant `\u03a3(stamp_claimed) == stamp_paid`\n holds exactly across any number of partial consumptions. Section\n 48 only permits deducting the stamp actually paid as a\n transfer expense, so the prior behaviour over-stated the\n deduction on Schedule 112A.\n- **Soft-hyphen-wrapped tokens in NSDL / CDSL holdings.** Some CAS\n generators insert a `U+00AD` soft hyphen at the point where a long\n token (notably a 12-char ISIN) wraps across two display lines, e.g.\n `INF179K01WN9`. The block/cell extractor now treats a trailing\n soft hyphen as a continuation marker (splicing the next fragment on\n with no separator) and strips any embedded soft hyphens, so the\n token is reconstructed intact. Previously the wrapped ISIN matched\n neither the anchored ISIN regex nor its leftover, and the holding\n was silently dropped. (Reconstruction works when the wrapped\n fragments fall in the same row block; ISINs split across blocks by\n a non-standard page scale are not covered.)\n\n## 0.9.1 - 2026-06-02\n- CDSL: parse holdings rows whose ISIN spans/wraps across multiple\n lines instead of silently dropping them (#129, thanks @mvineetmenon).\n- CDSL: parse stock holdings rows where a long security name wraps so\n the line no longer begins with the ISIN \u2014 these equities were\n previously skipped entirely (#132 / #133, thanks @mvineetmenon).\n- Classify failed-SIP `Payment not received` transactions as\n `REVERSAL` rather than `REDEMPTION`, so a reversed (unsettled)\n purchase no longer surfaces as a spurious redemption / capital-gains\n event (#131, thanks @rahulpatel135).\n- Allow `pytest` 9.x in the dev/test dependency range (#126).\n\n## 0.9.0 - 2026-05-22\n- Add support for CDSL statements\n- Drop support for Python 3.9 and 3.10; minimum supported version is now 3.11\n- Support PyMuPDF >= 1.25 (1.27.x tested). Older `<1.25` pin removed.\n- Bump `casparser-isin` to `>= 2026.5.1` (new DB format v2 with\n `sebi_category`/`last_seen` columns; ISIN-first lookup priority).\n- Relax other dependency pins (click, colorama, rich, pdfminer.six).\n- Fix `MutualFund.fix_float` pydantic validator so the aliased `return`\n field (Python attribute `return_`) also gets the comma-stripping\n treatment; previously NSDL MF folio rows with a return value of\n 1 lakh or more would fail Decimal validation.\n- Parser robustness fixes for PyMuPDF 1.25+ text extraction quirks\n (all superseded in 1.0.0 by the pypdfium2 rewrite, kept here for\n the historical record).\n\n## 0.8.1 - 2025-09-21\n- NSDL parser bug fixes\n\n## 0.8.0 - 2025-02-26\n- NSDL support: first version\n- various bug fixes\n\n## 0.7.4 - 2023-10-04\n- (fix) fix broken scheme names\n\n## 0.7.3 - 2023-09-26\n- (new) Add support for parsing nominee details (available in `Folio.nominees`)\n- (fix) fix empty PAN in certain cases\n\n## 0.7.2 - 2023-09-19\n- Bug fixes\n - Exclude short term capital gains (STCG) from 112A reports\n - Fix advisor code parsing\n\n# 0.7.1 - 2023-09-06\n- fix bug where long scheme names were getting truncated\n\n## 0.7.0 - 2023-09-03\n- update pydantic to v2\n\n## 0.6.1 - 2023-04-04\n- update CII data till FY2022-23\n- bug fixes\n\n## 0.6.0 - 2023-02-20\n- use pydantic models for better data validation\n\n## 0.5.5 - 2022-08-06\n- bug fix with MuPDF parser\n\n## 0.5.4 - 2022-02-01\n- bug fix in CAS summary statement parser\n\n## 0.5.3 - 2021-08-21\n- support for generating csv files for capital gains in 112A format for income tax filing\n- various bug fixes\n\n## 0.5.2 - 2021-08-11\n- fix crash while generating capital gains reports on dividend payout funds\n- rework capital gains algorithm\n- add `advisor` column in transactions csv\n- various bug fixes\n\n## 0.5.1 - 2021-07-21\n- gains: PnL report\n- support for migration of Franklin Templeton funds to CAMS RTA\n- various bug fixes\n\n## 0.5.0 - 2021-07-02\n- Support for calculating capital gains from detailed CAS statements\n- support for parsing Tax Deducted at Source (`TDS`) transactions\n\n## 0.4.8 - 2021-06-27\n- `REVERSAL` TransactionType to indicate reverted/rejected transactions\n- convert all enums to strEnums for better readability [(#35)](https://github.com/codereverser/casparser/pull/35)\n- fix issue with parsing multi-line transactions\n\n## 0.4.7 - 2021-06-01\n\n- Minor bug fixes in summary-statement parser.\n- cli now uses [rich](http://rich.readthedocs.io/) for console output.\n- Use poetry for dependency management and deployment.\n- **BREAKING CHANGE**: Table output choices have been removed.\n `-s/--summary` is a flag and doesn't accept any additional arguments.\n- Support for folios without PAN (#28).\n- add support for new style dividend transactions after IDCW renaming.\n- improved parser for transaction entries.\n\n## 0.4.6 - 2021-04-04\n\n- New `sort_transactions` option in `casparser.read_cas_pdf` (and `--sort` flag in CLI)\n to fix transactions (and balances) for schemes with non-chronological order.\n- support negative balances in transactions\n\n## 0.4.5 - 2021-03-20\n\n- Support for segregated portfolio transactions [ credits: [abhishekjain-qb](https://github.com/abhishekjain-qb) ]\n\n## 0.4.4 - 2021-02-07\n\n- CSV output fixes\n - better csv output format for summary CAS statements.\n - option to output only summary information for detailed statements\n (`-s fancy_grid -o output.csv`)\n\n## 0.4.3 - 2021-01-30\n\n- ISIN, AMFI code mapping for schemes (**beta**)\n\n## 0.4.2 - 2021-01-22\n\n- fixes unicode issues in windows\n- supports negative scheme balances\n- better scheme name parsing\n- fixes dividend transaction parsing\n\n\n## 0.4.1 - 2021-01-13\n\n- hotfix for parsing folios without KYC details\n\n## 0.4.0 - 2021-01-08\n\n- adds support for parsing summary statements from CAMS/KARVY (**beta**)\n- minor bug fixes in CSV file gen\n... [truncated 1748 chars]\n\n```\n\n### casparser/__init__.py\n```python\nfrom .analysis import CapitalGainsReport\nfrom .parsers import read_cas_pdf\nfrom .types import CASData\n\n__all__ = [\n \"read_cas_pdf\",\n \"__version__\",\n \"CASData\",\n \"CapitalGainsReport\",\n]\n\n__version__ = \"1.2.0\"\n\n```\n\n### casparser/parsers/_classify.py\n```python\n\"\"\"Classification helpers shared across the CAMS / KFin parsers.\n\nTwo pure utilities:\n\n- `get_transaction_type` maps a transaction description + signed units\n count to a `TransactionType` enum, also extracting the dividend rate\n for IDCW / dividend lines.\n- `get_parsed_scheme_name` normalises a raw scheme name (drops\n `(formerly ...)`, `(erstwhile ...)`, `(Demat ...)` trailers, collapses\n whitespace).\n\nThese are pulled out of the old `casparser.process.cas_detailed` module\nbecause the pypdfium2 DETAILED parser still needs them but the rest of\nthat module's text-rendering machinery is now gone.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom decimal import Decimal\nfrom typing import Optional, Tuple\n\nfrom casparser.enums import TransactionType\n\n# Matches an IDCW / dividend transaction description and captures the\n# per-unit rupee value. The \"reinvest\" hint is detected separately\n# (REINVEST_RE) rather than as an inline group: with a lazy `.*?` on\n# both sides of an optional group, the engine settles on the first\n# complete match and never backtracks to populate the group, so it only\n# captured \"reinvest\" when the word sat exactly where the minimal\n# expansion stopped. \"Reinvestment of IDCW @ Rs...\" and \"IDCW - Reinvest\n# @ Rs...\" both leaked through as PAYOUT. A plain substring search is\n# unambiguous.\nDIVIDEND_RE = re.compile(\n r\"(?:div\\.|dividend|idcw).*?@\\s*Rs\\.\\s*([\\d\\.]+)(?:\\s+per\\s+unit)?\",\n re.I | re.DOTALL,\n)\nREINVEST_RE = re.compile(r\"reinvest\", re.I)\n\n# Counterparty folio embedded in a gift transfer description. Both RTAs\n# name the other folio but punctuate differently \u2014 KFin uses a colon\n# (\"Folio No: 12345678901\"), CAMS a dot (\"Folio No.87654321\") \u2014 so accept\n# either separator. Used to link a donor's GIFT_OUT to the donee's GIFT_IN\n# across two CAS files.\nGIFT_FOLIO_RE = re.compile(r\"Folio\\s+No\\s*[:.]\\s*(\\d+)\", re.I)\n\n\ndef extract_gift_folio(description: str) -> Optional[str]:\n \"\"\"Return the counterparty folio number named in a gift description,\n or None if absent.\"\"\"\n if m := GIFT_FOLIO_RE.search(description or \"\"):\n return m.group(1)\n return None\n\n\ndef get_transaction_type(\n description: str, units: Optional[Decimal]\n) -> Tuple[TransactionType, Optional[Decimal]]:\n \"\"\"Classify a transaction by its description + units sign.\n\n Returns `(transaction_type, dividend_rate_or_None)`. The dividend\n rate is only set for IDCW / dividend transactions.\n \"\"\"\n dividend_rate: Optional[Decimal] = None\n description = description.lower()\n if div_match := DIVIDEND_RE.search(description):\n dividend_rate = Decimal(div_match.group(1))\n txn_type = (\n TransactionType.DIVIDEND_REINVEST\n if REINVEST_RE.search(description)\n else TransactionType.DIVIDEND_PAYOUT\n )\n elif units is None:\n if \"stt\" in description:\n txn_type = TransactionType.STT_TAX\n elif \"stamp\" in description:\n txn_type = TransactionType.STAMP_DUTY_TAX\n elif \"tds\" in description:\n txn_type = TransactionType.TDS_TAX\n else:\n txn_type = TransactionType.MISC\n elif units > 0:\n if \"gift\" in description:\n txn_type = TransactionType.GIFT_IN\n elif \"switch\" in description:\n txn_type = (\n TransactionType.SWITCH_IN_MERGER\n if \"merger\" in description\n else TransactionType.SWITCH_IN\n )\n elif \"segregat\" in description:\n txn_type = TransactionType.SEGREGATION\n elif (\n \"sip\" in description\n or \"systematic\" in description\n or re.search(r\"instal+ment\", description, re.I)\n or re.search(r\"sys.+?invest\", description, re.I | re.DOTALL)\n ):\n txn_type = TransactionType.PURCHASE_SIP\n else:\n txn_type = TransactionType.PURCHASE\n elif units < 0:\n if \"gift\" in description:\n txn_type = TransactionType.GIFT_OUT\n elif re.search(\n r\"reversal|rejection|dishonoured|mismatch|insufficient\\s+balance|\"\n r\"payment\\s+not\\s+received\",\n description,\n re.I,\n ):\n txn_type = TransactionType.REVERSAL\n elif \"switch\" in description:\n txn_type = (\n TransactionType.SWITCH_OUT_MERGER\n if \"merger\" in description\n else TransactionType.SWITCH_OUT\n )\n else:\n txn_type = TransactionType.REDEMPTION\n else:\n txn_type = TransactionType.UNKNOWN\n\n return txn_type, dividend_rate\n\n\ndef get_parsed_scheme_name(scheme: str) -> str:\n \"\"\"Strip `(formerly ...)`, `(erstwhile ...)`, `(Demat ...)`,\n `(Non-Demat ...)` trailers; collapse whitespace; trim trailing\n punctuation.\"\"\"\n scheme = re.sub(\n r\"\\((formerly|erstwhile).+?\\)\",\n \"\",\n scheme,\n flags=re.I | re.DOTALL,\n ).strip()\n scheme = re.sub(\n r\"\\((Demat|Non-Demat).*\",\n \"\",\n scheme,\n flags=re.I | re.DOTALL,\n ).strip()\n scheme = re.sub(r\"\\s+\", \" \", scheme).strip()\n return re.sub(r\"[^a-zA-Z0-9_)]+$\", \"\", scheme).strip()\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-4ea50eaa50de", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-4ea50eaa50de", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "8dcabe8aeec49304e32a513c551ff1256163b3c4", "source_files": ["CHANGELOG.md", "casparser/__init__.py", "casparser/parsers/_classify.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** JSON export fails with PydanticSerializationUnexpectedValue for reclassified transactions\n\n## Description\nWhen transactions are reclassified, the `TransactionType` field incorrectly stores a string representation of the enum rather than the enum object itself. This leads to a `PydanticSerializationUnexpectedValue` error when attempting to export data to JSON, particularly for merged descriptions. The expected behavior is for the `TransactionType` field to consistently hold the correct enum value, allowing JSON export to complete successfully without errors after reclassification.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `96ce8cdb5561` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### casparser/parsers/cams_detailed.py\n```python\n\"\"\"CAMS / KFin DETAILED CAS parser using column-based row reading.\n\nReads each page's transaction table by detecting column boundaries and\nassigning cells per row, producing the `CASData` shape returned by\n`casparser.read_cas_pdf`.\n\nHandles:\n- Multi-page, multi-AMC statements with one folio/scheme header per block\n- Transaction table with the 6 standard columns (Date / Transaction /\n Amount / Units / Price / Unit Balance)\n- Multi-line transaction descriptions: a wrapped continuation line (all\n text in the Transaction column, directly below its row) is appended to\n the previous transaction's description and the row is re-classified on\n the merged text (issue #118)\n- Informational marker rows (`***Registration of Nominee***`, address/KYC\n updates, Transmission restatements) \u2014 dated rows with no amount and no\n units \u2014 are emitted as `MISC` transactions with `amount`/`units` None\n (issue #118)\n- \"Opening Unit Balance\", \"Closing Unit Balance\", \"NAV on\", \"Valuation on\"\n labeled rows\n- ISIN / AMFI enrichment (via `_isin.isin_search`), nominees, Total Cost\n Value, and investor info / statement period\n\nKnown limitations:\n- Segregated portfolios are classified as `SEGREGATION` transactions but\n are not fully supported by the capital-gains module.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom dataclasses import dataclass\nfrom decimal import Decimal\nfrom typing import List, Optional\n\nfrom dateutil import parser as dateparse\n\nfrom casparser.enums import CASFileType, FileType, TransactionType\nfrom casparser.types import (\n CASData,\n Folio,\n Scheme,\n SchemeValuation,\n StatementPeriod,\n TransactionData,\n)\n\nfrom ._classify import (\n extract_gift_folio,\n get_parsed_scheme_name,\n get_transaction_type,\n)\nfrom ._investor import extract_cams_kfin_investor\nfrom ._isin import isin_search\nfrom .extract import Char, Line, extract_pages\n\n# -----------------------------------------------------------------------------\n# Column anchors\n# -----------------------------------------------------------------------------\n\n# CAMS DETAILED transaction table. The header is two physical rows in the\n# PDF: \"Date Transaction Amount Units Price Unit\" on top, \"(INR) (INR)\n# Balance\" below. We require \u22654 of these labels on one line.\nTXN_HEADER_LABELS = {\"Date\", \"Transaction\", \"Amount\", \"Units\", \"Price\", \"Unit\", \"Balance\", \"NAV\"}\nTXN_MIN_HITS = 4\n\n# All numeric columns are right-aligned; Date and Transaction are left-aligned.\nALIGN = {\n \"Date\": \"left\",\n \"Transaction\": \"left\",\n \"Amount\": \"right\",\n \"Units\": \"right\",\n \"Price\": \"right\",\n \"Unit Balance\": \"right\",\n \"NAV\": \"right\",\n}\n\n\n@dataclass\nclass Column:\n label: str\n x_lo: float # range covering header label width\n x_hi: float\n alignment: str # 'left' | 'right'\n\n @property\n def x_anchor(self) -> float:\n \"\"\"For right-aligned columns, x_hi is the snap target; for left,\n x_lo is.\"\"\"\n return self.x_hi if self.alignment == \"right\" else self.x_lo\n\n\ndef _words_on_line(line: Line, min_gap: float = 1.5) -> List[tuple[str, float, float]]:\n \"\"\"Return [(text, x0, x1)] words on a line, splitting on x-gap > min_gap.\"\"\"\n cs = sorted(line.chars, key=lambda c: c.x0)\n words = []\n cur, cur_x0, cur_x1 = \"\", None, None\n for c in cs:\n if cur and (c.x0 - cur_x1) > min_gap:\n words.append((cur, cur_x0, cur_x1))\n cur = \"\"\n if not cur:\n cur_x0 = c.x0\n cur += c.text\n cur_x1 = c.x1\n if cur:\n words.append((cur, cur_x0, cur_x1))\n return words\n\n\nHEADER_WINDOW_Y = 15.0 # vertical span (pts) that constitutes one logical\n# header block. CAMS uses 2 baselines spanning ~10pt; KFin uses 4 baselines\n# spanning ~11pt (Amount/Price at top, Unit, Date/Transaction/Units, (INR)\n# /(INR)/Balance at bottom).\n\n\ndef detect_txn_columns(\n lines: List[Line], start_idx: int\n) -> Optional[tuple[int, int, List[Column]]]:\n \"\"\"Find the next transaction-table header at or after start_idx.\n\n A header is a y-window of consecutive lines (top-down) spanning \u2264 HEADER_\n WINDOW_Y points and collectively containing \u2265 TXN_MIN_HITS distinct\n column labels. We collect labels from the whole window so wraps like\n \"Unit\"/\"Balance\" stacked over 2 baselines or KFin's 4-baseline split\n behave the same.\n\n Returns (first_line_index, last_line_index, ordered columns) for the\n header window. Transaction parsing should start at last_line_index + 1;\n the [first, last] span is excluded from the scheme-header region buffer.\n \"\"\"\n for i in range(start_idx, len(lines)):\n window = [lines[i]]\n for j in range(i + 1, len(lines)):\n if lines[i].baseline - lines[j].baseline > HEADER_WINDOW_Y:\n break\n window.append(lines[j])\n\n all_words: List[tuple[str, float, float]] = []\n for line in window:\n all_words.extend(_words_on_line(line))\n labels = {w[0] for w in all_words if w[0] in TXN_HEADER_LABELS}\n if len(labels) < TXN_MIN_HITS:\n continue\n last_idx = i + len(window) - 1\n return i, last_idx, _build_columns(all_words)\n return None\n\n\ndef _build_columns(words: List[tuple[str, float, float]]) -> List[Column]:\n \"\"\"Map header words to Columns. Merge \"Unit\"+\"Balance\" into one column.\"\"\"\n cols: List[Column] = []\n for text, x0, x1 in words:\n if text == \"Unit\" and (\"Balance\" in (w[0] for w in words)):\n # Find \"Balance\" with overlapping x-range\n for w_text, w_x0, w_x1 in words:\n if w_text == \"Balance\" and abs((w_x0 + w_x1) / 2 - (x0 + x1) / 2) < 30:\n cols.append(Column(\"Unit Balance\", min(x0, w_x0), max(x1, w_x1), \"right\"))\n break\n elif text in ALIGN and text not in (\"Unit\", \"Balance\"):\n cols.append(Column(text, x0, x1, ALIGN[text]))\n cols.sort(key=lambda c: c.x_lo)\n return cols\n\n\nNUMERIC_ZONE_WIDTH = 55.0 # pts; right-aligned numeric values sit within\n# this width to the left of the column's x_hi. Wide enough for any common\n# Indian-format amount (e.g. \"1,23,45,678.90\") but narrow enough to exclude\n# wrapped description text that bleeds in from the left.\n\n\ndef _column_ranges(columns: List[Column]) -> List[tuple[Column, float, float]]:\n \"\"\"Compute x-range per column. Right-aligned numeric columns get a\n fixed-width zone ending at x_hi. Left-aligned columns extend from x_lo to\n the start of the next column's zone.\n\n The fundamental asymmetry: description text (Transaction column) is wide\n and naturally extends into the Amount column's x-space, while the actual\n amount value is in a narrow zone right-aligned to x_hi. Hence numeric\n columns are bounded by content-width, not by midpoint to neighbors.\n \"\"\"\n sorted_cols = sorted(columns, key=lambda c: (c.x_lo + c.x_hi) / 2)\n ranges: List[tuple[Column, float, float]] = []\n for i, col in enumerate(sorted_cols):\n if col.alignment == \"right\":\n lo = col.x_hi - NUMERIC_ZONE_WIDTH\n hi = col.x_hi + 3.0\n else:\n lo = col.x_lo - 3.0\n if i + 1 < len(sorted_cols):\n nxt = sorted_cols[i + 1]\n hi = nxt.x_hi - NUMERIC_ZONE_WIDTH if nxt.alignment == \"right\" else nxt.x_lo - 3.0\n else:\n hi = float(\"inf\")\n ranges.append((col, lo, hi))\n return ranges\n\n\ndef assign_cells(line: Line, columns: List[Column]) -> dict[str, str]:\n \"\"\"Bucket each char into a column by x-midpoint, then render each cell\n text in left-to-right order. Overlay duplicates are already filtered\n upstream by ``extract.extract_pages`` at the atom level.\"\"\"\n ranges = _column_ranges(columns)\n cells: dict[str, list[Char]] = {c.label: [] for c in columns}\n for ch in line.chars:\n x_mid = (ch.x0 + ch.x1) / 2\n for col, lo, hi in ranges:\n if lo <= x_mid < hi:\n cells[col.label].append(ch)\n break\n out = {}\n for label, chars in cells.items():\n if not chars:\n continue\n chars.sort(key=lambda c: c.x0)\n heights = sorted(c.h for c in chars)\n h_med = heights[len(heights) // 2]\n gap = max(1.5, 0.6 * h_med)\n parts, prev_x1 = [], None\n for c in chars:\n if prev_x1 is not None and (c.x0 - prev_x1) > gap:\n parts.append(\" \")\n parts.append(c.text)\n prev_x1 = c.x1\n out[label] = \"\".join(parts).strip()\n return out\n\n\n# -----------------------------------------------------------------------------\n# Label parsers (folio/scheme/labeled rows)\n# -----------------------------------------------------------------------------\n\nFOLIO_LINE_RE = re.compile(\n # Folio format: with optional \" / \" sub-account\n # suffix. Spaces around the slash are common in the source PDF.\n # Each of PAN / KYC / PAN-KYC is optional but when present\n # appears in this order on the same line. `.*?` lives *inside*\n # the optional group so a non-greedy match doesn't skip past it\n # and leave the capture empty.\n r\"Folio\\s+No\\s*:\\s*(\\d+(?:\\s*/\\s*\\d+)?)\"\n r\"(?:.*?PAN\\s*:\\s*([A-Z]{5}\\d{4}[A-Z]))?\"\n r\"(?:.*?KYC\\s*:\\s*(OK|NOT OK))?\"\n r\"(?:.*?PAN\\s*:\\s*(OK|NOT OK))?\",\n re.I,\n)\nINLINE_ISIN_RE = re.compile(r\"[-\\s]*ISIN\\s*:\\s*([A-Z0-9]+)\", re.I)\nINLINE_ADVISOR_RE = re.compile(r\"[-\\s]*\\(\\s*Advisor\\s*:\\s*([^)]+?)\\)\", re.I)\nSCHEME_HEAD_RTA_RE = re.compile(r\"Registrar\\s*:\\s*(\\S+)\", re.I)\n# A full MF ISIN is `INF` + 8 alphanumerics + 1 check digit (12 chars).\n# Used to reject a truncated ISIN (e.g. `INF769K`) that results when the\n# value wraps across the `Registrar :` label \u2014 passing a partial ISIN to\n# isin_search suppresses the name+code fallback and yields no ISIN.\nFULL_ISIN_RE = re.compile(r\"^INF[0-9A-Z]{8}\\d$\")\n# Same shape, unanchored \u2014 to find a complete ISIN anywhere in the\n# stitched header when the labelled \"ISIN: \" capture wraps.\nISIN_ANYWHERE_RE = re.compile(r\"\\bINF[0-9A-Z]{8}\\d\\b\")\n# Recognised registrar names. The RTA value is NOT reliably the first\n# token after `Registrar :` \u2014 some templates interleave `(Advisor: ...)`,\n# an ISIN-continuation fragment, or a rotated-watermark fragment between\n# the label and the real registrar name. We pick the recognised token\n# from the stitched scheme header instead.\nRTA_TOKEN_RE = re.compile(r\"\\b(CAMS|KFINTECH|KFIN|KARVY)\\b\", re.I)\nOPEN_BAL_RE = re.compile(r\"Opening\\s+Unit\\s+Balance\\s*:?\\s*([\\d,.]+)\", re.I)\nCLOSE_BAL_RE = re.compile(r\"Closing\\s+Unit\\s+Balance\\s*:?\\s*([\\d,.]+)\", re.I)\nNAV_RE = re.compile(r\"NAV\\s+on\\s+(\\d{2}-[A-Za-z]{3}-\\d{4})\\s*:\\s*INR\\s*([\\d,.]+)\", re.I)\nVALUATION_RE = re.compile(\n r\"(?:Valuation|Market\\s+Value)\\s+on\\s+(\\d{2}-[A-Za-z]{3}-\\d{4})\\s*:\\s*INR\\s*([\\d,.]+)\",\n re.I,\n)\nCOST_VALUE_RE = re.compile(r\"Total\\s+Cost\\s+Value\\s*:?\\s*([\\d,.]+)\", re.I)\n# Nominee block on the folio header. Three optional name slots; an\n# empty slot (\"Nominee 2: \") means no nominee at that position.\nNOMINEE_RE = re.compile(\n r\"Nominee\\s+1\\s*:\\s*(?P[^:]*?)\\s*(?:Nominee\\s+2\\s*:\\s*(?P[^:]*?)\\s*\"\n r\"(?:Nominee\\s+3\\s*:\\s*(?P.*?))?)?$\",\n re.I,\n)\nSTMT_PERIOD_RE = re.compile(\n r\"(\\d{2}-[A-Za-z]{3}-\\d{4})\\s+To\\s+(\\d{2}-[A-Za-z]{3}-\\d{4})\",\n re.I,\n)\n# AMC header line. Most issuers end in \"Mutual Fund\" or \"MF\"; a few\n# newer entrants use \" Fund House\" instead. We anchor on the\n# trailing suffix so disclaimer paragraphs that happen to mention an\n# AMC name mid-sentence don't get classified as section headers.\nAMC_RE = re.compile(\n r\"^(.+?\\s+(?:MF|Mutual\\s*Fund|Fund\\s*House))$\",\n re.I,\n)\n# Extract leading date pattern. Accept \"25-Oct-2021\", \"25 Oct 2021\",\n# \"25Oct2021\", etc. Dashes sometimes sit on a different baseline. The\n# regex anchors only at start so it survives stray trailing chars\n# (e.g. KFin's instalment number \"1\" leaking from the description column).\nDATE_CELL_RE = re.compile(r\"^\\s*(\\d{1,2}[-\\s]*[A-Za-z]{3}[-\\s]*\\d{4})\")\n\n# A transaction description too wide for the Transaction column wraps onto\n# its own physical line directly below the row (issue #118).\nCONTINUATION_MAX_GAP = 10.0\n\n\ndef _continuation_text(cells: dict[str, str]) -> Optional[str]:\n \"\"\"The description text of a wrapped-continuation line, or ``None``.\n\n A continuation has content in the Transaction column and nowhere else.\n Any glyph in Date or a numeric column means the line is something\n else (a dated row, a straddling footer fragment) \u2014 not a wrap.\n \"\"\"\n filled = [label for label, value in cells.items() if value.strip()]\n if filled != [\"Transaction\"]:\n return None\n return cells[\"Transaction\"].strip() or None\n\n\ndef _decimal(s: str) -> Optional[Decimal]:\n if s is None:\n return None\n s = s.strip()\n if not s:\n return None\n neg = s.startswith(\"(\") or s.startswith(\"-\")\n s = s.lstrip(\"(\").rstrip(\")\").lstrip(\"-\").replace(\",\", \"\")\n try:\n d = Decimal(s)\n return -d if neg else d\n except Exception:\n return None\n\n\n# -----------------------------------------------------------------------------\n# Running-balance sign validator\n# -----------------------------------------------------------------------------\n\n\ndef _apply_balance_sign_fix(scheme: Scheme) -> None:\n \"\"\"Cross-check parsed ``units`` against the per-row ``balance``\n column and flip the sign of single-row mis-parses.\n\n Some KFin templates print *Reversed* rows (e.g. the Franklin\n wound-up debt schemes' ``Payment - Units Extinguished-Reversed``\n entries) with cosmetic parentheses around the units value even\n though the semantic sign is the opposite of the original. The\n running ``Unit Balance`` column is unambiguous, so we trust it\n and flip the sign (plus the matching amount, which the same\n parens convention turned negative) on any row where\n ``prev_balance + units != balance`` but\n ``prev_balance - units == balance``. After flipping we\n reclassify the type via :func:`get_transaction_type`, so a\n flip from negative-to-positive moves the row out of the default\n ``REDEMPTION`` bucket into whichever positive bucket the\n description warrants.\n\n Rows without ``units`` (STT / Stamp / TDS / MISC) and rows\n without a parsed ``balance`` are skipped \u2014 they can't be\n cross-checked. The helper is a no-op for transactions whose\n signs already agree with the running balance, which covers the\n overwhelming majority of CAS data.\n \"\"\"\n tol = Decimal(\"0.005\")\n prev_balance: Optional[Decimal] = scheme.open if scheme.open is not None else Decimal(0)\n for t in scheme.transactions:\n if t.units is None or t.balance is None or prev_balance is None:\n continue\n units = Decimal(str(t.units))\n balance = Decimal(str(t.balance))\n if abs((prev_balance + units) - balance) <= tol:\n prev_balance = balance\n continue\n if abs((prev_balance - units) - balance) <= tol:\n flipped_units = -units\n t.units = flipped_units\n if t.amount is not None:\n t.amount = -Decimal(str(t.amount))\n new_type, new_div = get_transaction_type(t.description, flipped_units)\n t.type = new_type.name\n t.dividend_rate = new_div\n prev_balance = balance\n\n # Recompute the running close_calculated using the corrected\n # signs so downstream invariant assertions reflect the fix.\n total = scheme.open if scheme.open is not None else Decimal(0)\n for t in scheme.transactions:\n if t.units is not None:\n total += Decimal(str(t.units))\n scheme.close_calculated = total\n\n\ndef _reconcile_balances(scheme: Scheme) -> List[str]:\n \"\"\"Validate transactions against the printed running ``Unit Balance``.\n\n The statement carries its own checksum: every row prints the running\n unit balance *after* that transaction, so ``prev_balance + units``\n must equal the pri\n... [truncated 31108 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-b999d7308ca8", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-b999d7308ca8", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "96ce8cdb55614c2d62c9a9abb561c9a338698643", "source_files": ["casparser/parsers/cams_detailed.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** CDSL CAS: Mutual Fund holdings show incorrect (zero) current value for certain row formats\n\n## Description\nWhen parsing CDSL Consolidated Account Statements (CAS), some Mutual Fund holdings rows are incorrectly processed, leading to a reported current value of zero. This happens for a specific row variant where a distribution mode column (e.g., ARN/DIRECT) is present, but there is no separate \"invested / total cost\" column. In these cases, the row contains only three numeric columns: units, NAV, and current value.\n\n**Actual Behavior:** The current value for such holdings is parsed as 0, which also results in an incorrect (lower) total balance for the MF-Folios.\n**Expected Behavior:** The current value should be correctly extracted from the third numeric column in these specific rows, and the total MF-Folios balance should accurately reflect the sum of all holdings' current values.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `226c7d016abe` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### casparser/parsers/cdsl.py\n```python\n\"\"\"Dedicated CDSL parser.\n\nLike `nsdl_parser`, this consumes structured `Block`/`Cell` data from\n`pageobj.extract_blocks` and emits an `NSDLCASData` directly \u2014 no\ndetour through PROD's `process_cdsl_text`.\n\nCDSL CAS layout (in document order; absolute page numbers vary by\nholding count):\n\n - **Cover + account roster** \u2014 investor address block followed by the\n \"Account Type / Account Details / ISINs / Value\" summary table that\n enumerates each demat account and the MF-folios pseudo-account.\n - **Per-MF-folio descriptive blocks** \u2014 AMC Name, Scheme Name,\n Folio No, KYC, ISIN/UCC/RTA, one block group per folio. No\n balances here.\n - **Per-account transaction sections + holdings tables** \u2014 each\n section starts with `DP Name : ... BO ID :\n `, followed by transactions, then a\n `HOLDING STATEMENT AS ON` header and the holdings table itself\n (9-10 cells per row).\n - **`MUTUAL FUND UNITS HELD AS ON` table** \u2014 one row per MF folio\n with full P&L (scheme name, ISIN, folio, ARN code, units, NAV,\n invested, current value, TER, commission, profit, return%).\n - **Notes / footer** at the end.\n\nSome CDSL PDFs ship with a heavy Hindi-font overlay that makes\nroughly half the table cells unreadable by content-stream extraction\n(PROD fails on them too). The atom-level overlay filter in\n`extract.py` recovers most of these; the remainder need a smarter\nfont-aware extractor and are out of scope here.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom decimal import Decimal, InvalidOperation\nfrom typing import Dict, List, Optional, Tuple\n\nfrom casparser.enums import FileType\nfrom casparser.types import (\n DematAccount,\n DematOwner,\n Equity,\n MutualFund,\n NSDLCASData,\n StatementPeriod,\n)\n\nfrom . import pageobj\nfrom ._investor import extract_nsdl_cdsl_investor\nfrom .pageobj import Block\n\n# --- patterns ---\n\nISIN_RE = re.compile(r\"^[A-Z]{2}[0-9A-Z]{9}\\d$\")\nINF_ISIN_RE = re.compile(r\"^INF[0-9A-Z]{8}\\d$\")\nINE_ISIN_RE = re.compile(r\"^IN[E9][0-9A-Z]{8}\\d$\")\nNUMERIC_RE = re.compile(r\"^-?[\\d,]+(?:\\.\\d+)?$\")\n\nPERIOD_RE = re.compile(\n r\"(?:for\\s+the\\s+period\\s+from|statement\\s+for\\s+the\\s+period\\s+from)\\s+\"\n r\"(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\\s+to\\s+(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\",\n re.I,\n)\n\nDEMAT_TYPE_RE = re.compile(r\"^(CDSL|NSDL)\\s+Demat\\s+Account\\s*$\", re.I)\nPAN_RE = re.compile(r\"(.+?)\\s*\\(\\s*PAN\\s*:\\s*([^)]+?)\\s*\\)\", re.I)\n\n# Page-2 summary row carries `DP Id: Client Id : `\n# (whitespace around the colons varies).\nSUMMARY_DPC_RE = re.compile(\n r\"DP\\s*Id\\s*:\\s*(\\S+?)\\s+Client\\s*Id\\s*:\\s*(\\d+)\",\n re.I,\n)\n# Per-account holdings header: `DP Name : DP ID : \n# CLIENT ID : `.\nSECTION_DPC_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+DP\\s*ID\\s*:\\s*(\\S+)\\s+CLIENT\\s*ID\\s*:\\s*(\\S+)\",\n re.I | re.S,\n)\n# Transaction-page header: `DP Name : BO ID : <16-char id>`.\n# The id concatenates DP ID + Client ID, both 8 chars. CDSL DP IDs are\n# numeric, NSDL DP IDs start with `IN`, so the 16-char field can be all\n# digits (CDSL) or two letters + 14 digits (NSDL).\nSECTION_BOID_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+(?:BO\\s*ID|DPID)\\s*:\\s*([A-Z0-9]{16})\",\n re.I | re.S,\n)\n\n\n# --- decimal helpers ---\n\n\ndef _to_decimal(text) -> Decimal:\n if text is None:\n return Decimal(0)\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return Decimal(0)\n try:\n return Decimal(s)\n except InvalidOperation:\n return Decimal(0)\n\n\ndef _opt_decimal(text) -> Optional[Decimal]:\n if text is None:\n return None\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return None\n try:\n return Decimal(s)\n except InvalidOperation:\n return None\n\n\ndef _looks_numeric(text: str) -> bool:\n s = text.strip()\n if not s:\n return False\n return bool(NUMERIC_RE.match(s))\n\n\n# --- account key utilities ---\n\n\ndef _full_type(type_word: str) -> str:\n return f\"{type_word.upper()} Demat Account\"\n\n\ndef _account_key(type_word: str, dp_id: str, client_id: str) -> Tuple[str, str, str]:\n return (type_word.upper(), dp_id.strip(), client_id.strip())\n\n\ndef _split_bo_id(bo_id: str) -> Tuple[str, str, str]:\n \"\"\"16-char BO ID \u2192 `(type_word, dp_id, client_id)`.\n\n NSDL DP IDs start with `IN` (8 chars total), CDSL DP IDs are pure\n digits. Both followed by an 8-digit Client ID.\"\"\"\n if len(bo_id) != 16:\n return \"\", \"\", \"\"\n if bo_id[:2].upper() == \"IN\":\n return \"NSDL\", bo_id[:8], bo_id[8:]\n if bo_id.isdigit():\n return \"CDSL\", bo_id[:8], bo_id[8:]\n return \"\", \"\", \"\"\n\n\n# --- parser entry point ---\n\n\ndef parse_cdsl(\n pdf_path: str,\n password: str,\n file_type: FileType = FileType.CDSL,\n *,\n _doc=None,\n) -> NSDLCASData:\n atoms = pageobj.extract_atoms(pdf_path, password, _doc=_doc)\n blocks = pageobj.blocks_from_atoms(atoms)\n period = _find_period(blocks) or StatementPeriod(**{\"from\": \"\", \"to\": \"\"})\n\n # Phase 1: account roster from page 2 summary.\n accounts_by_key: Dict[Tuple[str, str, str], DematAccount] = {}\n ordered_accounts: List[DematAccount] = []\n mf_folios_account: Optional[DematAccount] = None\n pending_owners: List[DematOwner] = []\n\n for b in blocks:\n if b.page != 2:\n continue\n txt = b.text()\n ltxt = txt.lower()\n if \"in the single name of\" in ltxt or \"in the joint name\" in ltxt:\n pending_owners = []\n continue\n if PAN_RE.search(txt) and \"Mutual\" not in txt:\n for m in PAN_RE.finditer(txt):\n pending_owners.append(\n DematOwner(\n name=m.group(1).strip(),\n PAN=m.group(2).strip(),\n )\n )\n continue\n if _is_summary_demat_row(b):\n ac, key = _account_from_summary_row(b, pending_owners)\n if key not in accounts_by_key:\n accounts_by_key[key] = ac\n ordered_accounts.append(ac)\n continue\n if _is_summary_mf_folios_row(b):\n if mf_folios_account is None:\n mf_folios_account = _mf_folios_account_from_summary(b, pending_owners)\n ordered_accounts.append(mf_folios_account)\n continue\n\n # Phase 2: scheme-code \u2192 (ISIN, UCC, folio, name) map from the\n # descriptive MF blocks that follow the roster page. Their page\n # span depends on how many MF folios the investor holds; we\n # bound-scan from page 3 up to the start of the per-account\n # transaction section (detected via the `BO ID :` / `DPID :`\n # marker), and only consume blocks that match the descriptive\n # template (Scheme Name + Scheme Code + ISIN + UCC).\n scheme_meta: Dict[str, Dict[str, str]] = {}\n pending_scheme: Dict[str, str] = {}\n for b in blocks:\n if b.page < 3:\n continue\n if SECTION_BOID_RE.search(b.text()):\n break\n txt = b.text()\n if \"Scheme Name :\" in txt and \"Scheme Code :\" in txt:\n sm = re.search(\n r\"Scheme\\s*Name\\s*:\\s*(.+?)\\s+Scheme\\s*Code\\s*:\\s*(\\S+)\",\n txt,\n re.S,\n )\n if sm:\n pending_scheme = {\n \"scheme_name\": sm.group(1).replace(\"\\n\", \" \").strip(),\n \"scheme_code\": sm.group(2).strip(),\n }\n elif \"Folio No :\" in txt:\n fm = re.search(r\"Folio\\s*No\\s*:\\s*(\\S+)\", txt)\n if fm:\n pending_scheme[\"folio\"] = fm.group(1)\n elif \"ISIN :\" in txt and \"UCC\" in txt:\n im = re.search(r\"ISIN\\s*:\\s*(\\S+)\", txt)\n um = re.search(r\"UCC\\s*:\\s*([\\w/]+)?\", txt)\n if im and pending_scheme.get(\"scheme_code\"):\n pending_scheme[\"isin\"] = im.group(1)\n if um and um.group(1):\n pending_scheme[\"ucc\"] = um.group(1)\n scheme_meta[pending_scheme[\"scheme_code\"]] = dict(pending_scheme)\n pending_scheme = {}\n\n # Phase 3: walk all post-cover pages for holdings tables.\n # We skip pages 1-2 (cover + roster) because the roster lines\n # contain CDSL/NSDL identifiers that would otherwise look like\n # section headers; the dispatch logic below handles the rest.\n cur_account: Optional[DematAccount] = None\n cur_mode: Optional[str] = None # 'equities' | 'mf_holdings'\n\n for b in blocks:\n if b.page < 3:\n continue\n txt = b.text()\n ltxt = txt.lower()\n\n # Per-account section header \u2014 `DP Name : ... BO ID : ...`\n # or `DP Name : ... DPID : ...` (NSDL variant) form.\n m = SECTION_BOID_RE.search(txt)\n if m:\n broker = m.group(1).strip()\n bo_id = m.group(2)\n type_word, dp_id, client_id = _split_bo_id(bo_id)\n if type_word:\n ac_key = _account_key(type_word, dp_id, client_id)\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Or \"DP Name : ... DP ID : ... CLIENT ID : ...\"\n m = SECTION_DPC_RE.search(txt)\n if m:\n type_word = \"CDSL\"\n if \"NSDL\" in txt.upper() and \"CDSL\" not in txt.upper():\n type_word = \"NSDL\"\n broker, dp_id, client_id = m.groups()\n ac_key = _account_key(type_word, dp_id.strip(), client_id.strip())\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Transaction-statement section \u2014 switch OFF holdings mode so\n # transaction rows aren't parsed as equity rows.\n if \"statement of transactions\" in ltxt:\n cur_mode = None\n continue\n\n # Holdings section markers\n if \"holding statement\" in ltxt and \"as on\" in ltxt:\n cur_mode = \"equities\"\n continue\n if \"mutual fund units held as on\" in ltxt:\n cur_account = mf_folios_account\n cur_mode = \"mf_holdings\"\n continue\n\n # Skip column-header rows\n if _is_holdings_header(b) or _is_total_row(b):\n continue\n\n # Holdings rows\n if cur_account is None or cur_mode is None:\n continue\n if cur_mode == \"equities\":\n row = _parse_holdings_row(b)\n if row is None:\n pass\n else:\n isin, name, num_shares, price, value = row\n # CDSL Demat statements list ETFs (ISIN starting with\n # INF) in the same holdings table as equities, but\n # they're semantically mutual-fund units. Route them\n # to the mutual_funds list to mirror PROD's\n # classification.\n if INF_ISIN_RE.match(isin):\n cur_account.mutual_funds.append(\n MutualFund(\n name=name,\n isin=isin,\n balance=num_shares,\n nav=price,\n value=value,\n )\n )\n else:\n cur_account.equities.append(\n Equity(\n name=name,\n isin=isin,\n num_shares=num_shares,\n price=price,\n value=value,\n )\n )\n elif cur_mode == \"mf_holdings\":\n mf = _parse_mf_holdings_row(b, scheme_meta)\n if mf:\n cur_account.mutual_funds.append(mf)\n\n return NSDLCASData(\n statement_period=period,\n accounts=ordered_accounts,\n investor_info=extract_nsdl_cdsl_investor(\n pdf_path,\n password,\n _atoms=atoms,\n ),\n file_type=file_type,\n )\n\n\n# --- summary-row recognisers (page 2) ---\n\n\ndef _is_summary_demat_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n if not DEMAT_TYPE_RE.match(block.cells[0].text.strip()):\n return False\n return bool(SUMMARY_DPC_RE.search(block.cells[1].text))\n\n\ndef _is_summary_mf_folios_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n return bool(re.match(r\"^Mutual\\s+Fund\\s+Folios\", block.cells[0].text.strip(), re.I))\n\n\ndef _account_from_summary_row(\n block: Block, owners: List[DematOwner]\n) -> Tuple[DematAccount, Tuple[str, str, str]]:\n type_word = DEMAT_TYPE_RE.match(block.cells[0].text.strip()).group(1).upper()\n broker_dp = block.cells[1].text\n lines = [ln.strip() for ln in broker_dp.split(\"\\n\") if ln.strip()]\n broker = lines[0] if lines else \"\"\n dpc = SUMMARY_DPC_RE.search(broker_dp)\n dp_id = dpc.group(1) if dpc else \"\"\n client_id = dpc.group(2) if dpc else \"\"\n folios = int(_to_decimal(block.cells[2].text))\n balance = _to_decimal(block.cells[3].text)\n ac = DematAccount(\n name=broker,\n type=_full_type(type_word),\n dp_id=dp_id,\n client_id=client_id,\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n return ac, _account_key(type_word, dp_id, client_id)\n\n\ndef _mf_folios_account_from_summary(block: Block, owners: List[DematOwner]) -> DematAccount:\n folios_m = re.search(r\"(\\d+)\", block.cells[1].text)\n folios = int(folios_m.group(1)) if folios_m else 0\n balance = _to_decimal(block.cells[3].text)\n return DematAccount(\n name=\"Mutual Fund Folios\",\n type=\"Mutual Fund Folios\",\n dp_id=\"\",\n client_id=\"\",\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n\n\n# --- helpers ---\n\n\ndef _find_period(blocks: List[Block]) -> Optional[StatementPeriod]:\n for b in blocks:\n m = PERIOD_RE.search(b.text())\n if m:\n return StatementPeriod(**{\"from\": m.group(1), \"to\": m.group(2)})\n return None\n\n\ndef _is_holdings_header(block: Block) -> bool:\n \"\"\"Block has no ISIN and looks like a column-label row.\"\"\"\n txt = block.text()\n if re.search(r\"\\b(IN[EF9][0-9A-Z]{8}\\d)\\b\", txt, re.I):\n return False\n ltxt = txt.lower().replace(\"\\n\", \" \").replace(\"\\t\\t\", \" \")\n if \"isin\" in ltxt and (\"security\" in ltxt or \"scheme name\" in ltxt):\n return True\n if \"current\" in ltxt and \"bal\" in ltxt and \"market\" in ltxt:\n return True\n return False\n\n\ndef _is_total_row(block: Block) -> bool:\n first = block.cells[0].text.strip().lower() if block.cells else \"\"\n return first in (\"sub total\", \"total\", \"grand total\")\n\n\n# --- equity holdings row ---\n\n\ndef _parse_holdings_row(block: Block) -> Optional[Tuple[str, str, Decimal, Decimal, Decimal]]:\n \"\"\"CDSL holdings row \u2192 `(isin, name, num_shares, price, value)`.\n\n Column layout (post-`HOLDING STATEMENT`):\n ISIN | Security | Current Bal | Frozen Bal | Pledge Bal |\n Pledge Setup Bal | Free Bal | Market Price | Value (`)\n\n A few rows have a leading '@' marker cell between ISIN and name\n (suspended issue notation). Rows with all-`--` quantity cells\n (rights entitlements that haven't been exercised) are still\n parsed \u2014 `_to_decimal` maps `--` to 0. We use position-based\n assignment, not the last-three-numerics heuristic, because some\n rows have only 2 numeric cells (price + value) when all balance\n columns are `--`.\"\"\"\n if not block.cells:\n return None\n first = block.cells[0].text.strip()\n if not ISIN_RE.match(first):\n return None\n isin = first\n\n # Find the data-cell boundary: the first cell after ISIN whose\n # text is a number or `--`. Everything between ISIN and that cell\n # is part of the security name (PDF renderer somet\n... [truncated 3988 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-dc6b4bad9a9d", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-dc6b4bad9a9d", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "226c7d016abe8de403dadebff193ab360f678d28", "source_files": ["casparser/parsers/cdsl.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Incorrect Mutual Fund Profit/Return Calculation\n\n## Description\nWhen calculating the profit or return for Mutual Funds, the reported figures are inaccurate. The system currently calculates these values based on the position, which leads to incorrect financial outcomes. The expected behavior is for Mutual Fund profit/return to be accurately determined using the value-cost identity.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `ea95d2eee7e1` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 1.2.1\n\n### Fixed\n\n- Fix mis-classification of STP (Systematic Transfer Plan) for\n Kfintech-serviced schemes. (discussion #141)\n\n## 1.2.0\n\n### New\n\n- **Gift (inter-folio transfer) transactions.** Adds `GIFT_IN` / `GIFT_OUT`\n transaction types, classified on the `\"gift\"` keyword together with the units\n sign. Closes #134.\n- **`TransactionData.gift_folio`.** Carries the counterparty folio named in a\n gift row's description, so a donor's statement can be linked to the donee's\n across two CAS files. `None` for all other transaction types.\n\n### Fixed\n\n- Gift row mistaken for a folio boundary.\n\n## 1.1.0\n\n### New\n\n- **`CASData.parse_warnings`.** The CAMS/KFin DETAILED parser now reconciles each\n scheme's transactions against its printed running `Unit Balance` column \u2014 the\n statement's own checksum \u2014 and records a non-fatal warning on any\n discontinuity (`prev_balance + units != printed balance`) or closing-balance\n mismatch. A non-empty list means a transaction row was likely dropped or\n mis-parsed; the parse still returns, but that scheme's data should not be\n trusted blindly. The region-based header parser additionally warns when a\n scheme-header region is discarded without its `Opening Unit Balance` anchor\n (folio/AMC boundary, end of document, or an unparseable header) \u2014 previously\n such a scheme and all its transactions vanished silently. Warnings are printed\n by the CLI after a successful parse.\n- **JSON Schemas for the output models.** `schema/CASData.schema.json` and\n `schema/NSDLCASData.schema.json` are generated from the Pydantic models\n (`scripts/generate_schema.py`); the README shape documentation was reworked\n around them.\n\n### Fixed\n\n- **Dividend reinvest misclassification.** `DIVIDEND_RE` carried an inline\n `(reinvest)*` group inside two lazy quantifiers that never backtracked to\n capture, so `\"Reinvestment of IDCW @ Rs\u2026\"` and `\"IDCW - Reinvest @ Rs\u2026\"` were\n classified as `DIVIDEND_PAYOUT`. Reinvest is now detected with a separate\n substring search.\n- **Folio collisions across AMCs.** Folios were keyed by folio number alone, but\n folio numbers are RTA-scoped, not globally unique \u2014 two AMCs sharing one\n silently merged the second AMC's schemes into the first's folio. Now keyed by\n `(amc, folio_no)`.\n- **Advisor-wrap header mis-parsed as a bogus `ARN` scheme.** A wrapped\n `(Advisor: ARN-xxxxx)` continuation line could anchor a spurious scheme whose\n RTA code parsed as `ARN`, splitting one holding into an empty stub plus a\n mis-coded duplicate.\n\n### Changed\n\n- **Scheme-header parsing rewritten as anchor-delimited regions.** The CAMS/KFin\n DETAILED parser no longer stitches headers by line-local proximity\n (`Y_BAND` / `consumed_below` lookahead). It accumulates the lines between the\n folio line (or the previous scheme's footer) and the next `Opening Unit\n Balance` into one region and parses fields from it once \u2014 bounded by the\n document's reliable single-line anchors, so it tolerates arbitrary header wrap\n distance and stitches headers across page breaks (which the old code could\n not). Output is compatible with 1.0.1; the only changes on the private corpus\n are cleaner scheme names (interleaved-ISIN IDCW names keep their\n `Payout` / `Reinvest` qualifier; leaked advisor / ISIN fragments are removed).\n\n## 1.0.1\n\n### New\n\n- **Demat equity holdings now carry `symbol` + `exchange`.** NSDL/CDSL\n statements identify an equity by ISIN only, so `Equity` rows used to lack an\n exchange trading ticker. The NSE symbol + exchange are now backfilled from the\n ISIN database after parsing (`parsers._isin.batch_equity_symbols`,\n `_enrich_demat_equities`), mirroring the existing MF `amfi` / `type`\n enrichment \u2014 so a demat holding identified only by ISIN can be priced via a\n symbol-keyed feed. Unresolvable ISINs stay `None`. Requires\n `casparser-isin>=2026.6.9` (ships the symbol columns + `ISINDb.batch_isin_lookup`).\n\n## 1.0.0\n\nMajor release. The parsing backend was rewritten from scratch on\n[pypdfium2](https://github.com/pypdfium2-team/pypdfium2) (Apache-2.0 /\nBSD-3) and the four supported CAS issuers now each have a dedicated\nparser tuned to their template family.\n\n### Breaking changes\n\n- **pdfminer.six and PyMuPDF backends removed.** `casparser.read_cas_pdf`\n no longer dispatches between them. The `mupdf` / `fast` extras in\n `pyproject.toml` are gone. The `--force-pdfminer` CLI flag and the\n `force_pdfminer=` kwarg on `read_cas_pdf` are kept as no-ops; the\n kwarg emits a `DeprecationWarning` and is otherwise ignored.\n- **License simplified to pure MIT.** With the GPL/AGPL-licensed\n PyMuPDF dependency gone, the `licenses/` directory of GPL/AGPL\n copies has been removed. pypdfium2 is dual Apache-2.0 / BSD-3 and\n doesn't impose any copyleft obligation on users of casparser.\n- **Minimum Python is now 3.11.** 3.9 / 3.10 classifiers dropped from\n `pyproject.toml`.\n- **`CASData.investor_info` is now `Optional[InvestorInfo]`** (matches\n the `NSDLCASData.investor_info` shape that already existed). It is\n populated on every supported issuer, but consumers should still\n guard against the `None` case for unfamiliar templates.\n- **Internal `casparser.process` package removed.** The two helpers\n downstream code still imports from it are now at\n `casparser.parsers._classify` (`get_parsed_scheme_name`,\n `get_transaction_type`) and `casparser.parsers._isin` (`isin_search`).\n\n### New\n\n- **Demat MF holdings now carry `amfi` + `type`.** NSDL/CDSL statements\n identify a mutual-fund holding by ISIN only, so `MutualFund` rows used\n to lack the AMFI code and scheme type that RTA (CAMS/KFin) `Scheme`\n rows have. Both are now backfilled from the ISIN database in a single\n batched lookup after parsing (`parsers._isin.batch_isin_metadata`), so\n the same fund parsed from a depository CAS and an RTA CAS reconciles on\n `amfi` / `type` when imported together. Unresolvable ISINs stay `None`.\n- **First-class NSDL and CDSL parsers.** Drops the regex-on-text\n approach the 0.8 NSDL/CDSL code used; the new parsers consume\n structured `Block`/`Cell` records directly from `pypdfium2`. Several\n bugs the v0.8 NSDL/CDSL code shipped with are no longer in scope\n (misplaced-UCC-as-folio on NSDL MF Holdings, space-merged\n folio+units cells on CDSL, the silently-dropped NSDL HDFC\n subaccount on CDSL multi-account statements, `Optional[Decimal]`\n comma-strip miss in the `MutualFund` validator).\n- **CAMS / KFin 2026 templates supported** out of the box. The newer\n CAMS SUMMARY template added an ISIN column the v0.8 regex didn't\n match; v1.0 parses all rows. The newer KFin SUMMARY template emits\n zero-balance schemes with single-space-separated trio cells that\n the v0.8 regex required `\\t\\t` between; v1.0 picks them up too.\n- **AMC-header detection extended** to include the `Fund House`\n suffix. v0.8's regex only matched `Mutual Fund` / `MF` suffixes,\n so schemes from a few newer AMCs whose names end in `Fund House`\n ended up bucketed under the previous AMC.\n- **ISIN / AMFI enrichment has a direct-ISIN fallback** path via\n `MFISINDb.direct_isin_lookup` for the case where multi-line\n `Registrar:` rendering corrupts the RTA token.\n- **Schedule 112A column 1b** (\"Share/Unit Transferred\") is emitted\n for FY2024-25 onward, per the AY 2025-26 ITR utility template. The\n Finance (No. 2) Act 2024 split the equity-LTCG regime on\n 23-Jul-2024; the 112A CSV now flags each transfer `BE`/`AE` against\n that date and splits an after-31-Jan-2018-acquired fund into\n separate rows when it was sold on both sides of the cutoff. Older\n FYs keep the 14-column layout their utility expects.\n- **Cost Inflation Index extended to FY2025-26 (376)** and the\n FY2024-25 value corrected from `365` to the CBDT-notified `363`\n (the wrong value slightly mis-indexed debt-fund LTCG cost of\n acquisition for FY2024-25 sales).\n\n### Fixed\n\n- **CAMS SUMMARY `valuation.date` no longer mis-parses to year 201**\n (was a column-boundary bug \u2014 the NAVDate column treated as\n right-aligned with a 42pt width clipped the trailing year digit,\n then Pydantic mis-coerced the `01-Jan-201` string).\n- **CDSL multi-account statements** (5+ demat accounts on one PDF) are\n now parsed correctly. Earlier the page-3+ scan only kicked in from\n page 8, dropping holdings sections that landed on pages 4-7.\n- **CDSL MF holdings** rows with `DIRECT` (or any non-`ARN-XXXX`\n distribution-mode token) now correctly populate `pnl` and `return_`.\n- **Leading-dot decimals** (`.196`, `-.5`) are now recognised as\n numeric by the NSDL / CDSL cell classifier. CDSL occasionally\n drops the leading zero on sub-unit balances; under the old regex\n those cells were mis-bucketed as text, shifting the row layout\n and producing a silent `\u03a3holdings \u2260 balance` mismatch.\n- **KFin `... - Reversed` transaction rows** (e.g. the Franklin\n wound-up debt schemes' `Payment - Units Extinguished-Reversed`\n entries) had their units cell printed with cosmetic parentheses\n even though the semantic sign is the opposite of the original.\n A new running-balance cross-check in the CAMS / KFin DETAILED\n parser flips the sign (and matching amount) on any single-row\n mis-parse and reclassifies the transaction type via the\n positive-units branch of `get_transaction_type`. Acts as a\n self-validating safety net for the entire transaction stream,\n not just the Franklin case.\n- **Failed-SIP `Payment not received` rows** are now classified as\n `REVERSAL` instead of `REDEMPTION`. These carry negative units (the\n provisional purchase is being undone) with a correct sign, so the\n running-balance validator leaves them untouched \u2014 only the\n description keyword distinguishes them, and it was missing from the\n reversal pattern. Misclassifying them as redemptions injected a\n phantom capital-gains event into the gains analysis.\n- **Stamp-duty allocation on split lots.** When a single purchase\n lot is consumed across N disposals the `FIFOUnits.sell` re-queue\n carried the *full* original stamp duty on every remaining slice,\n so the proportional allocation re-claimed the same paid stamp\n on each disposal \u2014 total stamp claimed grew unboundedly with\n split depth. (Worked example: 300-unit lot with \u20b91.25 stamp,\n split 100/100/100 \u2192 total claimed \u20b92.29 vs \u20b91.25 paid, an 84%\n over-claim that further widens for deeper splits.) The lot is\n now re-queued with the *unallocated remainder* (`purchase_tax -\n stamp_duty`), so the invariant `\u03a3(stamp_claimed) == stamp_paid`\n holds exactly across any number of partial consumptions. Section\n 48 only permits deducting the stamp actually paid as a\n transfer expense, so the prior behaviour over-stated the\n deduction on Schedule 112A.\n- **Soft-hyphen-wrapped tokens in NSDL / CDSL holdings.** Some CAS\n generators insert a `U+00AD` soft hyphen at the point where a long\n token (notably a 12-char ISIN) wraps across two display lines, e.g.\n `INF179K01WN9`. The block/cell extractor now treats a trailing\n soft hyphen as a continuation marker (splicing the next fragment on\n with no separator) and strips any embedded soft hyphens, so the\n token is reconstructed intact. Previously the wrapped ISIN matched\n neither the anchored ISIN regex nor its leftover, and the holding\n was silently dropped. (Reconstruction works when the wrapped\n fragments fall in the same row block; ISINs split across blocks by\n a non-standard page scale are not covered.)\n\n## 0.9.1 - 2026-06-02\n- CDSL: parse holdings rows whose ISIN spans/wraps across multiple\n lines instead of silently dropping them (#129, thanks @mvineetmenon).\n- CDSL: parse stock holdings rows where a long security name wraps so\n the line no longer begins with the ISIN \u2014 these equities were\n previously skipped entirely (#132 / #133, thanks @mvineetmenon).\n- Classify failed-SIP `Payment not received` transactions as\n `REVERSAL` rather than `REDEMPTION`, so a reversed (unsettled)\n purchase no longer surfaces as a spurious redemption / capital-gains\n event (#131, thanks @rahulpatel135).\n- Allow `pytest` 9.x in the dev/test dependency range (#126).\n\n## 0.9.0 - 2026-05-22\n- Add support for CDSL statements\n- Drop support for Python 3.9 and 3.10; minimum supported version is now 3.11\n- Support PyMuPDF >= 1.25 (1.27.x tested). Older `<1.25` pin removed.\n- Bump `casparser-isin` to `>= 2026.5.1` (new DB format v2 with\n `sebi_category`/`last_seen` columns; ISIN-first lookup priority).\n- Relax other dependency pins (click, colorama, rich, pdfminer.six).\n- Fix `MutualFund.fix_float` pydantic validator so the aliased `return`\n field (Python attribute `return_`) also gets the comma-stripping\n treatment; previously NSDL MF folio rows with a return value of\n 1 lakh or more would fail Decimal validation.\n- Parser robustness fixes for PyMuPDF 1.25+ text extraction quirks\n (all superseded in 1.0.0 by the pypdfium2 rewrite, kept here for\n the historical record).\n\n## 0.8.1 - 2025-09-21\n- NSDL parser bug fixes\n\n## 0.8.0 - 2025-02-26\n- NSDL support: first version\n- various bug fixes\n\n## 0.7.4 - 2023-10-04\n- (fix) fix broken scheme names\n\n## 0.7.3 - 2023-09-26\n- (new) Add support for parsing nominee details (available in `Folio.nominees`)\n- (fix) fix empty PAN in certain cases\n\n## 0.7.2 - 2023-09-19\n- Bug fixes\n - Exclude short term capital gains (STCG) from 112A reports\n - Fix advisor code parsing\n\n# 0.7.1 - 2023-09-06\n- fix bug where long scheme names were getting truncated\n\n## 0.7.0 - 2023-09-03\n- update pydantic to v2\n\n## 0.6.1 - 2023-04-04\n- update CII data till FY2022-23\n- bug fixes\n\n## 0.6.0 - 2023-02-20\n- use pydantic models for better data validation\n\n## 0.5.5 - 2022-08-06\n- bug fix with MuPDF parser\n\n## 0.5.4 - 2022-02-01\n- bug fix in CAS summary statement parser\n\n## 0.5.3 - 2021-08-21\n- support for generating csv files for capital gains in 112A format for income tax filing\n- various bug fixes\n\n## 0.5.2 - 2021-08-11\n- fix crash while generating capital gains reports on dividend payout funds\n- rework capital gains algorithm\n- add `advisor` column in transactions csv\n- various bug fixes\n\n## 0.5.1 - 2021-07-21\n- gains: PnL report\n- support for migration of Franklin Templeton funds to CAMS RTA\n- various bug fixes\n\n## 0.5.0 - 2021-07-02\n- Support for calculating capital gains from detailed CAS statements\n- support for parsing Tax Deducted at Source (`TDS`) transactions\n\n## 0.4.8 - 2021-06-27\n- `REVERSAL` TransactionType to indicate reverted/rejected transactions\n- convert all enums to strEnums for better readability [(#35)](https://github.com/codereverser/casparser/pull/35)\n- fix issue with parsing multi-line transactions\n\n## 0.4.7 - 2021-06-01\n\n- Minor bug fixes in summary-statement parser.\n- cli now uses [rich](http://rich.readthedocs.io/) for console output.\n- Use poetry for dependency management and deployment.\n- **BREAKING CHANGE**: Table output choices have been removed.\n `-s/--summary` is a flag and doesn't accept any additional arguments.\n- Support for folios without PAN (#28).\n- add support for new style dividend transactions after IDCW renaming.\n- improved parser for transaction entries.\n\n## 0.4.6 - 2021-04-04\n\n- New `sort_transactions` option in `casparser.read_cas_pdf` (and `--sort` flag in CLI)\n to fix transactions (and balances) for schemes with non-chronological order.\n- support negative balances in transactions\n\n## 0.4.5 - 2021-03-20\n\n- Support for segregated portfolio transactions [ credits: [abhishekjain-qb](https://github.com/abhishekjain-qb) ]\n\n## 0.4.4 - 2021-02-07\n\n- CSV output fixes\n - better csv output format for summary CAS statements.\n - option to output only summary information for detailed statements\n (`-s fancy_grid -o output.csv`)\n\n## 0.4.3 - 2021-01-30\n\n- ISIN, AMFI code mapping for schemes (**beta**)\n\n## 0.4.2 - 2021-01-22\n\n- fixes unicode issues in windows\n- supports negative scheme balances\n- better scheme name parsing\n- fixes dividend transaction parsing\n\n\n## 0.4.1 - 2021-01-13\n\n- hotfix for parsing folios without KYC detail\n... [truncated 1880 chars]\n\n```\n\n### casparser/parsers/cdsl.py\n```python\n\"\"\"Dedicated CDSL parser.\n\nLike `nsdl_parser`, this consumes structured `Block`/`Cell` data from\n`pageobj.extract_blocks` and emits an `NSDLCASData` directly \u2014 no\ndetour through PROD's `process_cdsl_text`.\n\nCDSL CAS layout (in document order; absolute page numbers vary by\nholding count):\n\n - **Cover + account roster** \u2014 investor address block followed by the\n \"Account Type / Account Details / ISINs / Value\" summary table that\n enumerates each demat account and the MF-folios pseudo-account.\n - **Per-MF-folio descriptive blocks** \u2014 AMC Name, Scheme Name,\n Folio No, KYC, ISIN/UCC/RTA, one block group per folio. No\n balances here.\n - **Per-account transaction sections + holdings tables** \u2014 each\n section starts with `DP Name : ... BO ID :\n `, followed by transactions, then a\n `HOLDING STATEMENT AS ON` header and the holdings table itself\n (9-10 cells per row).\n - **`MUTUAL FUND UNITS HELD AS ON` table** \u2014 one row per MF folio\n with full P&L (scheme name, ISIN, folio, ARN code, units, NAV,\n invested, current value, TER, commission, profit, return%).\n - **Notes / footer** at the end.\n\nSome CDSL PDFs ship with a heavy Hindi-font overlay that makes\nroughly half the table cells unreadable by content-stream extraction\n(PROD fails on them too). The atom-level overlay filter in\n`extract.py` recovers most of these; the remainder need a smarter\nfont-aware extractor and are out of scope here.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom decimal import Decimal, InvalidOperation\nfrom typing import Dict, List, Optional, Tuple\n\nfrom casparser.enums import FileType\nfrom casparser.types import (\n DematAccount,\n DematOwner,\n Equity,\n MutualFund,\n NSDLCASData,\n StatementPeriod,\n)\n\nfrom . import pageobj\nfrom ._investor import extract_nsdl_cdsl_investor\nfrom .pageobj import Block\n\n# --- patterns ---\n\nISIN_RE = re.compile(r\"^[A-Z]{2}[0-9A-Z]{9}\\d$\")\nINF_ISIN_RE = re.compile(r\"^INF[0-9A-Z]{8}\\d$\")\nINE_ISIN_RE = re.compile(r\"^IN[E9][0-9A-Z]{8}\\d$\")\n# CDSL sometimes drops the leading zero on fractional values (e.g. a\n# `0.196` unit balance prints as `.196`), so the integer part is\n# optional when a decimal part is present.\nNUMERIC_RE = re.compile(r\"^-?(?:[\\d,]+(?:\\.\\d+)?|\\.\\d+)$\")\n# A long CDSL folio wraps its tail onto the next display line, which the\n# extractor emits as a separate cell \u2014 e.g. folio \"91012112582/0\" splits\n# into \"910121125\" | \"82/0\". The tail is a `/` token; we\n# splice it back onto the folio head (the on-page hyphen at the wrap is\n# only a line-break indicator, absent from the authoritative\n# \"Folio No :\" block).\nFOLIO_TAIL_RE = re.compile(r\"\\d+/\\d+\")\n\nPERIOD_RE = re.compile(\n r\"(?:for\\s+the\\s+period\\s+from|statement\\s+for\\s+the\\s+period\\s+from)\\s+\"\n r\"(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\\s+to\\s+(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\",\n re.I,\n)\n\nDEMAT_TYPE_RE = re.compile(r\"^(CDSL|NSDL)\\s+Demat\\s+Account\\s*$\", re.I)\nPAN_RE = re.compile(r\"(.+?)\\s*\\(\\s*PAN\\s*:\\s*([^)]+?)\\s*\\)\", re.I)\n\n# Page-2 summary row carries `DP Id: Client Id : `\n# (whitespace around the colons varies).\nSUMMARY_DPC_RE = re.compile(\n r\"DP\\s*Id\\s*:\\s*(\\S+?)\\s+Client\\s*Id\\s*:\\s*(\\d+)\",\n re.I,\n)\n# Per-account holdings header: `DP Name : DP ID : \n# CLIENT ID : `.\nSECTION_DPC_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+DP\\s*ID\\s*:\\s*(\\S+)\\s+CLIENT\\s*ID\\s*:\\s*(\\S+)\",\n re.I | re.S,\n)\n# Transaction-page header: `DP Name : BO ID : <16-char id>`.\n# The id concatenates DP ID + Client ID, both 8 chars. CDSL DP IDs are\n# numeric, NSDL DP IDs start with `IN`, so the 16-char field can be all\n# digits (CDSL) or two letters + 14 digits (NSDL).\nSECTION_BOID_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+(?:BO\\s*ID|DPID)\\s*:\\s*([A-Z0-9]{16})\",\n re.I | re.S,\n)\n\n\n# --- decimal helpers ---\n\n\ndef _to_decimal(text) -> Decimal:\n if text is None:\n return Decimal(0)\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return Decimal(0)\n try:\n return Decimal(s)\n except InvalidOperation:\n return Decimal(0)\n\n\ndef _opt_decimal(text) -> Optional[Decimal]:\n if text is None:\n return None\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return None\n try:\n return Decimal(s)\n except InvalidOperation:\n return None\n\n\ndef _looks_numeric(text: str) -> bool:\n s = text.strip()\n if not s:\n return False\n return bool(NUMERIC_RE.match(s))\n\n\n# --- account key utilities ---\n\n\ndef _full_type(type_word: str) -> str:\n return f\"{type_word.upper()} Demat Account\"\n\n\ndef _account_key(type_word: str, dp_id: str, client_id: str) -> Tuple[str, str, str]:\n return (type_word.upper(), dp_id.strip(), client_id.strip())\n\n\ndef _split_bo_id(bo_id: str) -> Tuple[str, str, str]:\n \"\"\"16-char BO ID \u2192 `(type_word, dp_id, client_id)`.\n\n NSDL DP IDs start with `IN` (8 chars total), CDSL DP IDs are pure\n digits. Both followed by an 8-digit Client ID.\"\"\"\n if len(bo_id) != 16:\n return \"\", \"\", \"\"\n if bo_id[:2].upper() == \"IN\":\n return \"NSDL\", bo_id[:8], bo_id[8:]\n if bo_id.isdigit():\n return \"CDSL\", bo_id[:8], bo_id[8:]\n return \"\", \"\", \"\"\n\n\n# --- parser entry point ---\n\n\ndef parse_cdsl(\n pdf_path: str,\n password: str,\n file_type: FileType = FileType.CDSL,\n *,\n _doc=None,\n) -> NSDLCASData:\n atoms = pageobj.extract_atoms(pdf_path, password, _doc=_doc)\n blocks = pageobj.blocks_from_atoms(atoms)\n period = _find_period(blocks) or StatementPeriod(**{\"from\": \"\", \"to\": \"\"})\n\n # Phase 1: account roster from page 2 summary.\n accounts_by_key: Dict[Tuple[str, str, str], DematAccount] = {}\n ordered_accounts: List[DematAccount] = []\n mf_folios_account: Optional[DematAccount] = None\n pending_owners: List[DematOwner] = []\n\n for b in blocks:\n if b.page != 2:\n continue\n txt = b.text()\n ltxt = txt.lower()\n if \"in the single name of\" in ltxt or \"in the joint name\" in ltxt:\n pending_owners = []\n continue\n if PAN_RE.search(txt) and \"Mutual\" not in txt:\n for m in PAN_RE.finditer(txt):\n pending_owners.append(\n DematOwner(\n name=m.group(1).strip(),\n PAN=m.group(2).strip(),\n )\n )\n continue\n if _is_summary_demat_row(b):\n ac, key = _account_from_summary_row(b, pending_owners)\n if key not in accounts_by_key:\n accounts_by_key[key] = ac\n ordered_accounts.append(ac)\n continue\n if _is_summary_mf_folios_row(b):\n if mf_folios_account is None:\n mf_folios_account = _mf_folios_account_from_summary(b, pending_owners)\n ordered_accounts.append(mf_folios_account)\n continue\n\n # Phase 2: scheme-code \u2192 (ISIN, UCC, folio, name) map from the\n # descriptive MF blocks that follow the roster page. Their page\n # span depends on how many MF folios the investor holds; we\n # bound-scan from page 3 up to the start of the per-account\n # transaction section (detected via the `BO ID :` / `DPID :`\n # marker), and only consume blocks that match the descriptive\n # template (Scheme Name + Scheme Code + ISIN + UCC).\n scheme_meta: Dict[str, Dict[str, str]] = {}\n pending_scheme: Dict[str, str] = {}\n for b in blocks:\n if b.page < 3:\n continue\n if SECTION_BOID_RE.search(b.text()):\n break\n txt = b.text()\n if \"Scheme Name :\" in txt and \"Scheme Code :\" in txt:\n sm = re.search(\n r\"Scheme\\s*Name\\s*:\\s*(.+?)\\s+Scheme\\s*Code\\s*:\\s*(\\S+)\",\n txt,\n re.S,\n )\n if sm:\n pending_scheme = {\n \"scheme_name\": sm.group(1).replace(\"\\n\", \" \").strip(),\n \"scheme_code\": sm.group(2).strip(),\n }\n elif \"Folio No :\" in txt:\n fm = re.search(r\"Folio\\s*No\\s*:\\s*(\\S+)\", txt)\n if fm:\n pending_scheme[\"folio\"] = fm.group(1)\n elif \"ISIN :\" in txt and \"UCC\" in txt:\n im = re.search(r\"ISIN\\s*:\\s*(\\S+)\", txt)\n um = re.search(r\"UCC\\s*:\\s*([\\w/]+)?\", txt)\n if im and pending_scheme.get(\"scheme_code\"):\n pending_scheme[\"isin\"] = im.group(1)\n if um and um.group(1):\n pending_scheme[\"ucc\"] = um.group(1)\n scheme_meta[pending_scheme[\"scheme_code\"]] = dict(pending_scheme)\n pending_scheme = {}\n\n # Phase 3: walk all post-cover pages for holdings tables.\n # We skip pages 1-2 (cover + roster) because the roster lines\n # contain CDSL/NSDL identifiers that would otherwise look like\n # section headers; the dispatch logic below handles the rest.\n cur_account: Optional[DematAccount] = None\n cur_mode: Optional[str] = None # 'equities' | 'mf_holdings'\n\n for b in blocks:\n if b.page < 3:\n continue\n txt = b.text()\n ltxt = txt.lower()\n\n # Per-account section header \u2014 `DP Name : ... BO ID : ...`\n # or `DP Name : ... DPID : ...` (NSDL variant) form.\n m = SECTION_BOID_RE.search(txt)\n if m:\n broker = m.group(1).strip()\n bo_id = m.group(2)\n type_word, dp_id, client_id = _split_bo_id(bo_id)\n if type_word:\n ac_key = _account_key(type_word, dp_id, client_id)\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Or \"DP Name : ... DP ID : ... CLIENT ID : ...\"\n m = SECTION_DPC_RE.search(txt)\n if m:\n type_word = \"CDSL\"\n if \"NSDL\" in txt.upper() and \"CDSL\" not in txt.upper():\n type_word = \"NSDL\"\n broker, dp_id, client_id = m.groups()\n ac_key = _account_key(type_word, dp_id.strip(), client_id.strip())\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Transaction-statement section \u2014 switch OFF holdings mode so\n # transaction rows aren't parsed as equity rows.\n if \"statement of transactions\" in ltxt:\n cur_mode = None\n continue\n\n # Holdings section markers\n if \"holding statement\" in ltxt and \"as on\" in ltxt:\n cur_mode = \"equities\"\n continue\n if \"mutual fund units held as on\" in ltxt:\n cur_account = mf_folios_account\n cur_mode = \"mf_holdings\"\n continue\n\n # Skip column-header rows\n if _is_holdings_header(b) or _is_total_row(b):\n continue\n\n # Holdings rows\n if cur_account is None or cur_mode is None:\n continue\n if cur_mode == \"equities\":\n row = _parse_holdings_row(b)\n if row is None:\n pass\n else:\n isin, name, num_shares, price, value = row\n # CDSL Demat statements list ETFs (ISIN starting with\n # INF) in the same holdings table as equities, but\n # they're semantically mutual-fund units. Route them\n # to the mutual_funds list to mirror PROD's\n # classification.\n if INF_ISIN_RE.match(isin):\n cur_account.mutual_funds.append(\n MutualFund(\n name=name,\n isin=isin,\n balance=num_shares,\n nav=price,\n value=value,\n )\n )\n else:\n cur_account.equities.append(\n Equity(\n name=name,\n isin=isin,\n num_shares=num_shares,\n price=price,\n value=value,\n )\n )\n elif cur_mode == \"mf_holdings\":\n mf = _parse_mf_holdings_row(b, scheme_meta)\n if mf:\n cur_account.mutual_funds.append(mf)\n\n return NSDLCASData(\n statement_period=period,\n accounts=ordered_accounts,\n investor_info=extract_nsdl_cdsl_investor(\n pdf_path,\n password,\n _atoms=atoms,\n ),\n file_type=file_type,\n )\n\n\n# --- summary-row recognisers (page 2) ---\n\n\ndef _is_summary_demat_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n if not DEMAT_TYPE_RE.match(block.cells[0].text.strip()):\n return False\n return bool(SUMMARY_DPC_RE.search(block.cells[1].text))\n\n\ndef _is_summary_mf_folios_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n return bool(re.match(r\"^Mutual\\s+Fund\\s+Folios\", block.cells[0].text.strip(), re.I))\n\n\ndef _account_from_summary_row(\n block: Block, owners: List[DematOwner]\n) -> Tuple[DematAccount, Tuple[str, str, str]]:\n type_word = DEMAT_TYPE_RE.match(block.cells[0].text.strip()).group(1).upper()\n broker_dp = block.cells[1].text\n lines = [ln.strip() for ln in broker_dp.split(\"\\n\") if ln.strip()]\n broker = lines[0] if lines else \"\"\n dpc = SUMMARY_DPC_RE.search(broker_dp)\n dp_id = dpc.group(1) if dpc else \"\"\n client_id = dpc.group(2) if dpc else \"\"\n folios = int(_to_decimal(block.cells[2].text))\n balance = _to_decimal(block.cells[3].text)\n ac = DematAccount(\n name=broker,\n type=_full_type(type_word),\n dp_id=dp_id,\n client_id=client_id,\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n return ac, _account_key(type_word, dp_id, client_id)\n\n\ndef _mf_folios_account_from_summary(block: Block, owners: List[DematOwner]) -> DematAccount:\n folios_m = re.search(r\"(\\d+)\", block.cells[1].text)\n folios = int(folios_m.group(1)) if folios_m else 0\n balance = _to_decimal(block.cells[3].text)\n return DematAccount(\n name=\"Mutual Fund Folios\",\n type=\"Mutual Fund Folios\",\n dp_id=\"\",\n client_id=\"\",\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n\n\n# --- helpers ---\n\n\ndef _find_period(blocks: List[Block]) -> Optional[StatementPeriod]:\n for b in blocks:\n m = PERIOD_RE.search(b.text())\n if m:\n return StatementPeriod(**{\"from\": m.group(1), \"to\": m.group(2)})\n return None\n\n\ndef _is_holdings_header(block: Block) -> bool:\n \"\"\"Block has no ISIN and looks like a column-label row.\"\"\"\n txt = block.text()\n if re.search(r\"\\b(IN[EF9][0-9A-Z]{8}\\d)\\b\", txt, re.I):\n return False\n ltxt = txt.lower().replace(\"\\n\", \" \").replace(\"\\t\\t\", \" \")\n if \"isin\" in ltxt and (\"security\" in ltxt or \"scheme name\" in ltxt):\n return True\n if \"current\" in ltxt and \"bal\" in ltxt and \"market\" in ltxt:\n return True\n return False\n\n\ndef _is_total_row(block: Block) -> bool:\n first = block.cells[0].text.strip().lower() if block.cells else \"\"\n return first in (\"sub total\", \"total\", \"grand total\")\n\n\n# --- equity holdings row ---\n\n\ndef _parse_holdings_row(block: Block) -> Optional[Tuple[str, str, Decimal, Decimal, Decimal]]:\n \"\"\"CDSL holdings row \u2192 `(isin, name, num_shares, price, value)`.\n\n Column layout (post-`HOLDING STATEMENT`):\n ISIN | Security | Current Bal | Frozen Bal | Pledge Bal |\n Pledge Setup Bal | Free Bal | Market Price | Value (`)\n\n A few rows have a leading '@' marker cell between ISIN and name\n (suspended issue notation). Rows with all-`--` quantity cells\n (rights entitlements that haven\n... [truncated 5867 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-dc6fd68ed28a", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-dc6fd68ed28a", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "ea95d2eee7e194aef2375e7b5804fb481efeff80", "source_files": ["CHANGELOG.md", "casparser/parsers/cdsl.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Stamp duty over-allocated when a purchase lot is sold in multiple parts\n\n## Description\nWhen a single purchase lot is partially sold across multiple disposals, the stamp duty allocated to each subsequent partial sale is incorrectly calculated. This leads to an over-allocation of the total stamp duty, exceeding\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `84cdbdc97389` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 1.0.0\n\nMajor release. The parsing backend was rewritten from scratch on\n[pypdfium2](https://github.com/pypdfium2-team/pypdfium2) (Apache-2.0 /\nBSD-3) and the four supported CAS issuers now each have a dedicated\nparser tuned to their template family.\n\n### Breaking changes\n\n- **pdfminer.six and PyMuPDF backends removed.** `casparser.read_cas_pdf`\n no longer dispatches between them. The `mupdf` / `fast` extras in\n `pyproject.toml` are gone. The `--force-pdfminer` CLI flag and the\n `force_pdfminer=` kwarg on `read_cas_pdf` are kept as no-ops; the\n kwarg emits a `DeprecationWarning` and is otherwise ignored.\n- **License simplified to pure MIT.** With the GPL/AGPL-licensed\n PyMuPDF dependency gone, the `licenses/` directory of GPL/AGPL\n copies has been removed. pypdfium2 is dual Apache-2.0 / BSD-3 and\n doesn't impose any copyleft obligation on users of casparser.\n- **Minimum Python is now 3.11.** 3.9 / 3.10 classifiers dropped from\n `pyproject.toml`.\n- **`CASData.investor_info` is now `Optional[InvestorInfo]`** (matches\n the `NSDLCASData.investor_info` shape that already existed). It is\n populated on every supported issuer, but consumers should still\n guard against the `None` case for unfamiliar templates.\n- **Internal `casparser.process` package removed.** The two helpers\n downstream code still imports from it are now at\n `casparser.parsers._classify` (`get_parsed_scheme_name`,\n `get_transaction_type`) and `casparser.parsers._isin` (`isin_search`).\n\n### New\n\n- **First-class NSDL and CDSL parsers.** Drops the regex-on-text\n approach the 0.8 NSDL/CDSL code used; the new parsers consume\n structured `Block`/`Cell` records directly from `pypdfium2`. Several\n bugs the v0.8 NSDL/CDSL code shipped with are no longer in scope\n (misplaced-UCC-as-folio on NSDL MF Holdings, space-merged\n folio+units cells on CDSL, the silently-dropped NSDL HDFC\n subaccount on CDSL multi-account statements, `Optional[Decimal]`\n comma-strip miss in the `MutualFund` validator).\n- **CAMS / KFin 2026 templates supported** out of the box. The newer\n CAMS SUMMARY template added an ISIN column the v0.8 regex didn't\n match; v1.0 parses all rows. The newer KFin SUMMARY template emits\n zero-balance schemes with single-space-separated trio cells that\n the v0.8 regex required `\\t\\t` between; v1.0 picks them up too.\n- **AMC-header detection extended** to include the `Fund House`\n suffix. v0.8's regex only matched `Mutual Fund` / `MF` suffixes,\n so schemes from a few newer AMCs whose names end in `Fund House`\n ended up bucketed under the previous AMC.\n- **ISIN / AMFI enrichment has a direct-ISIN fallback** path via\n `MFISINDb.direct_isin_lookup` for the case where multi-line\n `Registrar:` rendering corrupts the RTA token.\n- **Schedule 112A column 1b** (\"Share/Unit Transferred\") is emitted\n for FY2024-25 onward, per the AY 2025-26 ITR utility template. The\n Finance (No. 2) Act 2024 split the equity-LTCG regime on\n 23-Jul-2024; the 112A CSV now flags each transfer `BE`/`AE` against\n that date and splits an after-31-Jan-2018-acquired fund into\n separate rows when it was sold on both sides of the cutoff. Older\n FYs keep the 14-column layout their utility expects.\n- **Cost Inflation Index extended to FY2025-26 (376)** and the\n FY2024-25 value corrected from `365` to the CBDT-notified `363`\n (the wrong value slightly mis-indexed debt-fund LTCG cost of\n acquisition for FY2024-25 sales).\n\n### Fixed\n\n- **CAMS SUMMARY `valuation.date` no longer mis-parses to year 201**\n (was a column-boundary bug \u2014 the NAVDate column treated as\n right-aligned with a 42pt width clipped the trailing year digit,\n then Pydantic mis-coerced the `01-Jan-201` string).\n- **CDSL multi-account statements** (5+ demat accounts on one PDF) are\n now parsed correctly. Earlier the page-3+ scan only kicked in from\n page 8, dropping holdings sections that landed on pages 4-7.\n- **CDSL MF holdings** rows with `DIRECT` (or any non-`ARN-XXXX`\n distribution-mode token) now correctly populate `pnl` and `return_`.\n- **Leading-dot decimals** (`.196`, `-.5`) are now recognised as\n numeric by the NSDL / CDSL cell classifier. CDSL occasionally\n drops the leading zero on sub-unit balances; under the old regex\n those cells were mis-bucketed as text, shifting the row layout\n and producing a silent `\u03a3holdings \u2260 balance` mismatch.\n- **KFin `... - Reversed` transaction rows** (e.g. the Franklin\n wound-up debt schemes' `Payment - Units Extinguished-Reversed`\n entries) had their units cell printed with cosmetic parentheses\n even though the semantic sign is the opposite of the original.\n A new running-balance cross-check in the CAMS / KFin DETAILED\n parser flips the sign (and matching amount) on any single-row\n mis-parse and reclassifies the transaction type via the\n positive-units branch of `get_transaction_type`. Acts as a\n self-validating safety net for the entire transaction stream,\n not just the Franklin case.\n\n## 0.9.0 - 2026-05-22\n- Add support for CDSL statements\n- Drop support for Python 3.9 and 3.10; minimum supported version is now 3.11\n- Support PyMuPDF >= 1.25 (1.27.x tested). Older `<1.25` pin removed.\n- Bump `casparser-isin` to `>= 2026.5.1` (new DB format v2 with\n `sebi_category`/`last_seen` columns; ISIN-first lookup priority).\n- Relax other dependency pins (click, colorama, rich, pdfminer.six).\n- Fix `MutualFund.fix_float` pydantic validator so the aliased `return`\n field (Python attribute `return_`) also gets the comma-stripping\n treatment; previously NSDL MF folio rows with a return value of\n 1 lakh or more would fail Decimal validation.\n- Parser robustness fixes for PyMuPDF 1.25+ text extraction quirks\n (all superseded in 1.0.0 by the pypdfium2 rewrite, kept here for\n the historical record).\n\n## 0.8.1 - 2025-09-21\n- NSDL parser bug fixes\n\n## 0.8.0 - 2025-02-26\n- NSDL support: first version\n- various bug fixes\n\n## 0.7.4 - 2023-10-04\n- (fix) fix broken scheme names\n\n## 0.7.3 - 2023-09-26\n- (new) Add support for parsing nominee details (available in `Folio.nominees`)\n- (fix) fix empty PAN in certain cases\n\n## 0.7.2 - 2023-09-19\n- Bug fixes\n - Exclude short term capital gains (STCG) from 112A reports\n - Fix advisor code parsing\n\n# 0.7.1 - 2023-09-06\n- fix bug where long scheme names were getting truncated\n\n## 0.7.0 - 2023-09-03\n- update pydantic to v2\n\n## 0.6.1 - 2023-04-04\n- update CII data till FY2022-23\n- bug fixes\n\n## 0.6.0 - 2023-02-20\n- use pydantic models for better data validation\n\n## 0.5.5 - 2022-08-06\n- bug fix with MuPDF parser\n\n## 0.5.4 - 2022-02-01\n- bug fix in CAS summary statement parser\n\n## 0.5.3 - 2021-08-21\n- support for generating csv files for capital gains in 112A format for income tax filing\n- various bug fixes\n\n## 0.5.2 - 2021-08-11\n- fix crash while generating capital gains reports on dividend payout funds\n- rework capital gains algorithm\n- add `advisor` column in transactions csv\n- various bug fixes\n\n## 0.5.1 - 2021-07-21\n- gains: PnL report\n- support for migration of Franklin Templeton funds to CAMS RTA\n- various bug fixes\n\n## 0.5.0 - 2021-07-02\n- Support for calculating capital gains from detailed CAS statements\n- support for parsing Tax Deducted at Source (`TDS`) transactions\n\n## 0.4.8 - 2021-06-27\n- `REVERSAL` TransactionType to indicate reverted/rejected transactions\n- convert all enums to strEnums for better readability [(#35)](https://github.com/codereverser/casparser/pull/35)\n- fix issue with parsing multi-line transactions\n\n## 0.4.7 - 2021-06-01\n\n- Minor bug fixes in summary-statement parser.\n- cli now uses [rich](http://rich.readthedocs.io/) for console output.\n- Use poetry for dependency management and deployment.\n- **BREAKING CHANGE**: Table output choices have been removed.\n `-s/--summary` is a flag and doesn't accept any additional arguments.\n- Support for folios without PAN (#28).\n- add support for new style dividend transactions after IDCW renaming.\n- improved parser for transaction entries.\n\n## 0.4.6 - 2021-04-04\n\n- New `sort_transactions` option in `casparser.read_cas_pdf` (and `--sort` flag in CLI)\n to fix transactions (and balances) for schemes with non-chronological order.\n- support negative balances in transactions\n\n## 0.4.5 - 2021-03-20\n\n- Support for segregated portfolio transactions [ credits: [abhishekjain-qb](https://github.com/abhishekjain-qb) ]\n\n## 0.4.4 - 2021-02-07\n\n- CSV output fixes\n - better csv output format for summary CAS statements.\n - option to output only summary information for detailed statements\n (`-s fancy_grid -o output.csv`)\n\n## 0.4.3 - 2021-01-30\n\n- ISIN, AMFI code mapping for schemes (**beta**)\n\n## 0.4.2 - 2021-01-22\n\n- fixes unicode issues in windows\n- supports negative scheme balances\n- better scheme name parsing\n- fixes dividend transaction parsing\n\n\n## 0.4.1 - 2021-01-13\n\n- hotfix for parsing folios without KYC details\n\n## 0.4.0 - 2021-01-08\n\n- adds support for parsing summary statements from CAMS/KARVY (**beta**)\n- minor bug fixes in CSV file generation\n\n## 0.3.9 - 2021-01-01\n\n- Support for classifying transactions\n\n## 0.3.8 - 2020-12-29\n\n- Support for parsing folios without PAN/KYC details\n\n## 0.3.7 - 2020-12-24\n\n- Support for parsing dividend transactions\n\n## 0.3.6 - 2020-12-21\n\n- Support for parsing folios without advisor\n\n## 0.3.5 - 2020-11-13\n\n- Support for parsing scheme's latest nav\n- Replaced `texttable` with `tabulate` for more cli output formats\n- Added more test cases\n\n## 0.3.4 - 2020-11-08\n\n- Support for parsing scheme valuation\n- Parser code refactor (transparent to user)\n\n## 0.3.3 - 2020-10-31\n\n- Added `balance` to Transaction\n- Added test cases with travis-ci and codecov support\n- minor bug fixes while parsing kfintech cas files\n\n## 0.3.2 - 2020-10-29\n\n- minor bug fixes\n\n## 0.3.1 - 2020-10-26\n\n- re-release 0.3.0 : Minor bug fix\n\n## 0.3.0 - 2020-10-25\n\n- **Breaking Change**: In order to preserve the order of entries, during format\n conversion to other data types like json., `folios` is a list instead of dict.\n- Added a second parser based on [PyMuPDF](https://github.com/pymupdf/PyMuPDF) /\n[MuPDF](https://mupdf.com/) - ~15-20x faster compared to pure-python pdfminer.\n- Added AMC detection (accessible via `amc` property of folio)\n- CLI summary now includes the number of transactions processed.\n\n## 0.2.1 - 2020-10-23\n\n- `read_cas_pdf` now supports more input types\n- better cli summary output\n- fixed investor info parsing where mobile numbers don't have country code\n- updated dependencies\n\n## 0.2.0 - 2020-10-15\n\n- removed support for python versions <3.8\n- Better investor info parser\n\n## 0.1.2 - 2020-10-14\n\n- Support for parsing investor info\n\n## 0.1.1 - 2020-10-14\n\n- Support for parsing folios without PAN\n\n## 0.1.0 - 2020-10-11\n\n- Initial release\n\n```\n\n### casparser/analysis/gains.py\n```python\nimport csv\nimport io\nimport itertools\nimport re\nfrom collections import deque\nfrom dataclasses import dataclass\nfrom datetime import date\nfrom decimal import Decimal\nfrom typing import List\n\nfrom dateutil.parser import parse as dateparse\nfrom dateutil.relativedelta import relativedelta\n\nfrom casparser.enums import FundType, GainType, TransactionType\nfrom casparser.exceptions import GainsError, IncompleteCASError\nfrom casparser.types import CASData, TransactionData\n\nfrom .utils import CII, get_fin_year, nav_search\n\nPURCHASE_TXNS = {\n TransactionType.DIVIDEND_REINVEST,\n TransactionType.PURCHASE,\n TransactionType.PURCHASE_SIP,\n TransactionType.REVERSAL,\n # Segregated folios are not supported\n # TransactionType.SEGREGATION.name,\n TransactionType.SWITCH_IN,\n TransactionType.SWITCH_IN_MERGER,\n}\n\nSALE_TXNS = {\n TransactionType.REDEMPTION.name,\n TransactionType.SWITCH_OUT.name,\n TransactionType.SWITCH_OUT_MERGER.name,\n}\n\n\n# Finance (No. 2) Act 2024 split the FY2024-25 LTCG regime on this date\n# (equity LTCG 10% -> 12.5%, exemption 1L -> 1.25L). Schedule 112A from\n# AY 2025-26 carries a column 1b (\"Share/Unit Transferred\") flagging which\n# side of this date each *transfer* (sale) falls on.\nLTCG_REGIME_CUTOFF = date(2024, 7, 23)\n\n# Schedule 112A column 1b only exists on the AY 2025-26 (FY 2024-25) utility\n# and later. We emit it when the report's FY starts in 2024 or later.\nTRANSFER_COL_FROM_FY_START_YEAR = 2024\n\n\ndef _transfer_flag(sale_date: date) -> str:\n \"\"\"Schedule 112A column 1b value for a transfer on `sale_date`:\n ``BE`` if before 23-Jul-2024, ``AE`` on or after.\"\"\"\n return \"BE\" if sale_date < LTCG_REGIME_CUTOFF else \"AE\"\n\n\ndef _fy_needs_transfer_col(fy: str) -> bool:\n \"\"\"True if `fy` (e.g. ``FY2024-25``) is FY2024-25 or later, i.e. the\n Schedule 112A column 1b applies.\"\"\"\n m = re.match(r\"FY(\\d{4})\", fy or \"\")\n return bool(m) and int(m.group(1)) >= TRANSFER_COL_FROM_FY_START_YEAR\n\n\n@dataclass\nclass GainEntry112A:\n \"\"\"GainEntry for schedule 112A of ITR.\"\"\"\n\n acquired: str # AE, BE \u2014 col 1a (acquired before/after 31-Jan-2018)\n transferred: str # AE, BE \u2014 col 1b (transferred before/after 23-Jul-2024)\n isin: str\n name: str\n units: Decimal\n sale_nav: Decimal\n sale_value: Decimal\n purchase_value: Decimal\n fmv_nav: Decimal\n fmv: Decimal\n stt: Decimal\n stamp_duty: Decimal\n\n @property\n def consideration_value(self):\n if self.acquired == \"BE\":\n return min(self.fmv, self.sale_value)\n else:\n return Decimal(\"0.00\") # FMV not considered\n\n @property\n def actual_coa(self):\n return max(self.purchase_value, self.consideration_value)\n\n @property\n def expenditure(self):\n return self.stt + self.stamp_duty\n\n @property\n def deductions(self):\n return self.actual_coa + self.expenditure\n\n @property\n def balance(self):\n return self.sale_value - self.deductions\n\n\n@dataclass\nclass MergedTransaction:\n \"\"\"Represent net transaction on a given date\"\"\"\n\n dt: date\n nav: Decimal = Decimal(0.0)\n purchase: Decimal = Decimal(0.0)\n purchase_units: Decimal = Decimal(0.0)\n sale: Decimal = Decimal(0.0)\n sale_units: Decimal = Decimal(0.0)\n stamp_duty: Decimal = Decimal(0.0)\n stt: Decimal = Decimal(0.0)\n tds: Decimal = Decimal(0.0)\n\n def add(self, txn: TransactionData):\n txn_type = txn.type\n if txn_type in PURCHASE_TXNS and txn.units is not None:\n self.nav = txn.nav\n self.purchase_units += txn.units\n self.purchase += txn.amount\n elif txn_type in SALE_TXNS and txn.units is not None:\n self.nav = txn.nav\n self.sale_units += txn.units\n self.sale += txn.amount\n elif txn_type == TransactionType.STT_TAX:\n self.stt += txn.amount\n elif txn_type == TransactionType.STAMP_DUTY_TAX:\n self.stamp_duty += txn.amount\n elif txn_type == TransactionType.TDS_TAX:\n self.tds += txn.amount\n elif txn_type == TransactionType.SEGREGATION:\n self.nav = Decimal(0.0)\n self.purchase_units += txn.units\n self.purchase = Decimal(0.0)\n\n\n@dataclass\nclass Fund:\n \"\"\"Fund details\"\"\"\n\n scheme: str\n folio: str\n isin: str\n type: str\n\n @property\n def name(self):\n return f\"{self.scheme} [{self.folio}]\"\n\n def __lt__(self, other: \"Fund\"):\n return self.scheme < other.scheme\n\n\n@dataclass\nclass GainEntry:\n \"\"\"Gain data of a realised transaction\"\"\"\n\n fy: str\n fund: Fund\n type: str\n purchase_date: date\n purchase_nav: Decimal\n purchase_value: Decimal\n stamp_duty: Decimal\n sale_date: date\n sale_nav: Decimal\n sale_value: Decimal\n stt: Decimal\n units: Decimal\n\n def __post_init__(self):\n self.__cutoff_date = date(2018, 1, 31)\n self.__sell_cutoff_date = date(2018, 4, 1)\n self.__update_nav()\n\n def __update_nav(self):\n self._cached_isin = self.fund.isin\n self._cached_nav = nav_search(self._cached_isin)\n\n @property\n def gain_type(self):\n \"\"\"Identify gain type based on the current fund type, buy and sell dates.\"\"\"\n ltcg = {\n FundType.EQUITY.name: self.purchase_date + relativedelta(years=1),\n FundType.DEBT.name: self.purchase_date + relativedelta(years=3),\n }\n\n return GainType.LTCG if self.sale_date > ltcg[self.type] else GainType.STCG\n\n @property\n def gain(self) -> Decimal:\n return Decimal(round(self.sale_value - self.purchase_value, 2))\n\n @property\n def fmv_nav(self) -> Decimal:\n if self.fund.isin != self._cached_isin:\n self.__update_nav()\n return self._cached_nav\n\n @property\n def fmv(self) -> Decimal:\n if self.fmv_nav is None:\n return self.purchase_value\n return self.fmv_nav * self.units\n\n @property\n def index_ratio(self) -> Decimal:\n return Decimal(\n round(CII[get_fin_year(self.sale_date)] / CII[get_fin_year(self.purchase_date)], 2)\n )\n\n @property\n def coa(self) -> Decimal:\n if self.fund.type == FundType.DEBT:\n return Decimal(round(self.purchase_value * self.index_ratio, 2))\n if self.purchase_date < self.__cutoff_date:\n if self.sale_date < self.__sell_cutoff_date:\n return self.sale_value\n return max(self.purchase_value, min(self.fmv, self.sale_value))\n return self.purchase_value\n\n @property\n def ltcg_taxable(self) -> Decimal:\n if self.gain_type == GainType.LTCG:\n return Decimal(round(self.sale_value - self.coa, 2))\n return Decimal(0.0)\n\n @property\n def ltcg(self) -> Decimal:\n if self.gain_type == GainType.LTCG:\n return self.gain\n return Decimal(0.0)\n\n @property\n def stcg(self) -> Decimal:\n if self.gain_type == GainType.STCG:\n return self.gain\n return Decimal(0.0)\n\n\ndef get_fund_type(transactions: List[TransactionData]) -> FundType:\n \"\"\"\n Detect Fund Type.\n - UNKNOWN if there are no redemption transactions\n - EQUITY if STT_TAX transactions are present in the portfolio\n - DEBT if no STT_TAX transactions are present along with redemptions\n\n :param transactions: list of transactions for a single fund parsed from the CAS\n :return: type of fund\n \"\"\"\n valid = any(\n [\n x.units is not None and x.units < 0 and x.type != TransactionType.REVERSAL\n for x in transactions\n ]\n )\n if not valid:\n return FundType.UNKNOWN\n return (\n FundType.EQUITY\n if any([x.type == TransactionType.STT_TAX for x in transactions])\n else FundType.DEBT\n )\n\n\nclass FIFOUnits:\n \"\"\"First-In First-Out units calculator.\"\"\"\n\n def __init__(self, fund: Fund, transactions: List[TransactionData]):\n \"\"\"\n :param fund: name of fund, mainly for reporting purposes.\n :param transactions: list of transactions for the fund\n \"\"\"\n self._fund: Fund = fund\n self._original_transactions = transactions\n if fund.type not in (\"EQUITY\", \"DEBT\"):\n self.fund_type = get_fund_type(transactions)\n else:\n self.fund_type = getattr(FundType, fund.type)\n self._merged_transactions = self.merge_transactions()\n\n self.transactions = deque()\n self.invested = Decimal(0.0)\n self.balance = Decimal(0.0)\n self.gains: List[GainEntry] = []\n\n self.process()\n\n @property\n def clean_transactions(self):\n \"\"\"remove redundant transactions, without amount\"\"\"\n return filter(lambda x: x.amount is not None, self._original_transactions)\n\n def merge_transactions(self):\n \"\"\"Group transactions by date with taxes and investments/redemptions separated.\"\"\"\n merged_transactions = {}\n for txn in sorted(self.clean_transactions, key=lambda x: (x.date, -x.amount)):\n dt = txn.date\n\n if isinstance(dt, str):\n dt = dateparse(dt).date()\n\n if dt not in merged_transactions:\n merged_transactions[dt] = MergedTransaction(dt)\n merged_transactions[dt].add(txn)\n return merged_transactions\n\n def process(self):\n self.gains = []\n for dt in sorted(self._merged_transactions.keys()):\n txn = self._merged_transactions[dt]\n if txn.purchase_units > 0:\n self.buy(dt, txn.purchase_units, txn.nav, txn.stamp_duty)\n if txn.sale_units < 0:\n self.sell(dt, txn.sale_units, txn.nav, txn.stt)\n return self.gains\n\n def buy(self, txn_date: date, quantity: Decimal, nav: Decimal, tax: Decimal):\n self.transactions.append((txn_date, quantity, nav, tax))\n self.invested += quantity * nav\n self.balance += quantity\n\n def sell(self, sell_date: date, quantity: Decimal, nav: Decimal, tax: Decimal):\n fin_year = get_fin_year(sell_date)\n original_quantity = abs(quantity)\n pending_units = original_quantity\n while pending_units >= 1e-2:\n try:\n purchase_date, units, purchase_nav, purchase_tax = self.transactions.popleft()\n except IndexError:\n raise GainsError(\n f\"FIFOUnits mismatch for {self._fund.name}. Please contact support.\"\n )\n if units <= pending_units:\n gain_units = units\n else:\n gain_units = pending_units\n\n purchase_value = round(gain_units * purchase_nav, 2)\n sale_value = round(gain_units * nav, 2)\n stamp_duty = round(purchase_tax * gain_units / units, 2)\n stt = round(tax * gain_units / original_quantity, 2)\n\n ge = GainEntry(\n fy=fin_year,\n fund=self._fund,\n type=self.fund_type.name,\n purchase_date=purchase_date,\n purchase_nav=purchase_nav,\n purchase_value=purchase_value,\n stamp_duty=stamp_duty,\n sale_date=sell_date,\n sale_nav=nav,\n sale_value=sale_value,\n stt=stt,\n units=gain_units,\n )\n self.gains.append(ge)\n\n self.balance -= gain_units\n self.invested -= purchase_value\n\n pending_units -= units\n if pending_units < 0 and purchase_nav is not None:\n # Sale is partially matched against the last buy transactions\n # Re-add the remaining units to the FIFO queue\n self.transactions.appendleft(\n (purchase_date, -1 * pending_units, purchase_nav, purchase_tax)\n )\n\n\nclass CapitalGainsReport:\n \"\"\"Generate Capital Gains Report from the parsed CAS data\"\"\"\n\n def __init__(self, data: CASData):\n self._data: CASData = data\n self._gains: List[GainEntry] = []\n self.errors = []\n self.invested_amount = Decimal(0.0)\n self.current_value = Decimal(0.0)\n self.process_data()\n\n @property\n def gains(self) -> List[GainEntry]:\n return list(sorted(self._gains, key=lambda x: (x.fy, x.fund, x.sale_date)))\n\n def has_gains(self) -> bool:\n return len(self.gains) > 0\n\n def has_error(self) -> bool:\n return len(self.errors) > 0\n\n def get_fy_list(self) -> List[str]:\n return list(sorted(set([f.fy for f in self.gains]), reverse=True))\n\n def process_data(self):\n self._gains = []\n for folio in self._data.folios:\n for scheme in folio.schemes:\n transactions = scheme.transactions\n fund = Fund(\n scheme=scheme.scheme,\n folio=folio.folio,\n isin=scheme.isin,\n type=scheme.type,\n )\n if len(transactions) > 0:\n if scheme.open >= 0.01:\n raise IncompleteCASError(\n \"Incomplete CAS found. For gains computation, \"\n \"all folios should have zero opening balance\"\n )\n try:\n fifo = FIFOUnits(fund, transactions)\n self.invested_amount += fifo.invested\n self.current_value += scheme.valuation.value\n self._gains.extend(fifo.gains)\n except GainsError as exc:\n self.errors.append((fund.name, str(exc)))\n\n def get_summary(self):\n \"\"\"Calculate capital gains summary\"\"\"\n summary = []\n for (fy, fund), txns in itertools.groupby(self.gains, key=lambda x: (x.fy, x.fund)):\n ltcg = stcg = ltcg_taxable = Decimal(0.0)\n for txn in txns:\n ltcg += txn.ltcg\n stcg += txn.stcg\n ltcg_taxable += txn.ltcg_taxable\n summary.append([fy, fund.name, fund.isin, fund.type, ltcg, ltcg_taxable, stcg])\n return summary\n\n def get_summary_csv_data(self) -> str:\n \"\"\"Return summary data as a csv string.\"\"\"\n headers = [\"FY\", \"Fund\", \"ISIN\", \"Type\", \"LTCG(Realized)\", \"LTCG(Taxable)\", \"STCG\"]\n with io.StringIO() as csv_fp:\n writer = csv.writer(csv_fp)\n writer.writerow(headers)\n for entry in self.get_summary():\n writer.writerow(entry)\n csv_fp.seek(0)\n csv_data = csv_fp.read()\n return csv_data\n\n def get_gains_csv_data(self) -> str:\n \"\"\"Return details gains data as a csv string.\"\"\"\n headers = [\n \"FY\",\n \"Fund\",\n \"ISIN\",\n \"Type\",\n \"Units\",\n \"Purchase Date\",\n \"Purchase Value\",\n \"Stamp Duty\",\n \"Acquisition Value\",\n \"Sale Date\",\n \"Sale Value\",\n \"STT\",\n \"LTCG Realized\",\n \"LTCG Taxable\",\n \"STCG\",\n ]\n with io.StringIO() as csv_fp:\n writer = csv.writer(csv_fp)\n writer.writerow(headers)\n for gain in self.gains:\n writer.writerow(\n [\n gain.fy,\n gain.fund.name,\n gain.fund.isin,\n gain.type,\n gain.units,\n gain.purchase_date,\n gain.purchase_value,\n gain.stamp_duty,\n gain.coa,\n gain.sale_date,\n gain.sale_value,\n gain.stt,\n gain.ltcg,\n gain.ltcg_taxable,\n gain.stcg,\n ]\n )\n csv_fp.seek(0)\n \n... [truncated 5058 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-e3a5f714eb37", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-e3a5f714eb37", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "84cdbdc97389f41a748c72e57b83f9fe89ec12d4", "source_files": ["CHANGELOG.md", "casparser/analysis/gains.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** NPS scheme/fund-manager information is incorrectly split across page breaks\n\n## Description\nWhen generating documents that include NPS scheme and fund-manager details, the information is sometimes split incorrectly if a page break occurs within or between these sections. This results in incomplete or misaligned data on subsequent pages. The expected behavior is for the system to robustly handle page breaks, ensuring that NPS scheme and fund-manager information remains correctly grouped and displayed, even when spanning multiple pages.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `31b743b0e8ba` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### casparser/parsers/cdsl.py\n```python\n\"\"\"Dedicated CDSL parser.\n\nLike `nsdl_parser`, this consumes structured `Block`/`Cell` data from\n`pageobj.extract_blocks` and emits an `NSDLCASData` directly \u2014 no\ndetour through PROD's `process_cdsl_text`.\n\nCDSL CAS layout (in document order; absolute page numbers vary by\nholding count):\n\n - **Cover + account roster** \u2014 investor address block followed by the\n \"Account Type / Account Details / ISINs / Value\" summary table that\n enumerates each demat account and the MF-folios pseudo-account.\n - **Per-MF-folio descriptive blocks** \u2014 AMC Name, Scheme Name,\n Folio No, KYC, ISIN/UCC/RTA, one block group per folio. No\n balances here.\n - **Per-account transaction sections + holdings tables** \u2014 each\n section starts with `DP Name : ... BO ID :\n `, followed by transactions, then a\n `HOLDING STATEMENT AS ON` header and the holdings table itself\n (9-10 cells per row).\n - **`MUTUAL FUND UNITS HELD AS ON` table** \u2014 one row per MF folio\n with full P&L (scheme name, ISIN, folio, ARN code, units, NAV,\n invested, current value, TER, commission, profit, return%).\n - **Notes / footer** at the end.\n\nSome CDSL PDFs ship with a heavy Hindi-font overlay that makes\nroughly half the table cells unreadable by content-stream extraction\n(PROD fails on them too). The atom-level overlay filter in\n`extract.py` recovers most of these; the remainder need a smarter\nfont-aware extractor and are out of scope here.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom decimal import Decimal, InvalidOperation\nfrom typing import Dict, List, Optional, Tuple\n\nfrom casparser.enums import FileType\nfrom casparser.types import (\n DematAccount,\n DematOwner,\n Equity,\n MutualFund,\n NPSAccount,\n NPSScheme,\n NSDLCASData,\n StatementPeriod,\n)\n\nfrom . import pageobj\nfrom ._investor import extract_nsdl_cdsl_investor\nfrom .pageobj import Block\n\n# --- patterns ---\n\nISIN_RE = re.compile(r\"^[A-Z]{2}[0-9A-Z]{9}\\d$\")\nINF_ISIN_RE = re.compile(r\"^INF[0-9A-Z]{8}\\d$\")\nINE_ISIN_RE = re.compile(r\"^IN[E9][0-9A-Z]{8}\\d$\")\n# CDSL sometimes drops the leading zero on fractional values (e.g. a\n# `0.196` unit balance prints as `.196`), so the integer part is\n# optional when a decimal part is present.\nNUMERIC_RE = re.compile(r\"^-?(?:[\\d,]+(?:\\.\\d+)?|\\.\\d+)$\")\n# A long CDSL folio wraps its tail onto the next display line, which the\n# extractor emits as a separate cell \u2014 e.g. folio \"91012112582/0\" splits\n# into \"910121125\" | \"82/0\". The tail is a `/` token; we\n# splice it back onto the folio head (the on-page hyphen at the wrap is\n# only a line-break indicator, absent from the authoritative\n# \"Folio No :\" block).\nFOLIO_TAIL_RE = re.compile(r\"\\d+/\\d+\")\n\nPERIOD_RE = re.compile(\n r\"(?:for\\s+the\\s+period\\s+from|statement\\s+for\\s+the\\s+period\\s+from)\\s+\"\n r\"(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\\s+to\\s+(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\",\n re.I,\n)\n\nDEMAT_TYPE_RE = re.compile(r\"^(CDSL|NSDL)\\s+Demat\\s+Account\\s*$\", re.I)\nPAN_RE = re.compile(r\"(.+?)\\s*\\(\\s*PAN\\s*:\\s*([^)]+?)\\s*\\)\", re.I)\n\n# Page-2 summary row carries `DP Id: Client Id : `\n# (whitespace around the colons varies).\nSUMMARY_DPC_RE = re.compile(\n r\"DP\\s*Id\\s*:\\s*(\\S+?)\\s+Client\\s*Id\\s*:\\s*(\\d+)\",\n re.I,\n)\n# Per-account holdings header: `DP Name : DP ID : \n# CLIENT ID : `.\nSECTION_DPC_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+DP\\s*ID\\s*:\\s*(\\S+)\\s+CLIENT\\s*ID\\s*:\\s*(\\S+)\",\n re.I | re.S,\n)\n# Transaction-page header: `DP Name : BO ID : <16-char id>`.\n# The id concatenates DP ID + Client ID, both 8 chars. CDSL DP IDs are\n# numeric, NSDL DP IDs start with `IN`, so the 16-char field can be all\n# digits (CDSL) or two letters + 14 digits (NSDL).\nSECTION_BOID_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+(?:BO\\s*ID|DPID)\\s*:\\s*([A-Z0-9]{16})\",\n re.I | re.S,\n)\n\n# --- NPS section patterns ---\n# An NPS holding row's scheme name always begins with this marker.\nNPS_SCHEME_MARKER = \"nps trust\"\n# `NPS-SP : PROT PRAN ID : ` \u2014 service provider (CRA) + PRAN.\nNPS_SP_RE = re.compile(r\"NPS[-\\s]*SP\\s*:\\s*([A-Za-z0-9]+)\", re.I)\nNPS_PRAN_RE = re.compile(r\"PRAN\\s*ID\\s*:\\s*([A-Z0-9]+)\", re.I)\n# `Portfolio Value ` 56,05,171.60 as on 31-03-2026` \u2014 reported NPS total.\nNPS_VALUE_RE = re.compile(r\"Portfolio\\s+Value[^\\d]*([\\d,]+\\.\\d+)\", re.I)\n# Tier (\"TIER I\"/\"TIER II\") and asset class (\"SCHEME E/C/G/A\") in the name.\nNPS_TIER_RE = re.compile(r\"\\bTIER\\s*[-\\s]*(I{1,2}|1|2)\\b\", re.I)\nNPS_ASSET_RE = re.compile(r\"\\bSCHEME\\s+([A-Za-z])\\b\")\n# Coarse split between the two text columns (scheme name | fund manager).\n# The holding table has exactly two text columns and two numeric columns;\n# numerics are ordered (units, then nav), so only the text split needs an x\n# hint \u2014 deliberately loose, well inside the wide inter-column gap.\n_NPS_FUND_MGR_MIN_X = 1500.0\n\n\n# --- decimal helpers ---\n\n\ndef _to_decimal(text) -> Decimal:\n if text is None:\n return Decimal(0)\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return Decimal(0)\n try:\n return Decimal(s)\n except InvalidOperation:\n return Decimal(0)\n\n\ndef _opt_decimal(text) -> Optional[Decimal]:\n if text is None:\n return None\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return None\n try:\n return Decimal(s)\n except InvalidOperation:\n return None\n\n\ndef _looks_numeric(text: str) -> bool:\n s = text.strip()\n if not s:\n return False\n return bool(NUMERIC_RE.match(s))\n\n\ndef _rel_close(a: Decimal, b: Decimal, rel: Decimal = Decimal(\"0.005\")) -> bool:\n if b == 0:\n return abs(a) <= Decimal(\"0.01\")\n return abs(a - b) / abs(b) <= rel\n\n\ndef _resolve_cdsl_mf_pnl_returns(\n numerics: List[str],\n value: Decimal,\n invested: Optional[Decimal],\n has_distrib_col: bool,\n) -> Tuple[Optional[Decimal], Optional[Decimal]]:\n \"\"\"Assign profit and return% from the post-value numeric tail.\n\n Positional ``numerics[-2]`` / ``[-1]`` is wrong when the statement\n omits a printed profit column and only shows return% \u2014 identity\n ``value - invested`` picks profit when present; otherwise leave\n ``pnl`` unset and treat a small trailing % as ``return_``.\"\"\"\n if not has_distrib_col:\n return None, None\n\n value_idx = 3 if len(numerics) >= 4 else 2\n remaining = [_to_decimal(n) for n in numerics[value_idx + 1 :]]\n remaining = [r for r in remaining if r != 0]\n\n expected_pnl: Optional[Decimal] = None\n if invested is not None and invested > 0:\n expected_pnl = value - invested\n\n pnl: Optional[Decimal] = None\n ret: Optional[Decimal] = None\n\n if expected_pnl is not None:\n for r in remaining:\n if _rel_close(r, expected_pnl):\n pnl = r\n break\n if pnl is None and len(numerics) >= 6:\n pos_pnl = _opt_decimal(numerics[-2])\n if pos_pnl is not None and _rel_close(pos_pnl, expected_pnl):\n pnl = pos_pnl\n\n others = [r for r in remaining if r != pnl]\n if pnl is not None and others:\n ret = others[-1]\n elif pnl is None and expected_pnl is not None:\n for r in others:\n if abs(r) < Decimal(\"100\"):\n ret = r\n break\n elif len(numerics) >= 5:\n ret = _opt_decimal(numerics[-1])\n\n if pnl == 0:\n pnl = None\n if ret == 0:\n ret = None\n return pnl, ret\n\n\n# --- account key utilities ---\n\n\ndef _full_type(type_word: str) -> str:\n return f\"{type_word.upper()} Demat Account\"\n\n\ndef _account_key(type_word: str, dp_id: str, client_id: str) -> Tuple[str, str, str]:\n return (type_word.upper(), dp_id.strip(), client_id.strip())\n\n\ndef _split_bo_id(bo_id: str) -> Tuple[str, str, str]:\n \"\"\"16-char BO ID \u2192 `(type_word, dp_id, client_id)`.\n\n NSDL DP IDs start with `IN` (8 chars total), CDSL DP IDs are pure\n digits. Both followed by an 8-digit Client ID.\"\"\"\n if len(bo_id) != 16:\n return \"\", \"\", \"\"\n if bo_id[:2].upper() == \"IN\":\n return \"NSDL\", bo_id[:8], bo_id[8:]\n if bo_id.isdigit():\n return \"CDSL\", bo_id[:8], bo_id[8:]\n return \"\", \"\", \"\"\n\n\n# --- parser entry point ---\n\n\ndef _norm_tier(t: str) -> str:\n return {\"1\": \"I\", \"2\": \"II\"}.get(t.upper(), t.upper())\n\n\ndef _build_nps_scheme(cells: list) -> Optional[NPSScheme]:\n \"\"\"Build one NPSScheme from an accumulated holding-row cell buffer.\n\n A scheme row spans several extractor lines: two text columns (scheme\n name, fund manager) and two numeric cells (units, then nav). Text is\n grouped into the two columns by a coarse x split; the numeric cells are\n assigned by order (left = units, right = nav). value = units * nav.\n Rows without both numerics (e.g. redacted) are skipped.\n \"\"\"\n text_cells = [c for c in cells if c.text.strip() and not _looks_numeric(c.text)]\n num_cells = sorted((c for c in cells if _looks_numeric(c.text)), key=lambda c: c.x_left)\n name_cells = sorted(\n (c for c in text_cells if c.x_left < _NPS_FUND_MGR_MIN_X), key=lambda c: -c.y_top\n )\n fm_cells = sorted(\n (c for c in text_cells if c.x_left >= _NPS_FUND_MGR_MIN_X), key=lambda c: -c.y_top\n )\n scheme = \" \".join(c.text.replace(\"\\n\", \" \").strip() for c in name_cells).strip()\n scheme = re.sub(r\"\\s+\", \" \", scheme)\n if NPS_SCHEME_MARKER not in scheme.lower():\n return None\n if len(num_cells) < 2:\n return None # units / nav not present (redacted) \u2014 cannot form a holding\n fund_manager = \" \".join(c.text.replace(\"\\n\", \" \").strip() for c in fm_cells).strip()\n fund_manager = re.sub(r\"\\s+\", \" \", fund_manager) or None\n units = _to_decimal(num_cells[0].text)\n nav = _to_decimal(num_cells[1].text)\n tier = None\n if m := NPS_TIER_RE.search(scheme):\n tier = _norm_tier(m.group(1))\n asset_class = None\n if m := NPS_ASSET_RE.search(scheme):\n asset_class = m.group(1).upper()\n return NPSScheme(\n scheme=scheme,\n fund_manager=fund_manager,\n tier=tier,\n asset_class=asset_class,\n units=units,\n nav=nav,\n value=(units * nav).quantize(Decimal(\"0.01\")),\n )\n\n\ndef _parse_nps(blocks: List[Block]) -> Optional[NPSAccount]:\n \"\"\"Extract the NPS holdings section (if present) from a CDSL CAS.\n\n Holdings only \u2014 the NPS transaction statement is intentionally not\n parsed. Scans for the NPS `HOLDING STATEMENT` region (identified by its\n `NPS TRUST-` scheme rows) and reads scheme name / fund manager /\n units / nav; PRAN + NPS-SP + reported portfolio value from the section\n text. Returns None when the CAS has no NPS section.\n \"\"\"\n nps_sp: Optional[str] = None\n pran: Optional[str] = None\n value: Optional[Decimal] = None\n schemes: List[NPSScheme] = []\n mode: Optional[str] = None # None | \"txn\" | \"holding\"\n buf: list = []\n\n def flush() -> None:\n nonlocal buf\n if buf:\n sc = _build_nps_scheme(buf)\n if sc is not None:\n schemes.append(sc)\n buf = []\n\n for b in blocks:\n txt = b.text()\n low = txt.lower()\n if nps_sp is None and (m := NPS_SP_RE.search(txt)):\n nps_sp = m.group(1)\n if pran is None and (m := NPS_PRAN_RE.search(txt)):\n pran = m.group(1)\n if \"statement of transactions\" in low:\n flush()\n mode = \"txn\"\n continue\n if \"holding statement\" in low and \"as on\" in low:\n flush()\n mode = \"holding\"\n continue\n if \"portfolio value\" in low:\n # Closes the NPS holding region; capture the reported total only\n # when we are actually closing NPS holdings (schemes seen).\n if (schemes or buf) and (m := NPS_VALUE_RE.search(txt)):\n value = _to_decimal(m.group(1))\n flush()\n mode = None\n continue\n if \"nps investment summary\" in low:\n flush()\n mode = None\n continue\n if mode != \"holding\":\n continue\n starts_scheme = any(c.text.strip().lower().startswith(NPS_SCHEME_MARKER) for c in b.cells)\n if starts_scheme:\n flush()\n buf = list(b.cells)\n elif buf:\n buf.extend(b.cells)\n flush()\n\n if not schemes and value is None and nps_sp is None and pran is None:\n return None\n if value is None:\n value = sum((s.value for s in schemes), Decimal(0))\n return NPSAccount(pran=pran, nps_sp=nps_sp, value=value, schemes=schemes)\n\n\ndef parse_cdsl(\n pdf_path: str,\n password: str,\n file_type: FileType = FileType.CDSL,\n *,\n _doc=None,\n) -> NSDLCASData:\n atoms = pageobj.extract_atoms(pdf_path, password, _doc=_doc)\n blocks = pageobj.blocks_from_atoms(atoms)\n period = _find_period(blocks) or StatementPeriod(**{\"from\": \"\", \"to\": \"\"})\n\n # Phase 1: account roster from page 2 summary.\n accounts_by_key: Dict[Tuple[str, str, str], DematAccount] = {}\n ordered_accounts: List[DematAccount] = []\n mf_folios_account: Optional[DematAccount] = None\n pending_owners: List[DematOwner] = []\n\n for b in blocks:\n if b.page != 2:\n continue\n txt = b.text()\n ltxt = txt.lower()\n if \"in the single name of\" in ltxt or \"in the joint name\" in ltxt:\n pending_owners = []\n continue\n if PAN_RE.search(txt) and \"Mutual\" not in txt:\n for m in PAN_RE.finditer(txt):\n pending_owners.append(\n DematOwner(\n name=m.group(1).strip(),\n PAN=m.group(2).strip(),\n )\n )\n continue\n if _is_summary_demat_row(b):\n ac, key = _account_from_summary_row(b, pending_owners)\n if key not in accounts_by_key:\n accounts_by_key[key] = ac\n ordered_accounts.append(ac)\n continue\n if _is_summary_mf_folios_row(b):\n if mf_folios_account is None:\n mf_folios_account = _mf_folios_account_from_summary(b, pending_owners)\n ordered_accounts.append(mf_folios_account)\n continue\n\n # Phase 2: scheme-code \u2192 (ISIN, UCC, folio, name) map from the\n # descriptive MF blocks that follow the roster page. Their page\n # span depends on how many MF folios the investor holds; we\n # bound-scan from page 3 up to the start of the per-account\n # transaction section (detected via the `BO ID :` / `DPID :`\n # marker), and only consume blocks that match the descriptive\n # template (Scheme Name + Scheme Code + ISIN + UCC).\n scheme_meta: Dict[str, Dict[str, str]] = {}\n pending_scheme: Dict[str, str] = {}\n for b in blocks:\n if b.page < 3:\n continue\n if SECTION_BOID_RE.search(b.text()):\n break\n txt = b.text()\n if \"Scheme Name :\" in txt and \"Scheme Code :\" in txt:\n sm = re.search(\n r\"Scheme\\s*Name\\s*:\\s*(.+?)\\s+Scheme\\s*Code\\s*:\\s*(\\S+)\",\n txt,\n re.S,\n )\n if sm:\n pending_scheme = {\n \"scheme_name\": sm.group(1).replace(\"\\n\", \" \").strip(),\n \"scheme_code\": sm.group(2).strip(),\n }\n elif \"Folio No :\" in txt:\n fm = re.search(r\"Folio\\s*No\\s*:\\s*(\\S+)\", txt)\n if fm:\n pending_scheme[\"folio\"] = fm.group(1)\n elif \"ISIN :\" in txt and \"UCC\" in txt:\n im = re.search(r\"ISIN\\s*:\\s*(\\S+)\", txt)\n um = re.search(r\"UCC\\s*:\\s*([\\w/]+)?\", txt)\n if im and pending_scheme.get(\"scheme_code\"):\n pending_scheme[\"isin\"] = im.group(1)\n if um and um.group(1):\n pending_scheme[\"ucc\"] = um.group(1)\n scheme_meta[pending_schem\n... [truncated 13129 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-ede19d2e304e", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-ede19d2e304e", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "31b743b0e8ba5b6188cbdcc86eeb56a16afd4c77", "source_files": ["casparser/parsers/cdsl.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** CDSL/NSDL parser misclassifies leading-dot decimal numbers\n\n## Description\nWhen parsing CDSL or NSDL statements, numeric values that begin with a decimal point (e.g., `.196` instead of `0.196`) are incorrectly classified as text. This causes the row layout to shift unexpectedly and leads to an incorrect sum of holdings (\u03a3holdings) that does not match the actual balance. Expected behavior is for these leading-dot decimals to be recognized as valid numbers and parsed correctly, ensuring accurate balance calculations.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `dc6b4bad9a9d` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 1.0.0\n\nMajor release. The parsing backend was rewritten from scratch on\n[pypdfium2](https://github.com/pypdfium2-team/pypdfium2) (Apache-2.0 /\nBSD-3) and the four supported CAS issuers now each have a dedicated\nparser tuned to their template family.\n\n### Breaking changes\n\n- **pdfminer.six and PyMuPDF backends removed.** `casparser.read_cas_pdf`\n no longer dispatches between them. The `mupdf` / `fast` extras in\n `pyproject.toml` are gone. The `--force-pdfminer` CLI flag and the\n `force_pdfminer=` kwarg on `read_cas_pdf` are kept as no-ops; the\n kwarg emits a `DeprecationWarning` and is otherwise ignored.\n- **License simplified to pure MIT.** With the GPL/AGPL-licensed\n PyMuPDF dependency gone, the `licenses/` directory of GPL/AGPL\n copies has been removed. pypdfium2 is dual Apache-2.0 / BSD-3 and\n doesn't impose any copyleft obligation on users of casparser.\n- **Minimum Python is now 3.11.** 3.9 / 3.10 classifiers dropped from\n `pyproject.toml`.\n- **`CASData.investor_info` is now `Optional[InvestorInfo]`** (matches\n the `NSDLCASData.investor_info` shape that already existed). It is\n populated on every supported issuer, but consumers should still\n guard against the `None` case for unfamiliar templates.\n- **Internal `casparser.process` package removed.** The two helpers\n downstream code still imports from it are now at\n `casparser.parsers._classify` (`get_parsed_scheme_name`,\n `get_transaction_type`) and `casparser.parsers._isin` (`isin_search`).\n\n### New\n\n- **First-class NSDL and CDSL parsers.** Drops the regex-on-text\n approach the 0.8 NSDL/CDSL code used; the new parsers consume\n structured `Block`/`Cell` records directly from `pypdfium2`. Several\n bugs the v0.8 NSDL/CDSL code shipped with are no longer in scope\n (misplaced-UCC-as-folio on NSDL MF Holdings, space-merged\n folio+units cells on CDSL, the silently-dropped NSDL HDFC\n subaccount on CDSL multi-account statements, `Optional[Decimal]`\n comma-strip miss in the `MutualFund` validator).\n- **CAMS / KFin 2026 templates supported** out of the box. The newer\n CAMS SUMMARY template added an ISIN column the v0.8 regex didn't\n match; v1.0 parses all rows. The newer KFin SUMMARY template emits\n zero-balance schemes with single-space-separated trio cells that\n the v0.8 regex required `\\t\\t` between; v1.0 picks them up too.\n- **AMC-header detection extended** to include the `Fund House`\n suffix. v0.8's regex only matched `Mutual Fund` / `MF` suffixes,\n so schemes from a few newer AMCs whose names end in `Fund House`\n ended up bucketed under the previous AMC.\n- **ISIN / AMFI enrichment has a direct-ISIN fallback** path via\n `MFISINDb.direct_isin_lookup` for the case where multi-line\n `Registrar:` rendering corrupts the RTA token.\n- **Schedule 112A column 1b** (\"Share/Unit Transferred\") is emitted\n for FY2024-25 onward, per the AY 2025-26 ITR utility template. The\n Finance (No. 2) Act 2024 split the equity-LTCG regime on\n 23-Jul-2024; the 112A CSV now flags each transfer `BE`/`AE` against\n that date and splits an after-31-Jan-2018-acquired fund into\n separate rows when it was sold on both sides of the cutoff. Older\n FYs keep the 14-column layout their utility expects.\n- **Cost Inflation Index extended to FY2025-26 (376)** and the\n FY2024-25 value corrected from `365` to the CBDT-notified `363`\n (the wrong value slightly mis-indexed debt-fund LTCG cost of\n acquisition for FY2024-25 sales).\n\n### Fixed\n\n- **CAMS SUMMARY `valuation.date` no longer mis-parses to year 201**\n (was a column-boundary bug \u2014 the NAVDate column treated as\n right-aligned with a 42pt width clipped the trailing year digit,\n then Pydantic mis-coerced the `01-Jan-201` string).\n- **CDSL multi-account statements** (5+ demat accounts on one PDF) are\n now parsed correctly. Earlier the page-3+ scan only kicked in from\n page 8, dropping holdings sections that landed on pages 4-7.\n- **CDSL MF holdings** rows with `DIRECT` (or any non-`ARN-XXXX`\n distribution-mode token) now correctly populate `pnl` and `return_`.\n\n## 0.9.0 - 2026-05-22\n- Add support for CDSL statements\n- Drop support for Python 3.9 and 3.10; minimum supported version is now 3.11\n- Support PyMuPDF >= 1.25 (1.27.x tested). Older `<1.25` pin removed.\n- Bump `casparser-isin` to `>= 2026.5.1` (new DB format v2 with\n `sebi_category`/`last_seen` columns; ISIN-first lookup priority).\n- Relax other dependency pins (click, colorama, rich, pdfminer.six).\n- Fix `MutualFund.fix_float` pydantic validator so the aliased `return`\n field (Python attribute `return_`) also gets the comma-stripping\n treatment; previously NSDL MF folio rows with a return value of\n 1 lakh or more would fail Decimal validation.\n- Parser robustness fixes for PyMuPDF 1.25+ text extraction quirks\n (all superseded in 1.0.0 by the pypdfium2 rewrite, kept here for\n the historical record).\n\n## 0.8.1 - 2025-09-21\n- NSDL parser bug fixes\n\n## 0.8.0 - 2025-02-26\n- NSDL support: first version\n- various bug fixes\n\n## 0.7.4 - 2023-10-04\n- (fix) fix broken scheme names\n\n## 0.7.3 - 2023-09-26\n- (new) Add support for parsing nominee details (available in `Folio.nominees`)\n- (fix) fix empty PAN in certain cases\n\n## 0.7.2 - 2023-09-19\n- Bug fixes\n - Exclude short term capital gains (STCG) from 112A reports\n - Fix advisor code parsing\n\n# 0.7.1 - 2023-09-06\n- fix bug where long scheme names were getting truncated\n\n## 0.7.0 - 2023-09-03\n- update pydantic to v2\n\n## 0.6.1 - 2023-04-04\n- update CII data till FY2022-23\n- bug fixes\n\n## 0.6.0 - 2023-02-20\n- use pydantic models for better data validation\n\n## 0.5.5 - 2022-08-06\n- bug fix with MuPDF parser\n\n## 0.5.4 - 2022-02-01\n- bug fix in CAS summary statement parser\n\n## 0.5.3 - 2021-08-21\n- support for generating csv files for capital gains in 112A format for income tax filing\n- various bug fixes\n\n## 0.5.2 - 2021-08-11\n- fix crash while generating capital gains reports on dividend payout funds\n- rework capital gains algorithm\n- add `advisor` column in transactions csv\n- various bug fixes\n\n## 0.5.1 - 2021-07-21\n- gains: PnL report\n- support for migration of Franklin Templeton funds to CAMS RTA\n- various bug fixes\n\n## 0.5.0 - 2021-07-02\n- Support for calculating capital gains from detailed CAS statements\n- support for parsing Tax Deducted at Source (`TDS`) transactions\n\n## 0.4.8 - 2021-06-27\n- `REVERSAL` TransactionType to indicate reverted/rejected transactions\n- convert all enums to strEnums for better readability [(#35)](https://github.com/codereverser/casparser/pull/35)\n- fix issue with parsing multi-line transactions\n\n## 0.4.7 - 2021-06-01\n\n- Minor bug fixes in summary-statement parser.\n- cli now uses [rich](http://rich.readthedocs.io/) for console output.\n- Use poetry for dependency management and deployment.\n- **BREAKING CHANGE**: Table output choices have been removed.\n `-s/--summary` is a flag and doesn't accept any additional arguments.\n- Support for folios without PAN (#28).\n- add support for new style dividend transactions after IDCW renaming.\n- improved parser for transaction entries.\n\n## 0.4.6 - 2021-04-04\n\n- New `sort_transactions` option in `casparser.read_cas_pdf` (and `--sort` flag in CLI)\n to fix transactions (and balances) for schemes with non-chronological order.\n- support negative balances in transactions\n\n## 0.4.5 - 2021-03-20\n\n- Support for segregated portfolio transactions [ credits: [abhishekjain-qb](https://github.com/abhishekjain-qb) ]\n\n## 0.4.4 - 2021-02-07\n\n- CSV output fixes\n - better csv output format for summary CAS statements.\n - option to output only summary information for detailed statements\n (`-s fancy_grid -o output.csv`)\n\n## 0.4.3 - 2021-01-30\n\n- ISIN, AMFI code mapping for schemes (**beta**)\n\n## 0.4.2 - 2021-01-22\n\n- fixes unicode issues in windows\n- supports negative scheme balances\n- better scheme name parsing\n- fixes dividend transaction parsing\n\n\n## 0.4.1 - 2021-01-13\n\n- hotfix for parsing folios without KYC details\n\n## 0.4.0 - 2021-01-08\n\n- adds support for parsing summary statements from CAMS/KARVY (**beta**)\n- minor bug fixes in CSV file generation\n\n## 0.3.9 - 2021-01-01\n\n- Support for classifying transactions\n\n## 0.3.8 - 2020-12-29\n\n- Support for parsing folios without PAN/KYC details\n\n## 0.3.7 - 2020-12-24\n\n- Support for parsing dividend transactions\n\n## 0.3.6 - 2020-12-21\n\n- Support for parsing folios without advisor\n\n## 0.3.5 - 2020-11-13\n\n- Support for parsing scheme's latest nav\n- Replaced `texttable` with `tabulate` for more cli output formats\n- Added more test cases\n\n## 0.3.4 - 2020-11-08\n\n- Support for parsing scheme valuation\n- Parser code refactor (transparent to user)\n\n## 0.3.3 - 2020-10-31\n\n- Added `balance` to Transaction\n- Added test cases with travis-ci and codecov support\n- minor bug fixes while parsing kfintech cas files\n\n## 0.3.2 - 2020-10-29\n\n- minor bug fixes\n\n## 0.3.1 - 2020-10-26\n\n- re-release 0.3.0 : Minor bug fix\n\n## 0.3.0 - 2020-10-25\n\n- **Breaking Change**: In order to preserve the order of entries, during format\n conversion to other data types like json., `folios` is a list instead of dict.\n- Added a second parser based on [PyMuPDF](https://github.com/pymupdf/PyMuPDF) /\n[MuPDF](https://mupdf.com/) - ~15-20x faster compared to pure-python pdfminer.\n- Added AMC detection (accessible via `amc` property of folio)\n- CLI summary now includes the number of transactions processed.\n\n## 0.2.1 - 2020-10-23\n\n- `read_cas_pdf` now supports more input types\n- better cli summary output\n- fixed investor info parsing where mobile numbers don't have country code\n- updated dependencies\n\n## 0.2.0 - 2020-10-15\n\n- removed support for python versions <3.8\n- Better investor info parser\n\n## 0.1.2 - 2020-10-14\n\n- Support for parsing investor info\n\n## 0.1.1 - 2020-10-14\n\n- Support for parsing folios without PAN\n\n## 0.1.0 - 2020-10-11\n\n- Initial release\n\n```\n\n### casparser/parsers/cdsl.py\n```python\n\"\"\"Dedicated CDSL parser.\n\nLike `nsdl_parser`, this consumes structured `Block`/`Cell` data from\n`pageobj.extract_blocks` and emits an `NSDLCASData` directly \u2014 no\ndetour through PROD's `process_cdsl_text`.\n\nCDSL CAS layout (in document order; absolute page numbers vary by\nholding count):\n\n - **Cover + account roster** \u2014 investor address block followed by the\n \"Account Type / Account Details / ISINs / Value\" summary table that\n enumerates each demat account and the MF-folios pseudo-account.\n - **Per-MF-folio descriptive blocks** \u2014 AMC Name, Scheme Name,\n Folio No, KYC, ISIN/UCC/RTA, one block group per folio. No\n balances here.\n - **Per-account transaction sections + holdings tables** \u2014 each\n section starts with `DP Name : ... BO ID :\n `, followed by transactions, then a\n `HOLDING STATEMENT AS ON` header and the holdings table itself\n (9-10 cells per row).\n - **`MUTUAL FUND UNITS HELD AS ON` table** \u2014 one row per MF folio\n with full P&L (scheme name, ISIN, folio, ARN code, units, NAV,\n invested, current value, TER, commission, profit, return%).\n - **Notes / footer** at the end.\n\nSome CDSL PDFs ship with a heavy Hindi-font overlay that makes\nroughly half the table cells unreadable by content-stream extraction\n(PROD fails on them too). The atom-level overlay filter in\n`extract.py` recovers most of these; the remainder need a smarter\nfont-aware extractor and are out of scope here.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom decimal import Decimal, InvalidOperation\nfrom typing import Dict, List, Optional, Tuple\n\nfrom casparser.enums import FileType\nfrom casparser.types import (\n DematAccount,\n DematOwner,\n Equity,\n MutualFund,\n NSDLCASData,\n StatementPeriod,\n)\n\nfrom . import pageobj\nfrom ._investor import extract_nsdl_cdsl_investor\nfrom .pageobj import Block\n\n# --- patterns ---\n\nISIN_RE = re.compile(r\"^[A-Z]{2}[0-9A-Z]{9}\\d$\")\nINF_ISIN_RE = re.compile(r\"^INF[0-9A-Z]{8}\\d$\")\nINE_ISIN_RE = re.compile(r\"^IN[E9][0-9A-Z]{8}\\d$\")\nNUMERIC_RE = re.compile(r\"^-?[\\d,]+(?:\\.\\d+)?$\")\n\nPERIOD_RE = re.compile(\n r\"(?:for\\s+the\\s+period\\s+from|statement\\s+for\\s+the\\s+period\\s+from)\\s+\"\n r\"(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\\s+to\\s+(\\d{2}[-/][A-Za-z0-9]{2,3}[-/]\\d{4})\",\n re.I,\n)\n\nDEMAT_TYPE_RE = re.compile(r\"^(CDSL|NSDL)\\s+Demat\\s+Account\\s*$\", re.I)\nPAN_RE = re.compile(r\"(.+?)\\s*\\(\\s*PAN\\s*:\\s*([^)]+?)\\s*\\)\", re.I)\n\n# Page-2 summary row carries `DP Id: Client Id : `\n# (whitespace around the colons varies).\nSUMMARY_DPC_RE = re.compile(\n r\"DP\\s*Id\\s*:\\s*(\\S+?)\\s+Client\\s*Id\\s*:\\s*(\\d+)\",\n re.I,\n)\n# Per-account holdings header: `DP Name : DP ID : \n# CLIENT ID : `.\nSECTION_DPC_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+DP\\s*ID\\s*:\\s*(\\S+)\\s+CLIENT\\s*ID\\s*:\\s*(\\S+)\",\n re.I | re.S,\n)\n# Transaction-page header: `DP Name : BO ID : <16-char id>`.\n# The id concatenates DP ID + Client ID, both 8 chars. CDSL DP IDs are\n# numeric, NSDL DP IDs start with `IN`, so the 16-char field can be all\n# digits (CDSL) or two letters + 14 digits (NSDL).\nSECTION_BOID_RE = re.compile(\n r\"DP\\s*Name\\s*:\\s*(.+?)\\s+(?:BO\\s*ID|DPID)\\s*:\\s*([A-Z0-9]{16})\",\n re.I | re.S,\n)\n\n\n# --- decimal helpers ---\n\n\ndef _to_decimal(text) -> Decimal:\n if text is None:\n return Decimal(0)\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return Decimal(0)\n try:\n return Decimal(s)\n except InvalidOperation:\n return Decimal(0)\n\n\ndef _opt_decimal(text) -> Optional[Decimal]:\n if text is None:\n return None\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return None\n try:\n return Decimal(s)\n except InvalidOperation:\n return None\n\n\ndef _looks_numeric(text: str) -> bool:\n s = text.strip()\n if not s:\n return False\n return bool(NUMERIC_RE.match(s))\n\n\n# --- account key utilities ---\n\n\ndef _full_type(type_word: str) -> str:\n return f\"{type_word.upper()} Demat Account\"\n\n\ndef _account_key(type_word: str, dp_id: str, client_id: str) -> Tuple[str, str, str]:\n return (type_word.upper(), dp_id.strip(), client_id.strip())\n\n\ndef _split_bo_id(bo_id: str) -> Tuple[str, str, str]:\n \"\"\"16-char BO ID \u2192 `(type_word, dp_id, client_id)`.\n\n NSDL DP IDs start with `IN` (8 chars total), CDSL DP IDs are pure\n digits. Both followed by an 8-digit Client ID.\"\"\"\n if len(bo_id) != 16:\n return \"\", \"\", \"\"\n if bo_id[:2].upper() == \"IN\":\n return \"NSDL\", bo_id[:8], bo_id[8:]\n if bo_id.isdigit():\n return \"CDSL\", bo_id[:8], bo_id[8:]\n return \"\", \"\", \"\"\n\n\n# --- parser entry point ---\n\n\ndef parse_cdsl(\n pdf_path: str,\n password: str,\n file_type: FileType = FileType.CDSL,\n *,\n _doc=None,\n) -> NSDLCASData:\n atoms = pageobj.extract_atoms(pdf_path, password, _doc=_doc)\n blocks = pageobj.blocks_from_atoms(atoms)\n period = _find_period(blocks) or StatementPeriod(**{\"from\": \"\", \"to\": \"\"})\n\n # Phase 1: account roster from page 2 summary.\n accounts_by_key: Dict[Tuple[str, str, str], DematAccount] = {}\n ordered_accounts: List[DematAccount] = []\n mf_folios_account: Optional[DematAccount] = None\n pending_owners: List[DematOwner] = []\n\n for b in blocks:\n if b.page != 2:\n continue\n txt = b.text()\n ltxt = txt.lower()\n if \"in the single name of\" in ltxt or \"in the joint name\" in ltxt:\n pending_owners = []\n continue\n if PAN_RE.search(txt) and \"Mutual\" not in txt:\n for m in PAN_RE.finditer(txt):\n pending_owners.append(\n DematOwner(\n name=m.group(1).strip(),\n PAN=m.group(2).strip(),\n )\n )\n continue\n if _is_summary_demat_row(b):\n ac, key = _account_from_summary_row(b, pending_owners)\n if key not in accounts_by_key:\n accounts_by_key[key] = ac\n ordered_accounts.append(ac)\n continue\n if _is_summary_mf_folios_row(b):\n if mf_folios_account is None:\n mf_folios_account = _mf_folios_account_from_summary(b, pending_owners)\n ordered_accounts.append(mf_folios_account)\n continue\n\n # Phase 2: scheme-code \u2192 (ISIN, UCC, folio, name) map from the\n # descriptive MF blocks that follow the roster page. Their page\n # span depends on how many MF folios the investor holds; we\n # bound-scan from page 3 up to the start of the per-account\n # transaction section (detected via the `BO ID :` / `DPID :`\n # marker), and only consume blocks that match the descriptive\n # template (Scheme Name + Scheme Code + ISIN + UCC).\n scheme_meta: Dict[str, Dict[str, str]] = {}\n pending_scheme: Dict[str, str] = {}\n for b in blocks:\n if b.page < 3:\n continue\n if SECTION_BOID_RE.search(b.text()):\n break\n txt = b.text()\n if \"Scheme Name :\" in txt and \"Scheme Code :\" in txt:\n sm = re.search(\n r\"Scheme\\s*Name\\s*:\\s*(.+?)\\s+Scheme\\s*Code\\s*:\\s*(\\S+)\",\n txt,\n re.S,\n )\n if sm:\n pending_scheme = {\n \"scheme_name\": sm.group(1).replace(\"\\n\", \" \").strip(),\n \"scheme_code\": sm.group(2).strip(),\n }\n elif \"Folio No :\" in txt:\n fm = re.search(r\"Folio\\s*No\\s*:\\s*(\\S+)\", txt)\n if fm:\n pending_scheme[\"folio\"] = fm.group(1)\n elif \"ISIN :\" in txt and \"UCC\" in txt:\n im = re.search(r\"ISIN\\s*:\\s*(\\S+)\", txt)\n um = re.search(r\"UCC\\s*:\\s*([\\w/]+)?\", txt)\n if im and pending_scheme.get(\"scheme_code\"):\n pending_scheme[\"isin\"] = im.group(1)\n if um and um.group(1):\n pending_scheme[\"ucc\"] = um.group(1)\n scheme_meta[pending_scheme[\"scheme_code\"]] = dict(pending_scheme)\n pending_scheme = {}\n\n # Phase 3: walk all post-cover pages for holdings tables.\n # We skip pages 1-2 (cover + roster) because the roster lines\n # contain CDSL/NSDL identifiers that would otherwise look like\n # section headers; the dispatch logic below handles the rest.\n cur_account: Optional[DematAccount] = None\n cur_mode: Optional[str] = None # 'equities' | 'mf_holdings'\n\n for b in blocks:\n if b.page < 3:\n continue\n txt = b.text()\n ltxt = txt.lower()\n\n # Per-account section header \u2014 `DP Name : ... BO ID : ...`\n # or `DP Name : ... DPID : ...` (NSDL variant) form.\n m = SECTION_BOID_RE.search(txt)\n if m:\n broker = m.group(1).strip()\n bo_id = m.group(2)\n type_word, dp_id, client_id = _split_bo_id(bo_id)\n if type_word:\n ac_key = _account_key(type_word, dp_id, client_id)\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Or \"DP Name : ... DP ID : ... CLIENT ID : ...\"\n m = SECTION_DPC_RE.search(txt)\n if m:\n type_word = \"CDSL\"\n if \"NSDL\" in txt.upper() and \"CDSL\" not in txt.upper():\n type_word = \"NSDL\"\n broker, dp_id, client_id = m.groups()\n ac_key = _account_key(type_word, dp_id.strip(), client_id.strip())\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n continue\n\n # Transaction-statement section \u2014 switch OFF holdings mode so\n # transaction rows aren't parsed as equity rows.\n if \"statement of transactions\" in ltxt:\n cur_mode = None\n continue\n\n # Holdings section markers\n if \"holding statement\" in ltxt and \"as on\" in ltxt:\n cur_mode = \"equities\"\n continue\n if \"mutual fund units held as on\" in ltxt:\n cur_account = mf_folios_account\n cur_mode = \"mf_holdings\"\n continue\n\n # Skip column-header rows\n if _is_holdings_header(b) or _is_total_row(b):\n continue\n\n # Holdings rows\n if cur_account is None or cur_mode is None:\n continue\n if cur_mode == \"equities\":\n row = _parse_holdings_row(b)\n if row is None:\n pass\n else:\n isin, name, num_shares, price, value = row\n # CDSL Demat statements list ETFs (ISIN starting with\n # INF) in the same holdings table as equities, but\n # they're semantically mutual-fund units. Route them\n # to the mutual_funds list to mirror PROD's\n # classification.\n if INF_ISIN_RE.match(isin):\n cur_account.mutual_funds.append(\n MutualFund(\n name=name,\n isin=isin,\n balance=num_shares,\n nav=price,\n value=value,\n )\n )\n else:\n cur_account.equities.append(\n Equity(\n name=name,\n isin=isin,\n num_shares=num_shares,\n price=price,\n value=value,\n )\n )\n elif cur_mode == \"mf_holdings\":\n mf = _parse_mf_holdings_row(b, scheme_meta)\n if mf:\n cur_account.mutual_funds.append(mf)\n\n return NSDLCASData(\n statement_period=period,\n accounts=ordered_accounts,\n investor_info=extract_nsdl_cdsl_investor(\n pdf_path,\n password,\n _atoms=atoms,\n ),\n file_type=file_type,\n )\n\n\n# --- summary-row recognisers (page 2) ---\n\n\ndef _is_summary_demat_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n if not DEMAT_TYPE_RE.match(block.cells[0].text.strip()):\n return False\n return bool(SUMMARY_DPC_RE.search(block.cells[1].text))\n\n\ndef _is_summary_mf_folios_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n return bool(re.match(r\"^Mutual\\s+Fund\\s+Folios\", block.cells[0].text.strip(), re.I))\n\n\ndef _account_from_summary_row(\n block: Block, owners: List[DematOwner]\n) -> Tuple[DematAccount, Tuple[str, str, str]]:\n type_word = DEMAT_TYPE_RE.match(block.cells[0].text.strip()).group(1).upper()\n broker_dp = block.cells[1].text\n lines = [ln.strip() for ln in broker_dp.split(\"\\n\") if ln.strip()]\n broker = lines[0] if lines else \"\"\n dpc = SUMMARY_DPC_RE.search(broker_dp)\n dp_id = dpc.group(1) if dpc else \"\"\n client_id = dpc.group(2) if dpc else \"\"\n folios = int(_to_decimal(block.cells[2].text))\n balance = _to_decimal(block.cells[3].text)\n ac = DematAccount(\n name=broker,\n type=_full_type(type_word),\n dp_id=dp_id,\n client_id=client_id,\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n return ac, _account_key(type_word, dp_id, client_id)\n\n\ndef _mf_folios_account_from_summary(block: Block, owners: List[DematOwner]) -> DematAccount:\n folios_m = re.search(r\"(\\d+)\", block.cells[1].text)\n folios = int(folios_m.group(1)) if folios_m else 0\n balance = _to_decimal(block.cells[3].text)\n return DematAccount(\n name=\"Mutual Fund Folios\",\n type=\"Mutual Fund Folios\",\n dp_id=\"\",\n client_id=\"\",\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n )\n\n\n# --- helpers ---\n\n\ndef _find_period(blocks: List[Block]) -> Optional[StatementPeriod]:\n for b in blocks:\n m = PERIOD_RE.search(b.text())\n if m:\n return StatementPeriod(**{\"from\": m.group(1), \"to\": m.group(2)})\n return None\n\n\ndef _is_holdings_header(block: Block) -> bool:\n \"\"\"Block has no ISIN and looks like a column-label row.\"\"\"\n txt = block.text()\n if re.search(r\"\\b(IN[EF9][0-9A-Z]{8}\\d)\\b\", txt, re.I):\n return False\n ltxt = txt.lower().replace(\"\\n\", \" \").replace(\"\\t\\t\", \" \")\n if \"isin\" in ltxt and (\"security\" in ltxt or \"scheme name\" in ltxt):\n return True\n if \"current\" in ltxt and \"bal\" in ltxt and \"market\" in ltxt:\n return True\n return False\n\n\ndef _is_total_row(block: Block) -> bool:\n first = block.cells[0].text.strip().lower() if block.cells else \"\"\n return first in (\"sub total\", \"total\", \"grand total\")\n\n\n# --- equity holdings row ---\n\n\ndef _parse_holdings_row(block: Block) -> Optional[Tuple[str, str, Decimal, Decimal, Decimal]]:\n \"\"\"CDSL holdings row \u2192 `(isin, name, num_shares, price, value)`.\n\n Column layout (post-`HOLDING STATEMENT`):\n ISIN | Security | Current Bal | Frozen Bal | Pledge Bal |\n Pledge Setup Bal | Free Bal | Market Price | Value (`)\n\n A few rows have a leading '@' marker cell between ISIN and name\n (suspended issue notation). Rows with all-`--` quantity cells\n (rights entitlements that haven't been exercised) are still\n parsed \u2014 `_to_decimal` maps `--` to 0. We use position-based\n assignment, not the last-three-numerics heuristic, because some\n rows have only 2 numeric cells (price + value) when all balance\n columns are `--`.\"\"\"\n if not block.cells:\n return None\n first = block.cells[0].text.strip()\n if not ISIN_RE.match(first):\n return None\n isin = first\n\n # Find the data-cell boundary: the first cell after ISIN whose\n # text is a number or `--`. Everything between ISIN and that cell\n # is part of the security name (PDF renderer somet\n... [truncated 4475 chars]\n\n```\n\n### casparser/parsers/nsdl.py\n```python\n\"\"\"Dedicated NSDL parser.\n\nConsumes structured `Block`/`Cell` data from `pageobj.extract_blocks`\nand produces an `NSDLCASData` directly \u2014 no detour through PROD's\n`process_nsdl_text` and its regex tokenisation.\n\nSource-of-truth strategy:\n\n 1. **Page 2 carries the canonical account roster** in a small summary\n table \u2014 one row per demat / MF-folio account with type, broker,\n DP ID, Client ID, ISIN/scheme count, and balance. We bootstrap\n accounts from here. This avoids the \"false header\" pollution that\n comes from scanning every page for the phrase \"Demat Account\"\n (footers, footnotes, paragraph 6/10/etc. all mention it).\n\n 2. **Per-account section headers** match an account in the roster\n by `(dp_id, client_id)` and become the cursor for subsequent\n equity / MF / bond rows in that section.\n\n 3. **\"Mutual Fund Folios (F)\" detailed table** routes to the\n MF-folio pseudo-account. Rows use x-position-anchored columns\n so the misplaced lone-digit UCC NSDL occasionally renders in\n the units column gets recognised as an anomaly and folded back\n into `ucc`, not into the numeric fields.\n\nDecimals are parsed at the parser level, stripping Indian-format\ncommas, so we don't depend on the `MutualFund.fix_float` validator\n(which has a bug where aliased fields with `Optional[Decimal]`\nannotation slip past comma-stripping).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom dataclasses import dataclass\nfrom decimal import Decimal, InvalidOperation\nfrom typing import Dict, List, Optional, Tuple\n\nfrom casparser.enums import FileType\nfrom casparser.types import (\n Bond,\n DematAccount,\n DematOwner,\n Equity,\n MutualFund,\n NSDLCASData,\n StatementPeriod,\n)\n\nfrom . import pageobj\nfrom ._investor import extract_nsdl_cdsl_investor\nfrom .pageobj import Block, Cell\n\n# --- patterns ---\n\nISIN_RE = re.compile(r\"^[A-Z]{2}[0-9A-Z]{9}\\d$\")\nINF_ISIN_RE = re.compile(r\"^INF[0-9A-Z]{8}\\d$\")\nINE_ISIN_RE = re.compile(r\"^IN[E9][0-9A-Z]{8}\\d$\")\nNUMERIC_RE = re.compile(r\"^-?[\\d,]+(?:\\.\\d+)?$\")\n\nPERIOD_RE = re.compile(\n r\"(?:for\\s+the\\s+period\\s+from|statement\\s+for\\s+the\\s+period\\s+from)\\s+\"\n r\"(\\d{2}-[A-Za-z]{3}-\\d{4})\\s+to\\s+(\\d{2}-[A-Za-z]{3}-\\d{4})\",\n re.I,\n)\n\nDEMAT_TYPE_RE = re.compile(r\"^(NSDL|CDSL)\\s+Demat\\s+Account\\s*$\", re.I)\nDP_CLIENT_RE = re.compile(\n r\"DP\\s*ID\\s*:?\\s*(\\S+?)\\s+Client\\s*ID\\s*:?\\s*(\\d+)\",\n re.I,\n)\nPAN_RE = re.compile(r\"(.+?)\\s*\\(PAN\\s*:\\s*([^)]+)\\)\", re.I)\nMF_FOLIOS_HEADER_RE = re.compile(r\"^Mutual\\s+Fund\\s+Folios\\b\", re.I)\n\n\n# --- decimal helpers ---\n\n\ndef _to_decimal(text) -> Decimal:\n if text is None:\n return Decimal(0)\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return Decimal(0)\n try:\n return Decimal(s)\n except InvalidOperation:\n return Decimal(0)\n\n\ndef _opt_decimal(text) -> Optional[Decimal]:\n if text is None:\n return None\n s = str(text).replace(\",\", \"\").strip()\n if not s or s in (\"-\", \"--\", \"N.A\", \"NA\"):\n return None\n try:\n return Decimal(s)\n except InvalidOperation:\n return None\n\n\ndef _looks_numeric(text: str) -> bool:\n s = text.strip()\n if not s:\n return False\n return bool(NUMERIC_RE.match(s))\n\n\n# --- column anchors (x_left ranges) for the detailed MF Holdings table ---\n\n\n@dataclass(frozen=True)\nclass _MFHoldingsCols:\n # x_left bands for the 10 columns of the detailed MF Holdings\n # table. Each band must not overlap its neighbour AND must cover\n # the full range a cell's `x_left` can drift across \u2014 PDFium\n # rounds glyph positions slightly differently across fixtures, so\n # bands are deliberately wider than the visual column width\n # (gap-to-gap rather than glyph-to-glyph). The \"units\" band reaches\n # ~260 because the units glyph in some NSDL CAS variants starts at\n # x\u2248225 and right-aligns; without the wider window the units cell\n # falls into the inter-column gap and reads as 0.\n cols = (\n (\"isin_ucc\", 15, 75),\n (\"name\", 75, 150),\n (\"folio\", 150, 200),\n (\"units\", 200, 260),\n (\"avg_cost\", 260, 310),\n (\"total_cost\", 310, 375),\n (\"current_nav\", 375, 425),\n (\"current_value\", 425, 480),\n (\"pnl\", 480, 555),\n (\"returns\", 555, 600),\n )\n\n def assign(self, cell: Cell) -> Optional[str]:\n for key, lo, hi in self.cols:\n if lo <= cell.x_left < hi:\n return key\n return None\n\n\n_MF_HOLDINGS = _MFHoldingsCols()\n\n\n# --- column anchors for the summary Corporate-Bonds table ---\n#\n# The NSDL-flavour bonds table on a demat-account page renders 8 data\n# cells per row. Two of them ('frequency' text + 'coupon rate' numeric)\n# share an x-band so they can't be distinguished by x alone \u2014 see\n# `_parse_bond_summary_row` for how the text/numeric discriminator is\n# applied within that band.\n@dataclass(frozen=True)\nclass _BondSummaryCols:\n cols = (\n (\"isin\", 15, 80),\n (\"name\", 80, 175),\n (\"coupon_band\", 175, 240), # frequency (text) + coupon (numeric)\n (\"maturity\", 240, 310),\n (\"num_bonds\", 310, 390),\n (\"face_value\", 390, 510),\n (\"value\", 510, 600),\n )\n\n def assign(self, cell: Cell) -> Optional[str]:\n for key, lo, hi in self.cols:\n if lo <= cell.x_left < hi:\n return key\n return None\n\n\n_BOND_SUMMARY = _BondSummaryCols()\n\n\n# --- account key utilities ---\n\n\ndef _full_type(type_word: str) -> str:\n \"\"\"`NSDL`/`CDSL` -> `NSDL Demat Account`/`CDSL Demat Account` to\n match the convention used elsewhere in the codebase.\"\"\"\n return f\"{type_word.upper()} Demat Account\"\n\n\ndef _account_key(type_word: str, dp_id: str, client_id: str) -> Tuple[str, str, str]:\n return (type_word.upper(), dp_id.strip(), client_id.strip())\n\n\n# --- parser entry point ---\n\n\ndef parse_nsdl(\n pdf_path: str,\n password: str,\n file_type: FileType = FileType.NSDL,\n *,\n _doc=None,\n) -> NSDLCASData:\n # Extract atoms once, then derive both the structured Blocks the\n # holdings parser needs and the investor info from the same pages.\n atoms = pageobj.extract_atoms(pdf_path, password, _doc=_doc)\n blocks = pageobj.blocks_from_atoms(atoms)\n period = _find_period(blocks) or StatementPeriod(**{\"from\": \"\", \"to\": \"\"})\n\n # Phase 1: bootstrap accounts from page-2 summary table.\n accounts_by_key: Dict[Tuple[str, str, str], DematAccount] = {}\n ordered_accounts: List[DematAccount] = []\n mf_folios_account: Optional[DematAccount] = None\n\n pending_owners: List[DematOwner] = [] # owners harvested from\n # the most recent 'in the (single|joint) name of' header; consumed\n # by the next summary-demat row and reset on each new header.\n\n for b in blocks:\n if b.page != 2:\n continue\n txt = b.text()\n ltxt = txt.lower()\n if (\n \"in the single name of\" in ltxt\n or \"in the joint names of\" in ltxt\n or \"in the joint name of\" in ltxt\n ):\n pending_owners = []\n continue\n # Capture owner names that follow.\n if PAN_RE.search(txt):\n # `name1 (PAN:...)\\nname2 (PAN:...)` is one cell with \\n.\n for m in PAN_RE.finditer(txt):\n pending_owners.append(\n DematOwner(\n name=m.group(1).strip(),\n PAN=m.group(2).strip(),\n )\n )\n continue\n # Summary demat-account row\n if _is_summary_demat_row(b):\n ac, key = _account_from_summary_row(b, list(pending_owners))\n if key not in accounts_by_key:\n accounts_by_key[key] = ac\n ordered_accounts.append(ac)\n continue\n # Summary MF Folios row\n if _is_summary_mf_folios_row(b):\n if mf_folios_account is None:\n mf_folios_account = _mf_folios_account_from_summary(b, list(pending_owners))\n ordered_accounts.append(mf_folios_account)\n continue\n\n # Phase 2: walk all blocks; identify per-account section headers\n # and parse subsequent holdings into the matching account.\n #\n # `cur_section` (equities / mfunds / bonds) is set by the small\n # section-marker blocks ('Equity Shares', 'Mutual Funds (M)',\n # 'Corporate Bonds (C)' etc.) and disambiguates the otherwise-\n # identical 18-cell detailed-table header \u2014 without it, MF and\n # bond rows on a CDSL detailed page get misrouted into equities.\n # `cur_mode` is the final routing key (one of\n # 'equities_summary', 'equities_detailed', 'mfunds_summary',\n # 'mfunds_detailed', 'mf_holdings', 'bonds_summary',\n # 'bonds_detailed') chosen by `_detect_mode_from_header` once the\n # column-header row arrives.\n page_blocks = [b for b in blocks if b.page > 2]\n cur_account: Optional[DematAccount] = None\n cur_mode: Optional[str] = None\n cur_section: Optional[str] = None\n\n i = 0\n while i < len(page_blocks):\n b = page_blocks[i]\n txt = b.text()\n ltxt = txt.lower()\n\n # Per-account section header. Same-block form (single-name\n # accounts) or split across 3 blocks (joint-name accounts).\n ac_key, consumed = _try_per_account_header(page_blocks, i)\n if ac_key is not None:\n cur_account = accounts_by_key.get(ac_key)\n cur_mode = None\n cur_section = None\n i += consumed\n continue\n\n # MF Folios detailed-table header\n if \"mutual fund folios (f)\" in ltxt:\n cur_account = mf_folios_account\n cur_mode = \"mf_holdings\"\n cur_section = \"mfunds\"\n i += 1\n continue\n\n # Table-header rows tell us which kind of holdings table follows.\n if cur_account is not None:\n mode = _detect_mode_from_header(b, cur_section)\n if mode is not None:\n cur_mode = mode\n i += 1\n continue\n if _is_total_row(b):\n i += 1\n continue\n sec = _section_marker_kind(b)\n if sec is not None:\n cur_section = sec\n # Don't clear cur_mode here \u2014 for unsupported sections\n # (preference shares, AIF, etc.) we want subsequent\n # rows to fall through and be ignored. cur_mode is\n # cleared/reset when the next table header is seen.\n cur_mode = None\n i += 1\n continue\n\n # Holdings rows\n if cur_account is None or cur_mode is None:\n i += 1\n continue\n if cur_mode == \"equities_summary\":\n eq = _parse_equity_row(b, detailed=False)\n if eq:\n cur_account.equities.append(eq)\n elif cur_mode == \"equities_detailed\":\n eq = _parse_equity_row(b, detailed=True)\n if eq:\n cur_account.equities.append(eq)\n elif cur_mode == \"mfunds_summary\":\n mf = _parse_summary_mf_row(b)\n if mf:\n cur_account.mutual_funds.append(mf)\n elif cur_mode == \"mfunds_detailed\":\n mf = _parse_detailed_mf_row(b)\n if mf:\n cur_account.mutual_funds.append(mf)\n elif cur_mode == \"mf_holdings\":\n mf = _parse_mf_holdings_row(b)\n if mf:\n cur_account.mutual_funds.append(mf)\n elif cur_mode == \"bonds_summary\":\n bd = _parse_bond_summary_row(b)\n if bd:\n cur_account.bonds.append(bd)\n elif cur_mode == \"bonds_detailed\":\n bd = _parse_bond_detailed_row(b)\n if bd:\n cur_account.bonds.append(bd)\n i += 1\n\n return NSDLCASData(\n statement_period=period,\n accounts=ordered_accounts,\n investor_info=extract_nsdl_cdsl_investor(\n pdf_path,\n password,\n _atoms=atoms,\n ),\n file_type=file_type,\n )\n\n\n# --- summary-row recognisers (page 2) ---\n\n\ndef _is_summary_demat_row(block: Block) -> bool:\n \"\"\"Page-2 summary row. Two physical layouts produce the same logical\n row depending on how PDFium clusters the broker name and DP/Client\n line:\n\n 4-cell form: ``Type | \"\\\\nDP ID:... Client ID:...\" | folios | value``\n Broker name and DP-ID line share one cell (joined with newline).\n\n 5-cell form: ``Type | \"\" | \"DP ID:... Client ID:...\" | folios | value``\n Broker name and DP-ID line render as separate cells.\n\n Both are accepted; we discriminate by locating the cell whose text\n contains the DP/Client pattern.\n \"\"\"\n if len(block.cells) not in (4, 5):\n return False\n if not DEMAT_TYPE_RE.match(block.cells[0].text.strip()):\n return False\n return any(DP_CLIENT_RE.search(c.text) for c in block.cells[1:])\n\n\ndef _is_summary_mf_folios_row(block: Block) -> bool:\n if len(block.cells) != 4:\n return False\n if not MF_FOLIOS_HEADER_RE.match(block.cells[0].text.strip()):\n return False\n return True\n\n\ndef _account_from_summary_row(\n block: Block, owners: List[DematOwner]\n) -> Tuple[DematAccount, Tuple[str, str, str]]:\n \"\"\"Build a DematAccount from a page-2 summary row, handling both the\n 4-cell and 5-cell layouts (see :func:`_is_summary_demat_row`).\"\"\"\n type_word = DEMAT_TYPE_RE.match(block.cells[0].text.strip()).group(1).upper()\n # Locate the cell carrying the DP/Client identifiers; everything\n # before it (cell index 1, possibly inline in the same cell) is the\n # broker name.\n dp_cell_idx = next(\n (i for i in range(1, len(block.cells)) if DP_CLIENT_RE.search(block.cells[i].text)),\n 1,\n )\n dp_cell_text = block.cells[dp_cell_idx].text\n dpc = DP_CLIENT_RE.search(dp_cell_text)\n dp_id = dpc.group(1) if dpc else \"\"\n client_id = dpc.group(2) if dpc else \"\"\n # Broker = the dp-cell text minus the DP/Client suffix, falling\n # back to the cell immediately before it for the 5-cell layout.\n broker_lines = [\n ln.strip() for ln in dp_cell_text.split(\"\\n\") if ln.strip() and not DP_CLIENT_RE.search(ln)\n ]\n if broker_lines:\n broker = broker_lines[0]\n elif dp_cell_idx >= 2:\n broker = block.cells[dp_cell_idx - 1].text.strip()\n else:\n broker = \"\"\n # Numerics (folios, balance) are the last two cells.\n folios = int(_to_decimal(block.cells[-2].text))\n balance = _to_decimal(block.cells[-1].text)\n ac = DematAccount(\n name=broker,\n type=_full_type(type_word),\n dp_id=dp_id,\n client_id=client_id,\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n bonds=[],\n )\n return ac, _account_key(type_word, dp_id, client_id)\n\n\ndef _mf_folios_account_from_summary(block: Block, owners: List[DematOwner]) -> DematAccount:\n # cells: ['Mutual Fund Folios', '25 Folios', '44', '5,37,10,359.39']\n folios_m = re.search(r\"(\\d+)\", block.cells[1].text)\n folios = int(folios_m.group(1)) if folios_m else 0\n balance = _to_decimal(block.cells[3].text)\n return DematAccount(\n name=\"Mutual Fund Folios\",\n type=\"Mutual Fund Folios\",\n dp_id=\"\",\n client_id=\"\",\n folios=folios,\n balance=balance,\n owners=list(owners),\n equities=[],\n mutual_funds=[],\n bonds=[],\n )\n\n\n# --- per-account section headers ---\n\n\ndef _try_per_account_header(\n blocks: List[Block], i: int\n) -> Tuple[Optional[Tuple[str, str, str]], int]:\n \"\"\"A per-account header marks the start of a holdings section for\n a specific account. Returns `(account_key, blocks_consumed)`.\n\n Two header layouts:\n A) **Single-block (single-name account)** \u2014 one block has TYPE\n + DP/Client in one row of 5 cells, plus broker nam\n... [truncated 14408 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "codereverser__casparser-f960976ba489", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/codereverser__casparser-f960976ba489", "repo_key": "codereverser__casparser", "repo": "codereverser/casparser", "base_commit": "dc6b4bad9a9d10e298fad1f3708587e4eea5f1fd", "source_files": ["CHANGELOG.md", "casparser/parsers/cdsl.py", "casparser/parsers/nsdl.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Requests fail immediately when targeting the wrong environment\n## Description\nWhen a request is made that targets an incorrect environment, the operation fails outright. This forces users to manually re-initiate the request after identifying and correcting the environment.\nExpected behavior: The system should automatically detect requests targeting the wrong environment and attempt to retry them, potentially after adjusting to the correct environment.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `4c6d971b70b6` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### inapppy/appstore.py\n```python\nfrom inapppy.errors import InAppPyValidationError\n\nfrom requests.exceptions import RequestException\nimport requests\n\n\napi_result_ok = 0\napi_result_errors = {\n 21000: InAppPyValidationError('Bad json'),\n 21002: InAppPyValidationError('Bad data'),\n 21003: InAppPyValidationError('Receipt authentication'),\n 21004: InAppPyValidationError('Shared secret mismatch'),\n 21005: InAppPyValidationError('Server is unavailable'),\n 21006: InAppPyValidationError('Subscription has expired'),\n 21007: InAppPyValidationError('Sandbox receipt was sent to the production env'),\n 21008: InAppPyValidationError('Production receipt was sent to the sandbox env'),\n}\n\n\nclass AppStoreValidator(object):\n bundle_id = None\n sandbox = None\n url = None\n\n def __init__(self, bundle_id, sandbox=False):\n self.bundle_id = bundle_id\n self.sandbox = sandbox\n\n if not self.bundle_id:\n raise InAppPyValidationError('`bundle_id` cannot be empty')\n\n self._change_url_by_sandbox()\n\n def _change_url_by_sandbox(self):\n self.url = ('https://sandbox.itunes.apple.com/verifyReceipt' if self.sandbox else\n 'https://buy.itunes.apple.com/verifyReceipt')\n\n def post_json(self, request_json):\n self._change_url_by_sandbox()\n\n return requests.post(self.url, json=request_json).json()\n\n def validate(self, receipt, shared_secret=None):\n receipt_json = {'receipt-data': receipt}\n\n # if shared secret is provided, attach it as `password`.\n if shared_secret:\n receipt_json['password'] = shared_secret\n\n try:\n api_response = self.post_json(receipt_json)\n except (ValueError, RequestException):\n raise InAppPyValidationError('HTTP error')\n\n status = api_response['status']\n if status != api_result_ok:\n error = api_result_errors.get(status, InAppPyValidationError('Unknown API status'))\n error.raw_response = api_response\n\n raise error\n\n return api_response\n\n```\n\n### setup.py\n```python\nfrom setuptools import setup\n\n\nsetup(\n name='inapppy',\n version='0.4',\n packages=['inapppy'],\n install_requires=['rsa', 'requests'],\n description=\"In-app purchase validation library for Apple AppStore and GooglePlay.\",\n keywords='in-app store purchase googleplay appstore validation',\n author='Lukas \u0160alkauskas',\n author_email='halfas.online@gmail.com',\n url='https://github.com/dotpot/InAppPy',\n long_description=open('README.rst').read(),\n license='MIT'\n)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "cx-lukas-salkauskas-x__InAppPy-5cbdd002e4eb", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/cx-lukas-salkauskas-x__InAppPy-5cbdd002e4eb", "repo_key": "cx-lukas-salkauskas-x__InAppPy", "repo": "cx-lukas-salkauskas-x/InAppPy", "base_commit": "4c6d971b70b62e94d43944062c72590a8e1db313", "source_files": ["inapppy/appstore.py", "setup.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Strikethrough formatting is not applied correctly when nested with other formatting\n\n## Description\nWhen text includes strikethrough formatting nested with other inline formatting (e.g., italic or bold), the strikethrough is sometimes ignored or rendered incorrectly. For instance, `~~*italic text*~~` might display as only *italic text* without the strikethrough. The expected behavior is for the strikethrough to be applied, taking precedence over the nested formatting.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `0a870ce8485c` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### marko/ext/gfm/elements.py\n```python\n\"\"\"\nExtra elements\n\"\"\"\nimport itertools\nimport re\n\nfrom marko import block, inline, patterns\n\n\nclass Paragraph(block.Paragraph):\n\n _task_list_item_pattern = re.compile(r\"(\\[[\\sxX]\\])\\s+\\S\")\n override = True\n\n def __init__(self, lines):\n super().__init__(lines)\n m = self._task_list_item_pattern.match(self.children)\n if m:\n self.checked = m.group(1)[1:-1].lower() == \"x\"\n self.children = self.children[m.end(1) :]\n\n\nclass InlineHTML(inline.InlineHTML):\n pattern = re.compile(\n r\"(<%s(?:%s)* */?>\" # open tag\n r\"|\" # closing tag\n r\"|)\" # HTML comment\n r\"|<\\?[\\s\\S]*?\\?>\" # processing instruction\n r\"|\" # declaration\n r\"|)\" # CDATA section\n % (patterns.tag_name, patterns.attribute, patterns.tag_name)\n )\n\n\nclass Strikethrough(inline.InlineElement):\n\n pattern = re.compile(r\"~~([^~]+)~~\")\n priority = 4\n parse_children = True\n\n\nclass _MatchObj:\n def __init__(self, match, start_shift=0, end_shift=0):\n self._match = match\n self._start_shift = start_shift\n self._end_shift = end_shift\n\n def start(self, n=0):\n start = self._match.start() + self._start_shift\n if n == 0:\n return start\n return max(start, self._match.start(n))\n\n def end(self, n=0):\n end = self._match.end() + self._end_shift\n if n == 0:\n return end\n return min(end, self._match.end(n))\n\n def group(self, n=0):\n start = max(self.start(n) - self._match.start(n), 0) or None\n end = min(self.end(n) - self._match.end(n), 0) or None\n return self._match.group(n)[start:end]\n\n def __getattr__(self, name):\n return getattr(self._match, name)\n\n\nclass Url(inline.AutoLink):\n\n www_pattern = re.compile(\n r\"(?:^|(?<=[\\s*_~(\\uff00-\\uffef]))(www\\.([\\w.\\-]*?\\.[\\w.\\-]+)[^<\\s]*)\"\n )\n email_pattern = r\"[\\w.\\-+]+@[\\w.\\-]*?\\.[\\w.\\-]*[a-zA-Z0-9]\"\n bare_pattern = re.compile(\n r\"(?:^|(?<=[\\s*_~(\\uff00-\\uffef]))((?:https?|ftp)://([\\w.\\-]*?\\.[\\w.\\-]+)\"\n r\"[^<\\s]*|%s(?=[\\s.<]|\\Z))\" % email_pattern\n )\n priority = 5\n\n def __init__(self, match):\n super().__init__(match)\n if self.www_pattern.match(self.dest):\n self.dest = \"http://\" + self.dest\n\n @classmethod\n def find(cls, text):\n for match in itertools.chain(\n cls.www_pattern.finditer(text), cls.bare_pattern.finditer(text)\n ):\n domain = match.group(2)\n if domain:\n parts = domain.split(\".\")\n if len(parts) < 2 or any(\"_\" in p for p in parts[-2:]):\n continue\n link_text = match.group()\n if link_text[-1] in (\"?\", \"!\", \".\", \",\", \":\", \"*\", \"_\", \"~\"):\n match = _MatchObj(match, end_shift=-1)\n elif link_text[-1] == \")\" and link_text.count(\")\") > link_text.count(\"(\"):\n shift = link_text.count(\")\") - link_text.count(\"(\")\n match = _MatchObj(match, end_shift=-shift)\n else:\n m = re.search(r\"&[a-zA-Z]+;$\", link_text)\n if m:\n match = _MatchObj(match, end_shift=-len(m.group()))\n yield match\n\n\nclass ListItem(block.ListItem):\n\n pattern = re.compile(r\" {,3}(\\d{1,9}[.)]|[*\\-+])[ \\t\\n\\r\\f]\")\n override = True\n\n\nclass Table(block.BlockElement):\n \"\"\"A table element.\"\"\"\n\n _num_of_cols = None\n _prefix = \"\"\n\n @classmethod\n def match(cls, source):\n source.anchor()\n if TableRow.match(source) and not TableRow._is_delimiter:\n if not TableRow.splitter.search(source.next_line()):\n return False\n source.pos = source.match.end()\n num_of_cols = len(TableRow._cells)\n if (\n TableRow.match(source)\n and TableRow._is_delimiter\n and num_of_cols == len(TableRow._cells)\n ):\n cls._num_of_cols = num_of_cols\n source.reset()\n return True\n source.reset()\n return False\n\n @classmethod\n def parse(cls, source):\n rv = cls()\n rv._num_of_cols = cls._num_of_cols\n rv.children = []\n with source.under_state(rv):\n TableRow.match(source)\n header = TableRow(TableRow.parse(source))\n rv.children.append(header)\n TableRow.match(source)\n delimiters = TableRow._cells\n source.consume()\n for d, th in zip(delimiters, header.children):\n stripped_d = d.strip()\n th.header = True\n if stripped_d[0] == \":\" and stripped_d[-1] == \":\":\n th.align = \"center\"\n elif stripped_d[0] == \":\":\n th.align = \"left\"\n elif stripped_d[-1] == \":\":\n th.align = \"right\"\n while not source.exhausted:\n for e in block.parser._build_block_element_list():\n if issubclass(e, (Table, block.Paragraph)):\n continue\n if e.match(source):\n break\n else:\n if TableRow.match(source):\n rv.children.append(TableRow(TableRow.parse(source)))\n continue\n break\n return rv\n\n\nclass TableRow(block.BlockElement):\n \"\"\"A table row element.\"\"\"\n\n splitter = re.compile(r\"\\s*(? parent._num_of_cols:\n cells = cells[: parent._num_of_cols]\n cells = [TableCell(cell) for cell in cells]\n if parent.children:\n for head, cell in zip(parent.children[0].children, cells):\n cell.align = head.align\n return cells\n\n\nclass TableCell(block.BlockElement):\n \"\"\"A table cell element.\"\"\"\n\n virtual = True\n inline_children = True\n\n def __init__(self, text):\n self.children = text.strip().replace(\"\\\\|\", \"|\")\n self.header = False\n self.align = None\n\n```\n\n### noxfile.py\n```python\nimport os\n\nimport nox\n\nos.environ.update(PDM_IGNORE_SAVED_PYTHON=\"1\")\n\n\n@nox.session(python=[\"3.6\", \"3.8\", \"3.9\", \"3.10\"])\ndef tests(session):\n session.run(\"pdm\", \"install\", \"-d\", external=True)\n session.run(\"pytest\", \"tests/\")\n\n\n@nox.session\ndef benchmark(session):\n session.run(\"pdm\", \"install\", \"-dG\", \"benchmark\", external=True)\n session.run(\"python\", \"-m\", \"tests.benchmark\")\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "frostming__marko-7b31460c08f9", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/frostming__marko-7b31460c08f9", "repo_key": "frostming__marko", "repo": "frostming/marko", "base_commit": "0a870ce8485cc2067f077f8485bccf9f0aba05ed", "source_files": ["marko/ext/gfm/elements.py", "noxfile.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** GFM Alerts not parsed correctly with extra header content or mixed-case types\n\n## Description\nWhen parsing GitHub Flavored Markdown (GFM) alert blocks, two issues are observed:\n\n1. **Extra content on header line:** An alert block is incorrectly recognized even when there is additional text on the same line as the alert type declaration. For example, `> [!NOTE] Some extra text` is currently parsed as a valid alert header.\n * **Expected behavior:** Lines containing any text after the `[!TYPE]` declaration should not be recognized as a GFM alert header.\n2. **Case-sensitive alert types:** Alert blocks are not recognized if the alert type (e.g., `NOTE`, `WARNING`) is not in all uppercase. For example, `> [!note]` or `> [!Warning]` are currently ignored.\n * **Expected behavior:** GFM\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `e34793226fc0` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n## v2.2.1(2025-10-13)\n\n### Changed\n\n- Add support for Python 3.14 and drop support for Python 3.8.\n\n### Fixed\n\n- Fix mis-spelled textarea in regex for escaping (GFM).\n- Fix an inline parsing edge case with nested emphasis.\n\n## v2.2.0(2025-08-08)\n\n### Added\n\n- Add comprehensive usage documentation guide.\n- Support GFM alerts in GitHub Flavored Markdown extension.\n\n### Changed\n\n- Make python-slugify dependency optional for the TOC extension.\n\n### Fixed\n\n- Fix code formatting issues.\n\n## v2.1.4(2025-06-13)\n\n### Fixed\n\n- Correct the parsing of LinkRefDef if it is the last line but doesn't end with a line break.\n\n## v2.1.3(2025-04-05)\n\n### Fixed\n\n- Fix a recursion error when dispatching render methods in extensions.\n- Initialize `children` attribute when creating a `Document` instance.\n\n## v2.1.2(2024-06-21)\n\n### Changed\n\n- Update the GFM spec to the latest master branch.\n- Update the CommonMark spec to 0.31.2.\n\n## v2.1.1(2024-06-19)\n\n### Fixed\n\n- Reference link will not render if the reference definition doesn't end with newline.\n\n## v2.1.0(2024-06-13)\n\n### Changed\n\n- Drop support of Python 3.7.\n\n## v2.0.3(2024-02-22)\n\n- Add pretty representation for the AST for debugging purpose. An extra group `repr` is added for more readable output.\n- Make a dummy `Document` element if the element to render is not a `Document` instance.\n\n## v2.0.2(2023-11-16)\n\n### Fixed\n\n- Rewrite the parsing logic of GFM tables.\n- Fixed the dispatching among different renderers for render methods in extensions. Now the GFM renderer supports `MarkdownRenderer`.\n\n## v2.0.1(2023-10-23)\n\n### Fixed\n\n- Preserve link references when rendering document as Markdown.\n\n### Documentation\n\n- Fix the sidebar warning in shibuya theme.\n\n## v2.0.0(2023-06-12)\n\n### Changed\n\n- Avoid saving to global variables during parsing. There can be multiple parsers running in parallel.\n- Now the `children` attribute for block elements should be a list of child elements.\n- Move the HTML content of `HTMLBlock` from `children` to `body` attribute.\n- Fixed some built-in extensions that modify class attributes.\n- Add a helper class to create extensions, instead of using arbitrary objects to hold partial properties.\n\n### Fixed\n\n- Call `setup_extensions()` when running `render()` method alone.\n\n## v1.3.1(2023-06-09)\n\n### Fixed\n\n- Fix the unpack error when parsing a fenced code block with `codehilite` extension enabled.\n\n## v1.3.0(2023-01-28)\n\n- Fix a bug that `Parser.parse_inline()` cannot be called without preceding call of `Parser.parse()`. [#131](https://github.com/frostming/marko/issue/131)\n- Fix a rendering bug when line breaks exist in a link text. [#126](https://github.com/frostming/marko/issue/126)\n- Drop support of Python 3.6.\n- Update the GFM spec to the latest master branch.\n- Fix a precedence issue of parsing strikethroughs in GFM.\n\n## v1.2.2(2022-09-22)\n\n- Fix a bug of markdown renderer, the ordered list index isn't increasing. [#112](https://github.com/frostming/marko/pull/112)\n- Fix a crash issue when parsing a list item with NBSP in preceding spaces. [#123](https://github.com/frostming/marko/pull/123)\n- Fix a hanging issue when parsing a text with nested brackets. [#124](https://github.com/frostming/marko/pull/124)\n\n## v1.2.1(2022-05-12)\n\n- Fix a bug that tabs between the list bullet and item are not expanded properly.\n- Upgrade from type comments to Py 3.5+ style annotations.\n\n## v1.2.0(2022-01-04)\n\n- Forbid delegation to element-specific render methods for AST renderers.\n- Add LaTeX renderer to the `marko.ext` namespace.\n\n## v1.1.0(2021-07-23)\n\n- Update the implementation to conform with Commonmark 0.30 spec.\n\n## v1.0.3(2021-06-07)\n\n- Consider unicode punctuations when judging whether a delimiter is an opener or a closer.\n- Prefix parsing is eager now.\n\n## v1.0.2(2021-04-06)\n\n- Fix a parsing crash if no newline following the prefix of a block element.\n- Unescape html character refs in ASTRenderer result.\n- Fix an index error when parsing an incomplete link.\n\n## v1.0.1(2021-01-06)\n\n- Remove the duplicate newlines in the output of paragraphs of markdown renderer.\n\n## v1.0.0(2020-12-29)\n\n- Drop support of Python 2.7\n- Remove the deprecated extension object\n- Blacken the code base\n\n## v0.10.0(2020-11-23)\n\n- Drop support of Python 3.5\n- Fix a bug about rendering image links of `MarkdownRender`\n\n## v0.9.1(2020-09-27)\n\n- Fix an XSS issue that exists in code language field.\n\n## v0.9.0(2020-09-27)\n\n- Fix a bug that backslashes get dropped inside a table cell.\n- Fix a bug that the priority of inline elements is not honored.\n- Add a new renderer: `marko.md_renderer.MarkdownRenderer` which rerenders the input back to markdown text.\n\n## v0.8.2(2020-06-22)\n\n- Add support for specifying extensions in marko CLI.\n- Display a help message when prompting for input in marko CLI.\n\n## v0.8.1(2020-04-03)\n\n- Fix a bug of list item parsing when mixed whitespace type is used.\n\n## v0.8.0(2020-03-07)\n\n- Support arguments for extensions\n\n## v0.7.1(2019-12-20)\n\n- Wrap code block with 'highlight' container in codehilite mode.\n\n## v0.7.0(2019-12-11)\n\n- Deprecate the extension name with `Extension` suffix, e.g. `FootnoteExtension` -> `Footnote`.\n And the old names will be removed by `v1.0.0`.\n- Store extra info after the language text in fenced code:\n ````\n ```python myscript.py <-- myscript.py is stored in element\n print('hello world')\n ```\n ````\n- Built-in code highlight extension using pygments.\n\n## v0.6.0(2019-7-26)\n\n- Reverse the extension order.\n- Add a new extension attribute `elements`.\n- Improve the CLI, add more options.\n\n## v0.5.1(2019-7-20)\n\n- Add type hints for all primary functions.\n\n## v0.5.0(2019-7-19)\n\n- Update to comply commonmark spec 0.29.\n- Change the extension system.\n\n## v0.4.3(2018-9-11)\n\n- Fix TOC rendering when heading level exceeds the max depth.\n\n## v0.4.2(2018-8-16)\n\n- Fix CJK regexp for pangu extension.\n\n## v0.4.0(2018-8-24)\n\n- Support Python 2.7.\n\n## v0.3.4(2018-8-20)\n\n- Fix bugs about extensions.\n\n## v0.3.1(2018-8-20)\n\n- Pangu extension.\n\n## v0.3.0(2018-8-20)\n\n- Change the entry function to a class, add TOC and footnotes extensions.\n\n## v0.2.0(2018-8-17)\n\n- Github flavored markdown and docs.\n\n## v0.1.0(2018-8-16)\n\n- Commonmark spec tests.\n\n```\n\n### marko/__init__.py\n```python\nr\"\"\"\n _ _ _ ___ _ _ ___\n | \\ / | /_\\ | _ \\ | |/ / / _ \\\n | |\\/| | / _ \\ | / | ' < | (_) |\n |_| |_| /_/ \\_\\ |_|_\\ |_|\\_\\ \\___/\n\n A markdown parser with high extensibility.\n\n Licensed under MIT.\n Created by Frost Ming\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Iterable, cast\n\nfrom .helpers import MarkoExtension, load_extension\nfrom .html_renderer import HTMLRenderer\nfrom .parser import Parser\nfrom .renderer import Renderer\n\nif TYPE_CHECKING:\n from .block import Document\n from .parser import ElementType\n\n__version__ = \"2.2.1\"\n\n\nclass SetupDone(Exception):\n def __str__(self) -> str:\n return \"Unable to register more extensions after setup done.\"\n\n\nclass Markdown:\n \"\"\"The main class to convert markdown documents.\n\n Attributes:\n * parser: an instance of :class:`marko.parser.Parser`\n * renderer: an instance of :class:`marko.renderer.Renderer`\n\n :param parser: a subclass of :class:`marko.parser.Parser`.\n :param renderer: a subclass of :class:`marko.renderer.Renderer`.\n :param extensions: a list of extensions to register on the object.\n See document of :meth:`Markdown.use()`.\n\n .. note::\n This class is not thread-safe. Create a new instance for each thread.\n \"\"\"\n\n def __init__(\n self,\n parser: type[Parser] = Parser,\n renderer: type[Renderer] = HTMLRenderer,\n extensions: Iterable[str | MarkoExtension] | None = None,\n ) -> None:\n if not issubclass(parser, Parser):\n raise TypeError(\"parser must be a subclass of Parser.\")\n self._base_parser = parser\n self._parser_mixins: list[type] = []\n\n if not issubclass(renderer, Renderer):\n raise TypeError(\"renderer must be a subclass of Renderer.\")\n self._base_renderer = renderer\n self._renderer_mixins: list[type] = []\n\n self._extra_elements: list[ElementType] = []\n self._setup_done = False\n if extensions:\n self.use(*extensions)\n\n def use(self, *extensions: str | MarkoExtension) -> None:\n r\"\"\"Register extensions to Markdown object.\n An extension should be either an object providing ``elements``, `parser_mixins``\n , ``renderer_mixins`` or all attributes, or a string representing the\n corresponding extension in ``marko.ext`` module.\n\n :param \\*extensions: string or :class:`marko.helpers.MarkoExtension` object.\n\n .. note:: Marko uses a mixin based extension system, the order of extensions\n matters: An extension preceding in order will have higher priorty.\n \"\"\"\n if self._setup_done:\n raise SetupDone()\n for extension in extensions:\n if isinstance(extension, str):\n extension = load_extension(extension)\n\n self._parser_mixins = extension.parser_mixins + self._parser_mixins\n self._renderer_mixins = extension.renderer_mixins + self._renderer_mixins\n self._extra_elements.extend(extension.elements)\n\n def _setup_extensions(self) -> None:\n \"\"\"Install all extensions and set things up.\"\"\"\n if self._setup_done:\n return\n self.parser = cast(\n Parser,\n type(\"_Parser\", tuple(self._parser_mixins) + (self._base_parser,), {})(),\n )\n for e in self._extra_elements:\n self.parser.add_element(e)\n self.renderer = cast(\n Renderer,\n type(\n \"_Renderer\",\n tuple(self._renderer_mixins) + (self._base_renderer,),\n {},\n )(),\n )\n self._setup_done = True\n\n def convert(self, text: str) -> str:\n \"\"\"Parse and render the given text.\"\"\"\n return self.render(self.parse(text))\n\n def __call__(self, text: str) -> str:\n return self.convert(text)\n\n def parse(self, text: str) -> Document:\n \"\"\"Call ``self.parser.parse(text)``.\n\n Override this to preprocess text or handle parsed result.\n \"\"\"\n self._setup_extensions()\n return self.parser.parse(text)\n\n def render(self, parsed: Document) -> str:\n \"\"\"Call ``self.renderer.render(text)``.\n\n Override this to handle parsed result.\n \"\"\"\n self._setup_extensions()\n with self.renderer as r:\n return r.render(parsed)\n\n\n# Inner instance, use the bare convert/parse/render function instead\n_markdown = Markdown()\n\n\ndef convert(text: str) -> str:\n \"\"\"Parse and render the given text.\n\n :param text: text to convert.\n :returns: The rendered result.\n \"\"\"\n return _markdown.convert(text)\n\n\ndef parse(text: str) -> Document:\n \"\"\"Parse the text to a structured data object.\n\n :param text: text to parse.\n :returns: the parsed object\n \"\"\"\n return _markdown.parse(text)\n\n\ndef render(parsed: Document) -> str:\n \"\"\"Render the parsed object to text.\n\n :param parsed: the parsed object\n :returns: the rendered result.\n \"\"\"\n return _markdown.render(parsed)\n\n\n__all__ = [\n \"MarkoExtension\",\n \"Markdown\",\n \"convert\",\n \"parse\",\n \"render\",\n \"load_extension\",\n \"Parser\",\n \"Renderer\",\n \"HTMLRenderer\",\n]\n\n```\n\n### marko/ext/gfm/elements.py\n```python\n\"\"\"\nExtra elements\n\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nimport re\nfrom typing import Any, cast\n\nfrom marko import block, inline\nfrom marko.source import Source\n\n\nclass Paragraph(block.Paragraph):\n _task_list_item_pattern = re.compile(r\"(\\[[\\sxX]\\])\\s+\\S\")\n override = True\n\n def __init__(self, lines):\n super().__init__(lines)\n m = self._task_list_item_pattern.match(self.inline_body)\n if m:\n self.checked = m.group(1)[1:-1].lower() == \"x\"\n self.inline_body = self.inline_body[m.end(1) :]\n\n\nclass Strikethrough(inline.InlineElement):\n pattern = re.compile(r\"(? link_text.count(\"(\"):\n shift = link_text.count(\")\") - link_text.count(\"(\")\n match = _MatchObj(match, end_shift=-shift)\n else:\n m = re.search(r\"&[a-zA-Z]+;$\", link_text)\n if m:\n match = _MatchObj(match, end_shift=-len(m.group()))\n yield match\n\n\nclass Table(block.BlockElement):\n \"\"\"A table element.\"\"\"\n\n _prefix = \"\"\n\n def __init__(self, children: list[TableRow], delimiters: list[str]) -> None:\n self.children = children\n self.delimiters = delimiters\n\n @property\n def head(self) -> TableRow:\n return cast(TableRow, self.children[0])\n\n @property\n def num_of_cols(self) -> int:\n return len(self.head.children)\n\n @classmethod\n def match(cls, source):\n source.anchor()\n if not TableRow.match(source) or source.context.is_delimiter:\n return False\n if TableRow.splitter.search(source.next_line()) is None:\n return False\n # consume the first row, we don't use source.consume() here\n # because that may unexpectedly update the line prefix.\n source.pos = source.match.end()\n head = TableRow([TableCell(cell) for cell in source.context.cells])\n if (\n not TableRow.match(source)\n or not source.context.is_delimiter\n or len(source.context.cells) != len(head.children)\n ):\n source.reset() # invalid table, revert the source position\n return False\n source.context.table_info = {\n \"children\": [head],\n \"delimiters\": source.context.cells,\n }\n source.consume() # consume the second row\n return True\n\n @classmethod\n def parse(cls, source):\n rv = cls(**source.context.table_info)\n with source.under_state(rv):\n for d, th in zip(rv.delimiters, rv.head.children):\n stripped_d = d.strip()\n th.header = True\n if stripped_d[0] == \":\" and stripped_d[-1] == \":\":\n th.align = \"center\"\n elif stripped_d[0] == \":\":\n th.align = \"left\"\n elif stripped_d[-1] == \":\":\n th.align = \"right\"\n while not source.exhausted:\n for e in source.parser._build_block_element_list():\n if issubclass(e, (Table, block.Paragraph)):\n continue\n if e.match(source):\n break\n else:\n if TableRow.match(source):\n rv.children.append(TableRow.parse(source))\n continue\n break\n return rv\n\n\nclass TableRow(block.BlockElement):\n \"\"\"A table row element.\"\"\"\n\n splitter = re.compile(r\"\\s*(? None:\n self.children = cells\n\n @classmethod\n def match(cls, source: Source) -> Any:\n line = source.next_line()\n if not line or not re.match(r\" {,3}\\S\", line):\n return False\n parts = cls.splitter.split(line.strip())\n if parts and not parts[0]:\n parts.pop(0)\n if parts and not parts[-1]:\n parts.pop()\n if len(parts) < 1:\n return False\n source.context.cells = parts\n source.context.is_delimiter = all(cls.delimiter.match(cell) for cell in parts)\n return True\n\n @classmethod\n def parse(cls, source: Source) -> TableRow:\n source.consume()\n parent = cast(Table, source.state)\n cells: list[str] = source.context.cells[:]\n if len(cells) < parent.num_of_cols:\n cells.extend(\"\" for _ in range(parent.num_of_cols - len(cells)))\n elif len(cells) > parent.num_of_cols:\n cells = cells[: parent.num_of_cols]\n cell_elements = [TableCell(cell) for cell in cells]\n for head, cell in zip(parent.head.children, cell_elements):\n cell.align = cast(TableCell, head).align\n return cls(cell_elements)\n\n\nclass TableCell(block.BlockElement):\n \"\"\"A table cell element.\"\"\"\n\n virtual = True\n\n def __init__(self, text: str) -> None:\n self.inline_body = text.strip().replace(\"\\\\|\", \"|\")\n self.header = False\n self.align: str | None = None\n\n\nclass Alert(block.Quote):\n \"\"\"Alert block element: block quote with a header like WARNING, NOTE, TIP, IMPORTANT, or CAUTION.\"\"\"\n\n priority = block.Quote.priority + 1\n\n @classmethod\n def match(cls, source):\n return source.expect_re(r\" {,3}>\\s*\\[\\!(WARNING|NOTE|TIP|IMPORTANT|CAUTION)\\]\")\n\n @classmethod\n def parse(cls, source):\n alert_type = source.match.group(1)\n source.next_line(require_prefix=False)\n source.consume()\n state = cls(alert_type)\n with source.under_state(state):\n state.children = source.parser.parse_source(source)\n return state\n\n def __init__(self, alert_type):\n self.alert_type = alert_type\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "frostming__marko-88e65f1f51c1", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/frostming__marko-88e65f1f51c1", "repo_key": "frostming__marko", "repo": "frostming/marko", "base_commit": "e34793226fc0ab80142d23cef2078ab0035a6104", "source_files": ["CHANGELOG.md", "marko/__init__.py", "marko/ext/gfm/elements.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Links with line breaks in their text do not render correctly\n\n## Description\nWhen a Markdown link's display text contains a line break, the link fails to render as a single, clickable entity. For example, `[This is a\\nmulti-line link text](https://example.com)` results in a broken or partially rendered link. The expected behavior is for the entire text, including the line break, to form a single, clickable link to the specified URL.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `3a39989a01d3` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n## v1.2.2(2022-09-22)\n\n- Fix a bug of markdown renderer, the ordered list index isn't increasing. [#112](https://github.com/frostming/marko/pull/112)\n- Fix a crash issue when parsing a list item with NBSP in preceding spaces. [#123](https://github.com/frostming/marko/pull/123)\n- Fix a hanging issue when parsing a text with nested brackets. [#124](https://github.com/frostming/marko/pull/124)\n\n## v1.2.1(2022-05-12)\n\n- Fix a bug that tabs between the list bullet and item are not expanded properly.\n- Upgrade from type comments to Py 3.5+ style annotations.\n\n## v1.2.0(2022-01-04)\n\n- Forbid delegation to element-specific render methods for AST renderers.\n- Add LaTeX renderer to the `marko.ext` namespace.\n\n## v1.1.0(2021-07-23)\n\n- Update the implementation to conform with Commonmark 0.30 spec.\n\n## v1.0.3(2021-06-07)\n\n- Consider unicode punctuations when judging whether a delimiter is an opener or a closer.\n- Prefix parsing is eager now.\n\n## v1.0.2(2021-04-06)\n\n- Fix a parsing crash if no newline following the prefix of a block element.\n- Unescape html character refs in ASTRenderer result.\n- Fix an index error when parsing an incomplete link.\n\n## v1.0.1(2021-01-06)\n\n- Remove the duplicate newlines in the output of paragraphs of markdown renderer.\n\n## v1.0.0(2020-12-29)\n\n- Drop support of Python 2.7\n- Remove the deprecated extension object\n- Blacken the code base\n\n## v0.10.0(2020-11-23)\n\n- Drop support of Python 3.5\n- Fix a bug about rendering image links of `MarkdownRender`\n\n## v0.9.1(2020-09-27)\n\n- Fix an XSS issue that exists in code language field.\n\n## v0.9.0(2020-09-27)\n\n- Fix a bug that backslashes get dropped inside a table cell.\n- Fix a bug that the priority of inline elements is not honored.\n- Add a new renderer: `marko.md_renderer.MarkdownRenderer` which rerenders the input back to markdown text.\n\n## v0.8.2(2020-06-22)\n\n- Add support for specifying extensions in marko CLI.\n- Display a help message when prompting for input in marko CLI.\n\n## v0.8.1(2020-04-03)\n\n- Fix a bug of list item parsing when mixed whitespace type is used.\n\n## v0.8.0(2020-03-07)\n\n- Support arguments for extensions\n\n## v0.7.1(2019-12-20)\n\n- Wrap code block with 'highlight' container in codehilite mode.\n\n## v0.7.0(2019-12-11)\n\n- Deprecate the extension name with `Extension` suffix, e.g. `FootnoteExtension` -> `Footnote`.\n And the old names will be removed by `v1.0.0`.\n- Store extra info after the language text in fenced code:\n ````\n ```python myscript.py <-- myscript.py is stored in element\n print('hello world')\n ```\n ````\n- Built-in code highlight extension using pygments.\n\n## v0.6.0(2019-7-26)\n\n- Reverse the extension order.\n- Add a new extension attribute `elements`.\n- Improve the CLI, add more options.\n\n## v0.5.1(2019-7-20)\n\n- Add type hints for all primary functions.\n\n## v0.5.0(2019-7-19)\n\n- Update to comply commonmark spec 0.29.\n- Change the extension system.\n\n## v0.4.3(2018-9-11)\n\n- Fix TOC rendering when heading level exceeds the max depth.\n\n## v0.4.2(2018-8-16)\n\n- Fix CJK regexp for pangu extension.\n\n## v0.4.0(2018-8-24)\n\n- Support Python 2.7.\n\n## v0.3.4(2018-8-20)\n\n- Fix bugs about extensions.\n\n## v0.3.1(2018-8-20)\n\n- Pangu extension.\n\n## v0.3.0(2018-8-20)\n\n- Change the entry function to a class, add TOC and footnotes extensions.\n\n## v0.2.0(2018-8-17)\n\n- Github flavored markdown and docs.\n\n## v0.1.0(2018-8-16)\n\n- Commonmark spec tests.\n\n```\n\n### marko/inline.py\n```python\n\"\"\"\nInline(span) level elements\n\"\"\"\nimport re\nfrom typing import TYPE_CHECKING, Iterator, Match, Pattern, Sequence, Union\n\nfrom . import inline_parser, patterns\nfrom .element import Element\n\nif TYPE_CHECKING:\n from .inline_parser import _Match\n\n__all__ = (\n \"LineBreak\",\n \"Literal\",\n \"LinkOrEmph\",\n \"InlineHTML\",\n \"CodeSpan\",\n \"Emphasis\",\n \"StrongEmphasis\",\n \"Link\",\n \"Image\",\n \"AutoLink\",\n \"RawText\",\n)\n\n\nclass InlineElement(Element):\n \"\"\"Any inline element should inherit this class\"\"\"\n\n #: Use to denote the precedence in parsing.\n priority = 5\n #: element regex pattern.\n pattern: Union[Pattern[str], str] = \"\"\n #: whether to parse children.\n parse_children = False\n #: which match group to parse.\n parse_group = 1\n #: if True, it won't be included in parsing process but produced by\n #: other elements instead.\n virtual = False\n #: If true, will replace the element which it derives from.\n override = False\n\n if TYPE_CHECKING:\n children: \"str | Sequence[Element]\"\n\n def __init__(self, match: \"_Match\") -> None:\n \"\"\"Parses the matched object into an element\"\"\"\n if not self.parse_children:\n self.children = match.group(self.parse_group)\n\n @classmethod\n def find(cls, text: str) -> Iterator[Match]:\n \"\"\"This method should return an iterable containing matches of this element.\"\"\"\n if isinstance(cls.pattern, str):\n cls.pattern = re.compile(cls.pattern)\n return cls.pattern.finditer(text)\n\n\nclass Literal(InlineElement):\n \"\"\"Literal escapes need to be parsed at the first.\"\"\"\n\n priority = 7\n pattern = re.compile(r'\\\\([!\"#\\$%&\\'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~])')\n\n @classmethod\n def strip_backslash(cls, text: str) -> str:\n return cls.pattern.sub(r\"\\1\", text)\n\n\nclass LineBreak(InlineElement):\n \"\"\"Line breaks:\n Soft: '\\n'\n Hard: ' \\n'\n \"\"\"\n\n priority = 2\n pattern = r\"( *|\\\\)\\n(?!\\Z)\"\n\n def __init__(self, match: \"_Match\") -> None:\n self.soft = not match.group(1).startswith((\" \", \"\\\\\"))\n\n\nclass InlineHTML(InlineElement):\n\n priority = 7\n pattern = re.compile(\n r\"(<%s(?:%s)* */?>\" # open tag\n r\"|\" # closing tag\n r\"|)[\\s\\S]*?(?\" # HTML comment\n r\"|<\\?[\\s\\S]*?\\?>\" # processing instruction\n r\"|\" # declaration\n r\"|)\" # CDATA section\n % (patterns.tag_name, patterns.attribute, patterns.tag_name)\n )\n\n\nclass LinkOrEmph(InlineElement):\n \"\"\"This is a special element, whose parsing is done specially.\n And it produces Link or Emphasis elements.\n \"\"\"\n\n parse_children = True\n\n def __new__(cls, match: \"_Match\") -> \"LinkOrEmph\":\n return parser.inline_elements[match.etype](match) # type: ignore\n\n @classmethod\n def find(cls, text: str) -> Iterator[Match]:\n return inline_parser.find_links_or_emphs(text, _root_node) # type: ignore\n\n\nclass StrongEmphasis(InlineElement):\n \"\"\"Strong emphasis: **sample text**\"\"\"\n\n virtual = True\n parse_children = True\n\n\nclass Emphasis(InlineElement):\n \"\"\"Emphasis: *sample text*\"\"\"\n\n virtual = True\n parse_children = True\n\n\nclass Link(InlineElement):\n \"\"\"Link: [text](/link/destination)\"\"\"\n\n virtual = True\n parse_children = True\n\n def __init__(self, match: \"_Match\") -> None:\n if match.group(2) and match.group(2)[0] == \"<\" and match.group(2)[-1] == \">\":\n self.dest = match.group(2)[1:-1]\n else:\n self.dest = match.group(2) or \"\"\n self.dest = Literal.strip_backslash(self.dest)\n self.title = (\n Literal.strip_backslash(match.group(3)[1:-1]) if match.group(3) else None\n )\n\n\nclass Image(InlineElement):\n \"\"\"Image: ![alt](/src/address)\"\"\"\n\n virtual = True\n parse_children = True\n\n def __init__(self, match: \"_Match\") -> None:\n if match.group(2) and match.group(2)[0] == \"<\" and match.group(2)[-1] == \">\":\n self.dest = match.group(2)[1:-1]\n else:\n self.dest = match.group(2) or \"\"\n self.dest = Literal.strip_backslash(self.dest)\n self.title = (\n Literal.strip_backslash(match.group(3)[1:-1]) if match.group(3) else None\n )\n\n\nclass CodeSpan(InlineElement):\n \"\"\"Inline code span: `code sample`\"\"\"\n\n priority = 7\n pattern = re.compile(r\"(? None:\n self.children = match.group(2).replace(\"\\n\", \" \")\n if self.children.strip() and self.children[0] == self.children[-1] == \" \":\n self.children = self.children[1:-1]\n\n\nclass AutoLink(InlineElement):\n \"\"\"Autolinks: \"\"\"\n\n priority = 7\n pattern = re.compile(rf\"<({patterns.uri}|{patterns.email})>\")\n\n def __init__(self, match: \"_Match\") -> None:\n self.dest = match.group(1)\n if re.match(patterns.email, self.dest):\n self.dest = \"mailto:\" + self.dest\n self.children = [RawText(match.group(1))]\n self.title = \"\"\n\n\nclass RawText(InlineElement):\n \"\"\"The raw text is the fallback for all holes that doesn't match any others.\"\"\"\n\n virtual = True\n\n if TYPE_CHECKING:\n children: str\n\n def __init__(self, match: str, escape: bool = True) -> None:\n self.children = match\n self.escape = escape\n\n\n# backrefs to avoid cylic import\nparser = None\n_root_node = None\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "frostming__marko-b5a628f28dbd", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/frostming__marko-b5a628f28dbd", "repo_key": "frostming__marko", "repo": "frostming/marko", "base_commit": "3a39989a01d34324809898243eb78c102174efd8", "source_files": ["CHANGELOG.md", "marko/inline.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Loose Markdown lists are rendered as tight lists\n\n## Description\nWhen a Markdown list is authored with blank lines between items (a \"loose\" list), the renderer incorrectly treats it as a \"tight\" list. This results in the HTML output for each list item not being wrapped in `

` tags, which is the expected rendering for loose list items.\n\n**Reproduction:**\nGiven the Markdown input:\n```markdown\n- First item\n\n- Second item\n```\n\n**Expected behavior:**\nThe rendered HTML should preserve the loose spacing, resulting in list items wrapped in `

` tags:\n```html\n

    \n
  • First item

  • \n
  • Second item

  • \n
\n```\n\n**Actual behavior:**\nThe rendered HTML treats the list as tight, omitting the `

` tags:\n```html\n

    \n
  • First item
  • \n
  • Second item
  • \n
\n```\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `6d26bbb0498b` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### marko/md_renderer.py\n```python\n\"\"\"\nMarkdown renderer\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom contextlib import contextmanager\nfrom typing import TYPE_CHECKING, Generator, cast\n\nfrom .renderer import Renderer\n\nif TYPE_CHECKING:\n from . import block, inline\n\n\nclass MarkdownRenderer(Renderer):\n \"\"\"Render the AST back to markdown document.\n\n It is useful for, e.g. merging sections and formatting documents.\n For convenience, markdown renderer provides all render functions for basic elements\n and those from common extensions.\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self._prefix = \"\"\n self._second_prefix = \"\"\n\n def __enter__(self) -> MarkdownRenderer:\n self._prefix = \"\"\n self._second_prefix = \"\"\n return super().__enter__()\n\n @contextmanager\n def container(\n self, prefix: str, second_prefix: str = \"\"\n ) -> Generator[None, None, None]:\n old_prefix = self._prefix\n old_second_prefix = self._second_prefix\n self._prefix += prefix\n self._second_prefix += second_prefix\n yield\n self._prefix = old_prefix\n self._second_prefix = old_second_prefix\n\n def render_paragraph(self, element: block.Paragraph) -> str:\n children = self.render_children(element)\n line = self._prefix + children + \"\\n\"\n self._prefix = self._second_prefix\n return line\n\n def render_list(self, element: block.List) -> str:\n result = []\n if element.ordered:\n for num, child in enumerate(element.children, element.start):\n with self.container(f\"{num}. \", \" \" * (len(str(num)) + 2)):\n result.append(self.render(child))\n else:\n for child in element.children:\n with self.container(f\"{element.bullet} \", \" \"):\n result.append(self.render(child))\n self._prefix = self._second_prefix\n return \"\".join(result)\n\n def render_list_item(self, element: block.ListItem) -> str:\n return self.render_children(element)\n\n def render_quote(self, element: block.Quote) -> str:\n with self.container(\"> \", \"> \"):\n result = self.render_children(element).rstrip(\"\\n\")\n self._prefix = self._second_prefix\n return result + \"\\n\"\n\n def render_fenced_code(self, element: block.FencedCode) -> str:\n extra = f\" {element.extra}\" if element.extra else \"\"\n lines = [self._prefix + f\"```{element.lang}{extra}\"]\n lines.extend(\n self._second_prefix + line\n for line in self.render_children(element).splitlines()\n )\n lines.append(self._second_prefix + \"```\")\n self._prefix = self._second_prefix\n return \"\\n\".join(lines) + \"\\n\"\n\n def render_code_block(self, element: block.CodeBlock) -> str:\n indent = \" \" * 4\n lines = self.render_children(element).splitlines()\n lines = [self._prefix + indent + lines[0]] + [\n self._second_prefix + indent + line for line in lines[1:]\n ]\n self._prefix = self._second_prefix\n return \"\\n\".join(lines) + \"\\n\"\n\n def render_html_block(self, element: block.HTMLBlock) -> str:\n result = self._prefix + element.body + \"\\n\"\n self._prefix = self._second_prefix\n return result\n\n def render_thematic_break(self, element: block.ThematicBreak) -> str:\n result = self._prefix + \"* * *\\n\"\n self._prefix = self._second_prefix\n return result\n\n def render_heading(self, element: block.Heading) -> str:\n result = (\n self._prefix\n + \"#\" * element.level\n + \" \"\n + self.render_children(element)\n + \"\\n\"\n )\n self._prefix = self._second_prefix\n return result\n\n def render_setext_heading(self, element: block.SetextHeading) -> str:\n return self.render_heading(cast(\"block.Heading\", element))\n\n def render_blank_line(self, element: block.BlankLine) -> str:\n self._prefix = self._second_prefix\n return \"\\n\"\n\n def render_link_ref_def(self, element: block.LinkRefDef) -> str:\n link_text = element.dest\n if element.title:\n link_text += f\" {element.title}\"\n return f\"[{element.label}]: {link_text}\\n\"\n\n def render_emphasis(self, element: inline.Emphasis) -> str:\n return f\"*{self.render_children(element)}*\"\n\n def render_strong_emphasis(self, element: inline.StrongEmphasis) -> str:\n return f\"**{self.render_children(element)}**\"\n\n def render_inline_html(self, element: inline.InlineHTML) -> str:\n return cast(str, element.children)\n\n def render_link(self, element: inline.Link) -> str:\n link_text = self.render_children(element)\n link_title = (\n '\"{}\"'.format(element.title.replace('\"', '\\\\\"')) if element.title else None\n )\n assert self.root_node\n label = next(\n (\n k\n for k, v in self.root_node.link_ref_defs.items()\n if v == (element.dest, link_title)\n ),\n None,\n )\n if label is not None:\n if label == link_text:\n return f\"[{label}]\"\n return f\"[{link_text}][{label}]\"\n title = f\" {link_title}\" if link_title is not None else \"\"\n return f\"[{link_text}]({element.dest}{title})\"\n\n def render_auto_link(self, element: inline.AutoLink) -> str:\n return f\"<{element.dest}>\"\n\n def render_image(self, element: inline.Image) -> str:\n template = \"![{}]({}{})\"\n title = (\n ' \"{}\"'.format(element.title.replace('\"', '\\\\\"')) if element.title else \"\"\n )\n return template.format(self.render_children(element), element.dest, title)\n\n def render_literal(self, element: inline.Literal) -> str:\n return f\"\\\\{element.children}\"\n\n def render_raw_text(self, element: inline.RawText) -> str:\n from .ext.pangu import PANGU_RE\n\n return re.sub(PANGU_RE, \" \", element.children)\n\n def render_line_break(self, element: inline.LineBreak) -> str:\n return \"\\n\" if element.soft else \"\\\\\\n\"\n\n def render_code_span(self, element: inline.CodeSpan) -> str:\n text = element.children\n if text and text[0] == \"`\" or text[-1] == \"`\":\n return f\"`` {text} ``\"\n return f\"`{element.children}`\"\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "frostming__marko-c898b7820ddd", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/frostming__marko-c898b7820ddd", "repo_key": "frostming__marko", "repo": "frostming/marko", "base_commit": "6d26bbb0498b406e6ec7fcd3575434e3d26106d0", "source_files": ["marko/md_renderer.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Strikethrough markdown with single tilde does not render correctly\n\n## Description\nWhen attempting to use a single tilde for strikethrough markdown (e.g., `~text~`), the text is not rendered with a strikethrough. Instead, it appears as plain text, including the tildes. Strikethrough markdown using double tildes (e.g., `~~text~~`) renders as expected.\n\n**Reproduction:**\n1. Input `This is ~strikethrough~ text.`\n2. Observe that \"strikethrough\" is not rendered with a line through it.\n3. Expected: \"strikethrough\" should appear with a line through it.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `7b31460c08f9` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### .github/workflows/ci.yml\n```python\nname: Tests\n\non:\n pull_request:\n push:\n branches:\n - master\n\njobs:\n Testing:\n runs-on: ${{ matrix.os }}\n strategy:\n matrix:\n python-version: [3.7, 3.8, 3.9, \"3.10\", \"3.11\"]\n os: [ubuntu-latest, macOS-latest, windows-latest]\n\n steps:\n - uses: actions/checkout@v3\n - name: Set up PDM\n uses: pdm-project/setup-pdm@v3\n with:\n python-version: ${{ matrix.python-version }}\n cache: true\n\n - name: Install dependencies\n run: pdm install -G toc -G codehilite\n - name: Run Tests 3.11\n if: ${{ matrix.python-version == '3.11' }}\n run: pdm run -v pytest tests\n - name: Run Tests < 3.11\n if: ${{ matrix.python-version != '3.11' }}\n run: pdm run -v pytest --cov=marko/ --cov-report=xml tests\n - name: Upload coverage to Codecov\n if: ${{ matrix.python-version != '3.11' }}\n uses: codecov/codecov-action@v1\n with:\n token: ${{ secrets.CODECOV_TOKEN }}\n file: ./coverage.xml\n flags: unittests\n\n```\n\n### CHANGELOG.md\n```python\n## Unreleased\n\n- Fix a bug that `Parser.parse_inline()` cannot be called without preceding call of `Parser.parse()`. [#131](https://github.com/frostming/marko/issue/131)\n- Fix a rendering bug when line breaks exist in a link text. [#126](https://github.com/frostming/marko/issue/126)\n- Drop support of Python 3.6.\n- Update the GFM spec to the latest master branch.\n\n## v1.2.2(2022-09-22)\n\n- Fix a bug of markdown renderer, the ordered list index isn't increasing. [#112](https://github.com/frostming/marko/pull/112)\n- Fix a crash issue when parsing a list item with NBSP in preceding spaces. [#123](https://github.com/frostming/marko/pull/123)\n- Fix a hanging issue when parsing a text with nested brackets. [#124](https://github.com/frostming/marko/pull/124)\n\n## v1.2.1(2022-05-12)\n\n- Fix a bug that tabs between the list bullet and item are not expanded properly.\n- Upgrade from type comments to Py 3.5+ style annotations.\n\n## v1.2.0(2022-01-04)\n\n- Forbid delegation to element-specific render methods for AST renderers.\n- Add LaTeX renderer to the `marko.ext` namespace.\n\n## v1.1.0(2021-07-23)\n\n- Update the implementation to conform with Commonmark 0.30 spec.\n\n## v1.0.3(2021-06-07)\n\n- Consider unicode punctuations when judging whether a delimiter is an opener or a closer.\n- Prefix parsing is eager now.\n\n## v1.0.2(2021-04-06)\n\n- Fix a parsing crash if no newline following the prefix of a block element.\n- Unescape html character refs in ASTRenderer result.\n- Fix an index error when parsing an incomplete link.\n\n## v1.0.1(2021-01-06)\n\n- Remove the duplicate newlines in the output of paragraphs of markdown renderer.\n\n## v1.0.0(2020-12-29)\n\n- Drop support of Python 2.7\n- Remove the deprecated extension object\n- Blacken the code base\n\n## v0.10.0(2020-11-23)\n\n- Drop support of Python 3.5\n- Fix a bug about rendering image links of `MarkdownRender`\n\n## v0.9.1(2020-09-27)\n\n- Fix an XSS issue that exists in code language field.\n\n## v0.9.0(2020-09-27)\n\n- Fix a bug that backslashes get dropped inside a table cell.\n- Fix a bug that the priority of inline elements is not honored.\n- Add a new renderer: `marko.md_renderer.MarkdownRenderer` which rerenders the input back to markdown text.\n\n## v0.8.2(2020-06-22)\n\n- Add support for specifying extensions in marko CLI.\n- Display a help message when prompting for input in marko CLI.\n\n## v0.8.1(2020-04-03)\n\n- Fix a bug of list item parsing when mixed whitespace type is used.\n\n## v0.8.0(2020-03-07)\n\n- Support arguments for extensions\n\n## v0.7.1(2019-12-20)\n\n- Wrap code block with 'highlight' container in codehilite mode.\n\n## v0.7.0(2019-12-11)\n\n- Deprecate the extension name with `Extension` suffix, e.g. `FootnoteExtension` -> `Footnote`.\n And the old names will be removed by `v1.0.0`.\n- Store extra info after the language text in fenced code:\n ````\n ```python myscript.py <-- myscript.py is stored in element\n print('hello world')\n ```\n ````\n- Built-in code highlight extension using pygments.\n\n## v0.6.0(2019-7-26)\n\n- Reverse the extension order.\n- Add a new extension attribute `elements`.\n- Improve the CLI, add more options.\n\n## v0.5.1(2019-7-20)\n\n- Add type hints for all primary functions.\n\n## v0.5.0(2019-7-19)\n\n- Update to comply commonmark spec 0.29.\n- Change the extension system.\n\n## v0.4.3(2018-9-11)\n\n- Fix TOC rendering when heading level exceeds the max depth.\n\n## v0.4.2(2018-8-16)\n\n- Fix CJK regexp for pangu extension.\n\n## v0.4.0(2018-8-24)\n\n- Support Python 2.7.\n\n## v0.3.4(2018-8-20)\n\n- Fix bugs about extensions.\n\n## v0.3.1(2018-8-20)\n\n- Pangu extension.\n\n## v0.3.0(2018-8-20)\n\n- Change the entry function to a class, add TOC and footnotes extensions.\n\n## v0.2.0(2018-8-17)\n\n- Github flavored markdown and docs.\n\n## v0.1.0(2018-8-16)\n\n- Commonmark spec tests.\n\n```\n\n### marko/ext/gfm/elements.py\n```python\n\"\"\"\nExtra elements\n\"\"\"\nimport itertools\nimport re\n\nfrom marko import block, inline, patterns\n\n\nclass Paragraph(block.Paragraph):\n\n _task_list_item_pattern = re.compile(r\"(\\[[\\sxX]\\])\\s+\\S\")\n override = True\n\n def __init__(self, lines):\n super().__init__(lines)\n m = self._task_list_item_pattern.match(self.children)\n if m:\n self.checked = m.group(1)[1:-1].lower() == \"x\"\n self.children = self.children[m.end(1) :]\n\n\nclass InlineHTML(inline.InlineHTML):\n pattern = re.compile(\n r\"(<%s(?:%s)* */?>\" # open tag\n r\"|\" # closing tag\n r\"|)\" # HTML comment\n r\"|<\\?[\\s\\S]*?\\?>\" # processing instruction\n r\"|\" # declaration\n r\"|)\" # CDATA section\n % (patterns.tag_name, patterns.attribute, patterns.tag_name)\n )\n\n\nclass Strikethrough(inline.InlineElement):\n\n pattern = re.compile(r\"~~([^~]+)~~\")\n priority = 5\n parse_children = True\n\n\nclass _MatchObj:\n def __init__(self, match, start_shift=0, end_shift=0):\n self._match = match\n self._start_shift = start_shift\n self._end_shift = end_shift\n\n def start(self, n=0):\n start = self._match.start() + self._start_shift\n if n == 0:\n return start\n return max(start, self._match.start(n))\n\n def end(self, n=0):\n end = self._match.end() + self._end_shift\n if n == 0:\n return end\n return min(end, self._match.end(n))\n\n def group(self, n=0):\n start = max(self.start(n) - self._match.start(n), 0) or None\n end = min(self.end(n) - self._match.end(n), 0) or None\n return self._match.group(n)[start:end]\n\n def __getattr__(self, name):\n return getattr(self._match, name)\n\n\nclass Url(inline.AutoLink):\n\n www_pattern = re.compile(\n r\"(?:^|(?<=[\\s*_~(\\uff00-\\uffef]))(www\\.([\\w.\\-]*?\\.[\\w.\\-]+)[^<\\s]*)\"\n )\n email_pattern = r\"[\\w.\\-+]+@[\\w.\\-]*?\\.[\\w.\\-]*[a-zA-Z0-9]\"\n bare_pattern = re.compile(\n r\"(?:^|(?<=[\\s*_~(\\uff00-\\uffef]))((?:https?|ftp)://([\\w.\\-]*?\\.[\\w.\\-]+)\"\n r\"[^<\\s]*|%s(?=[\\s.<]|\\Z))\" % email_pattern\n )\n priority = 5\n\n def __init__(self, match):\n super().__init__(match)\n if self.www_pattern.match(self.dest):\n self.dest = \"http://\" + self.dest\n\n @classmethod\n def find(cls, text):\n for match in itertools.chain(\n cls.www_pattern.finditer(text), cls.bare_pattern.finditer(text)\n ):\n domain = match.group(2)\n if domain:\n parts = domain.split(\".\")\n if len(parts) < 2 or any(\"_\" in p for p in parts[-2:]):\n continue\n link_text = match.group()\n if link_text[-1] in (\"?\", \"!\", \".\", \",\", \":\", \"*\", \"_\", \"~\"):\n match = _MatchObj(match, end_shift=-1)\n elif link_text[-1] == \")\" and link_text.count(\")\") > link_text.count(\"(\"):\n shift = link_text.count(\")\") - link_text.count(\"(\")\n match = _MatchObj(match, end_shift=-shift)\n else:\n m = re.search(r\"&[a-zA-Z]+;$\", link_text)\n if m:\n match = _MatchObj(match, end_shift=-len(m.group()))\n yield match\n\n\nclass ListItem(block.ListItem):\n\n pattern = re.compile(r\" {,3}(\\d{1,9}[.)]|[*\\-+])[ \\t\\n\\r\\f]\")\n override = True\n\n\nclass Table(block.BlockElement):\n \"\"\"A table element.\"\"\"\n\n _num_of_cols = None\n _prefix = \"\"\n\n @classmethod\n def match(cls, source):\n source.anchor()\n if TableRow.match(source) and not TableRow._is_delimiter:\n if not TableRow.splitter.search(source.next_line()):\n return False\n source.pos = source.match.end()\n num_of_cols = len(TableRow._cells)\n if (\n TableRow.match(source)\n and TableRow._is_delimiter\n and num_of_cols == len(TableRow._cells)\n ):\n cls._num_of_cols = num_of_cols\n source.reset()\n return True\n source.reset()\n return False\n\n @classmethod\n def parse(cls, source):\n rv = cls()\n rv._num_of_cols = cls._num_of_cols\n rv.children = []\n with source.under_state(rv):\n TableRow.match(source)\n header = TableRow(TableRow.parse(source))\n rv.children.append(header)\n TableRow.match(source)\n delimiters = TableRow._cells\n source.consume()\n for d, th in zip(delimiters, header.children):\n stripped_d = d.strip()\n th.header = True\n if stripped_d[0] == \":\" and stripped_d[-1] == \":\":\n th.align = \"center\"\n elif stripped_d[0] == \":\":\n th.align = \"left\"\n elif stripped_d[-1] == \":\":\n th.align = \"right\"\n while not source.exhausted:\n for e in block.parser._build_block_element_list():\n if issubclass(e, (Table, block.Paragraph)):\n continue\n if e.match(source):\n break\n else:\n if TableRow.match(source):\n rv.children.append(TableRow(TableRow.parse(source)))\n continue\n break\n return rv\n\n\nclass TableRow(block.BlockElement):\n \"\"\"A table row element.\"\"\"\n\n splitter = re.compile(r\"\\s*(? parent._num_of_cols:\n cells = cells[: parent._num_of_cols]\n cells = [TableCell(cell) for cell in cells]\n if parent.children:\n for head, cell in zip(parent.children[0].children, cells):\n cell.align = head.align\n return cells\n\n\nclass TableCell(block.BlockElement):\n \"\"\"A table cell element.\"\"\"\n\n virtual = True\n inline_children = True\n\n def __init__(self, text):\n self.children = text.strip().replace(\"\\\\|\", \"|\")\n self.header = False\n self.align = None\n\n```\n\n### noxfile.py\n```python\nimport os\n\nimport nox\n\nos.environ.update(PDM_IGNORE_SAVED_PYTHON=\"1\")\n\n\n@nox.session(python=[\"3.6\", \"3.8\", \"3.9\", \"3.10\", \"3.11\"])\ndef tests(session):\n session.run(\"pdm\", \"install\", \"-d\", external=True)\n session.run(\"pytest\", \"tests/\")\n\n\n@nox.session\ndef benchmark(session):\n session.run(\"pdm\", \"install\", \"-dG\", \"benchmark\", external=True)\n session.run(\"python\", \"-m\", \"tests.benchmark\")\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "frostming__marko-cf000809e7da", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/frostming__marko-cf000809e7da", "repo_key": "frostming__marko", "repo": "frostming/marko", "base_commit": "7b31460c08f913bf67bb24464c26c606b8739e3f", "source_files": [".github/workflows/ci.yml", "CHANGELOG.md", "marko/ext/gfm/elements.py", "noxfile.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Crash when parsing list items containing ` `\n\n## Description\nThe application crashes when attempting to parse a markdown list item that contains the ` ` HTML entity.\n\nFor example, parsing the following markdown input leads to a crash:\n```markdown\n* List item with a non-breaking space\n```\n\nThe expected behavior is for the application to successfully parse such list items without crashing, correctly interpreting ` ` as a non-breaking space.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `f7dfd20d1106` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### marko/block.py\n```python\n\"\"\"\nBlock level elements\n\"\"\"\nimport re\nfrom typing import Any, Dict\nfrom typing import List as _List\nfrom typing import Match, Optional, Tuple, Union, cast\n\nfrom . import inline, patterns\nfrom .element import Element\nfrom .helpers import Source, is_paired, normalize_label\nfrom .parser import Parser\n\n__all__ = (\n \"Document\",\n \"CodeBlock\",\n \"Heading\",\n \"List\",\n \"ListItem\",\n \"BlankLine\",\n \"Quote\",\n \"FencedCode\",\n \"ThematicBreak\",\n \"HTMLBlock\",\n \"LinkRefDef\",\n \"SetextHeading\",\n \"Paragraph\",\n)\n\n\nclass BlockElement(Element):\n \"\"\"Any block element should inherit this class\"\"\"\n\n #: Use to denote the precedence in parsing\n priority = 5\n #: if True, it won't be included in parsing process but produced by other elements\n #: other elements instead.\n virtual = False\n #: Whether children are parsed as inline elements.\n inline_children = False\n #: If true, will replace the element which it derives from.\n override = False\n _prefix = \"\"\n\n @classmethod\n def match(self, source: Source) -> Any:\n \"\"\"Test if the source matches the element at current position.\n The source should not be consumed in the method unless you have to.\n\n :param source: the ``Source`` object of the content to be parsed\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def parse(self, source: Source) -> Any:\n \"\"\"Parses the source. This is a proper place to consume the source body and\n return an element or information to build one. The information tuple will be\n passed to ``__init__`` method afterwards. Inline parsing, if any, should also\n be performed here.\n\n :param source: the ``Source`` object of the content to be parsed\n \"\"\"\n raise NotImplementedError()\n\n def parse_inline(self) -> None:\n \"\"\"Inline parsing is postponed so that all link references\n are seen before that.\n \"\"\"\n if self.inline_children:\n self.children = parser.parse_inline(self.children) # type: ignore\n elif isinstance(getattr(self, \"children\", None), list):\n for child in self.children:\n if isinstance(child, BlockElement):\n child.parse_inline()\n\n def __lt__(self, o: \"BlockElement\") -> bool:\n return self.priority < o.priority\n\n\nclass Document(BlockElement):\n \"\"\"Document node element.\"\"\"\n\n _prefix = \"\"\n virtual = True\n\n def __init__(self, text: str) -> None:\n self.link_ref_defs: Dict[str, Tuple[str, str]] = {}\n source = Source(text)\n inline._root_node = self # type: ignore\n with source.under_state(self):\n self.children = parser.parse(source) # type: ignore\n self.parse_inline()\n\n\nclass BlankLine(BlockElement):\n \"\"\"Blank lines\"\"\"\n\n priority = 5\n\n def __init__(self, start: int) -> None:\n self._anchor = start\n\n @classmethod\n def match(cls, source: Source) -> bool:\n line = source.next_line()\n return line is not None and not line.strip()\n\n @classmethod\n def parse(cls, source: Source) -> int:\n start = source.pos\n while not source.exhausted and cls.match(source):\n source.consume()\n return start\n\n\nclass Heading(BlockElement):\n \"\"\"Heading element: (### Hello\\n)\"\"\"\n\n priority = 6\n pattern = re.compile(\n r\" {0,3}(#{1,6})((?=\\s)[^\\n]*?|[^\\n\\S]*)(?:(?<=\\s)(? None:\n self.level = len(match.group(1))\n self.children = match.group(2).strip()\n\n @classmethod\n def match(cls, source: Source) -> Optional[Match]:\n return source.expect_re(cls.pattern)\n\n @classmethod\n def parse(cls, source: Source) -> Optional[Match]:\n m = source.match\n source.consume()\n return m\n\n\nclass SetextHeading(BlockElement):\n \"\"\"Setext heading: (Hello\\n===\\n)\n It can only be created by Paragraph.parse.\n \"\"\"\n\n virtual = True\n inline_children = True\n\n def __init__(self, lines: _List[str]) -> None:\n self.level = 1 if lines.pop().strip()[0] == \"=\" else 2\n self.children = \"\".join(line.lstrip() for line in lines).strip()\n\n\nclass CodeBlock(BlockElement):\n \"\"\"Indented code block: ( this is a code block\\n)\"\"\"\n\n priority = 4\n\n def __init__(self, lines: str) -> None:\n self.children = [inline.RawText(lines, False)]\n self.lang = \"\"\n self.extra = \"\"\n\n @classmethod\n def match(cls, source: Source) -> str:\n line = source.next_line(False)\n prefix = source.prefix + \" {4}\"\n if isinstance(source.state, Quote):\n # requires five spaces to prefix\n prefix = source.prefix[:-1] + \" {4}\"\n return cls.strip_prefix(line, prefix) # type: ignore\n\n @classmethod\n def parse(cls, source: Source) -> str:\n prefix = source.prefix + \" {4}\"\n lines = [cls.match(source)]\n source.consume()\n source.anchor()\n while not source.exhausted:\n line = source.next_line()\n if line is not None and not line.strip():\n source.consume()\n stripped_line = cls.strip_prefix(line, prefix)\n if stripped_line:\n lines.append(stripped_line)\n else:\n lines.append(\"\\n\")\n elif cls.match(source):\n lines.append(cls.match(source))\n source.consume()\n source.anchor()\n else:\n source.reset()\n break\n return \"\".join(lines).rstrip(\"\\n\") + \"\\n\"\n\n @staticmethod\n def strip_prefix(line: str, prefix: str) -> str:\n match = re.match(prefix, line.expandtabs(4))\n if not match:\n return \"\"\n end = match.end()\n for i in range(len(line)):\n expanded = line[: i + 1].expandtabs(4)\n if len(expanded) < end:\n continue\n d = len(expanded) - end\n if d == 0:\n return line[i + 1 :]\n return expanded[-d:] + line[i + 1 :]\n return \"\"\n\n\nclass FencedCode(BlockElement):\n \"\"\"Fenced code block: (```python\\nhello\\n```\\n)\"\"\"\n\n priority = 7\n pattern = re.compile(r\"( {,3})(`{3,}|~{3,})[^\\n\\S]*(.*?)$\", re.M)\n _parse_info: Tuple[str, str, str, str] = (\"\", \"\", \"\", \"\")\n\n def __init__(self, match: Tuple[str, str, str]) -> None:\n self.lang = inline.Literal.strip_backslash(match[0])\n self.extra = match[1]\n self.children = [inline.RawText(match[2], False)]\n\n @classmethod\n def match(cls, source: Source) -> Optional[Match]:\n m = source.expect_re(cls.pattern)\n if not m:\n return None\n prefix, leading, info = m.groups()\n if leading[0] == \"`\" and \"`\" in info:\n return None\n lang, extra = (info.split(None, 1) + [\"\"] * 2)[:2]\n cls._parse_info = prefix, leading, lang, extra\n return m\n\n @classmethod\n def parse(cls, source: Source) -> Tuple[str, str, str]:\n source.next_line()\n source.consume()\n lines = []\n while not source.exhausted:\n line = source.next_line()\n if line is None:\n break\n source.consume()\n m = re.match(r\" {,3}(~+|`+)[^\\n\\S]*$\", line, flags=re.M)\n if m and cls._parse_info[1] in m.group(1):\n break\n\n prefix_len = source.match_prefix(cls._parse_info[0], line)\n if prefix_len >= 0:\n line = line[prefix_len:]\n else:\n line = line.lstrip()\n lines.append(line)\n return cls._parse_info[2], cls._parse_info[3], \"\".join(lines)\n\n\nclass ThematicBreak(BlockElement):\n \"\"\"Horizontal rules: (----\\n)\"\"\"\n\n priority = 8\n pattern = re.compile(r\" {,3}([-_*][^\\n\\S]*){3,}$\\n?\", flags=re.M)\n\n @classmethod\n def match(cls, source: Source) -> bool:\n m = source.expect_re(cls.pattern)\n if not m:\n return False\n return len(set(re.sub(r\"\\s+\", \"\", m.group()))) == 1\n\n @classmethod\n def parse(cls, source: Source) -> \"ThematicBreak\":\n source.consume()\n return cls()\n\n\nclass HTMLBlock(BlockElement):\n \"\"\"HTML blocks, parsed as it is\"\"\"\n\n priority = 5\n _end_cond = None # Optional[Match]\n\n def __init__(self, lines: str) -> None:\n self.children = lines\n\n @classmethod\n def match(cls, source: Source) -> Union[int, bool]:\n if source.expect_re(r\"(?i) {,3}<(script|pre|style|textarea)[>\\s]\"):\n assert source.match\n cls._end_cond = re.compile(rf\"(?i)\")\n return 1\n if source.expect_re(r\" {,3}\")\n return 2\n if source.expect_re(r\" {,3}<\\?\"):\n cls._end_cond = re.compile(r\"\\?>\")\n return 3\n if source.expect_re(r\" {,3}\")\n return 4\n if source.expect_re(r\" {,3}\")\n return 5\n block_tag = r\"(?:{})\".format(\"|\".join(patterns.tags))\n if source.expect_re(r\"(?im) {,3}|$)\" % block_tag):\n cls._end_cond = None\n return 6\n if source.expect_re(\n r\"(?m) {,3}(<%(tag)s(?:%(attr)s)*[^\\n\\S]*/?>|)[^\\n\\S]*$\"\n % {\"tag\": patterns.tag_name, \"attr\": patterns.attribute_no_lf}\n ):\n cls._end_cond = None\n return 7\n\n return False\n\n @classmethod\n def parse(cls, source: Source) -> str:\n lines = []\n while not source.exhausted:\n line = source.next_line()\n if line is None:\n break\n lines.append(line)\n if cls._end_cond is not None:\n if cls._end_cond.search(line):\n source.consume()\n break\n elif line.strip() == \"\":\n lines.pop()\n break\n source.consume()\n return \"\".join(lines)\n\n\nclass Paragraph(BlockElement):\n \"\"\"A paragraph element\"\"\"\n\n priority = 1\n pattern = re.compile(r\"[^\\n]+$\\n?\", flags=re.M)\n inline_children = True\n\n def __init__(self, lines: _List[str]) -> None:\n str_lines = \"\".join(line.lstrip() for line in lines).rstrip(\"\\n\")\n self.children = str_lines\n self._tight = False\n\n @classmethod\n def match(cls, source: Source) -> bool:\n return source.expect_re(cls.pattern) is not None\n\n @staticmethod\n def is_setext_heading(line: str) -> bool:\n return re.match(r\" {,3}(=+|-+)[^\\n\\S]*$\", line) is not None\n\n @classmethod\n def break_paragraph(cls, source: Source, lazy: bool = False) -> bool:\n assert isinstance(parser, Parser)\n if (\n parser.block_elements[\"Quote\"].match(source)\n or parser.block_elements[\"Heading\"].match(source)\n or parser.block_elements[\"BlankLine\"].match(source)\n or parser.block_elements[\"FencedCode\"].match(source)\n ):\n return True\n if (\n lazy\n and isinstance(source.state, List)\n and parser.block_elements[\"ListItem\"].match(source)\n ):\n return True\n if parser.block_elements[\"List\"].match(source):\n result = parser.block_elements[\"ListItem\"].parse_leading(\n source.next_line(), 0\n )\n if lazy or (result[1][:-1] == \"1\" or result[1] in \"*-+\") and result[3]:\n return True\n html_type = parser.block_elements[\"HTMLBlock\"].match(source)\n if html_type and html_type != 7:\n return True\n if parser.block_elements[\"ThematicBreak\"].match(source):\n if not lazy and cls.is_setext_heading(source.next_line()):\n return False\n return True\n return False\n\n @classmethod\n def parse(cls, source: Source) -> _List[str]:\n lines = [source.next_line()]\n source.consume()\n end_parse = False\n while not source.exhausted and not end_parse:\n if cls.break_paragraph(source):\n break\n line = source.next_line()\n # the prefix is matched and not breakers\n if line:\n lines.append(line)\n source.consume()\n if cls.is_setext_heading(line):\n return parser.block_elements[\"SetextHeading\"](lines) # type: ignore\n else:\n # check lazy continuation, store the previous state stack\n states = source._states[:]\n while len(source._states) > 1:\n source.pop_state()\n if source.next_line():\n # matches the prefix, quit the loop\n if cls.break_paragraph(source, True):\n # stop the whole parsing\n end_parse = True\n else:\n lines.append(source.next_line())\n source.consume()\n break\n source._states = states\n return lines # type: ignore\n\n\nclass Quote(BlockElement):\n \"\"\"block quote element: (> hello world)\"\"\"\n\n priority = 6\n _prefix = r\" {,3}>[^\\n\\S]?\"\n\n @classmethod\n def match(cls, source: Source) -> Optional[Match]:\n return source.expect_re(r\" {,3}>\")\n\n @classmethod\n def parse(cls, source: Source) -> \"Quote\":\n state = cls()\n with source.under_state(state):\n state.children = parser.parse(source) # type: ignore\n return state\n\n\nclass List(BlockElement):\n \"\"\"List block element\"\"\"\n\n priority = 6\n _prefix = \"\"\n pattern = re.compile(r\" {,3}(\\d{1,9}[.)]|[*\\-+])[ \\t\\n\\r\\f]\")\n _parse_info = (\"\", False, 0)\n\n def __init__(self) -> None:\n self.bullet, self.ordered, self.start = self._parse_info\n self.tight = True\n\n @classmethod\n def match(cls, source: Source) -> bool:\n m = source.expect_re(cls.pattern)\n if not m:\n return False\n bullet, ordered, start = m.group(1), False, 1\n if bullet[:-1].isdigit():\n ordered = True\n start = int(bullet[:-1])\n cls._parse_info = (bullet, ordered, start)\n return m is not None\n\n @classmethod\n def parse(cls, source: Source) -> \"List\":\n state = cls()\n children = []\n tight = True\n has_blank_line = False\n with source.under_state(state):\n while not source.exhausted:\n if parser.block_elements[\"ListItem\"].match(source): # type: ignore\n el = parser.block_elements[\"ListItem\"].parse(source) # type: ignore\n if not isinstance(el, BlockElement):\n el = parser.block_elements[\"ListItem\"](el) # type: ignore\n children.append(el)\n source.anchor()\n if has_blank_line:\n tight = False\n elif BlankLine.match(source):\n BlankLine.parse(source)\n has_blank_line = True\n else:\n source.reset()\n break\n tight = tight and not any(\n isinstance(e, BlankLine) for item in children for e in item.children\n )\n if tight:\n for item in children:\n item._tight = tight\n for child in item.children:\n if isinstance(child, Paragraph):\n child._tight = tight\n state.children = children\n state.tight = tight\n return state\n\n\nclass ListItem(BlockElement):\n \"\"\"List item element. It can only be created by List.parse\"\"\"\n\n _parse_inf\n... [truncated 4074 chars]\n\n```\n\n### marko/helpers.py\n```python\n\"\"\"\nHelper functions and data structures\n\"\"\"\nimport functools\nimport re\nfrom contextlib import contextmanager\nfrom importlib import import_module\nfrom typing import (\n TYPE_CHECKING,\n Callable,\n Generator,\n List,\n Match,\n Optional,\n Pattern,\n Union,\n)\n\nif TYPE_CHECKING:\n\n from .block import BlockElement\n\n\ndef camel_to_snake_case(name: str) -> str:\n \"\"\"Takes a camelCased string and converts to snake_case.\"\"\"\n pattern = r\"[A-Z][a-z]+|[A-Z]+(?![a-z])\"\n return \"_\".join(map(str.lower, re.findall(pattern, name)))\n\n\ndef is_paired(text: str, open: str = \"(\", close: str = \")\") -> bool:\n \"\"\"Check if the text only contains:\n 1. blackslash escaped parentheses, or\n 2. parentheses paired.\n \"\"\"\n count = 0\n escape = False\n for c in text:\n if escape:\n escape = False\n elif c == \"\\\\\":\n escape = True\n elif c == open:\n count += 1\n elif c == close:\n if count == 0:\n return False\n count -= 1\n return count == 0\n\n\ndef _preprocess_text(text: str) -> str:\n return text.replace(\"\\r\\n\", \"\\n\")\n\n\nclass Source:\n \"\"\"Wrapper class on content to be parsed\"\"\"\n\n def __init__(self, text: str) -> None:\n self._buffer = _preprocess_text(text)\n self.pos = 0\n self._anchor = 0\n self._states: List[\"BlockElement\"] = []\n self.match: Optional[Match[str]] = None\n\n @property\n def state(self) -> \"BlockElement\":\n \"\"\"Returns the current element state.\"\"\"\n if not self._states:\n raise RuntimeError(\"Need to push a state first.\")\n return self._states[-1]\n\n @property\n def root(self) -> \"BlockElement\":\n \"\"\"Returns the root element, which is at the bottom of self._states.\"\"\"\n if not self._states:\n raise RuntimeError(\"Need to push a state first.\")\n return self._states[0]\n\n def push_state(self, element: \"BlockElement\") -> None:\n \"\"\"Push a new state to the state stack.\"\"\"\n self._states.append(element)\n\n def pop_state(self) -> \"BlockElement\":\n \"\"\"Pop the top most state.\"\"\"\n return self._states.pop()\n\n @contextmanager\n def under_state(self, element: \"BlockElement\") -> Generator[\"Source\", None, None]:\n \"\"\"A context manager to enable a new state temporarily.\"\"\"\n self.push_state(element)\n yield self\n self.pop_state()\n\n @property\n def exhausted(self) -> bool:\n \"\"\"Indicates whether the source reaches the end.\"\"\"\n return self.pos >= len(self._buffer)\n\n @property\n def prefix(self) -> str:\n \"\"\"The prefix of each line when parsing.\"\"\"\n return \"\".join(s._prefix for s in self._states)\n\n def _expect_re(\n self, regexp: Union[Pattern[str], str], pos: int\n ) -> Optional[Match[str]]:\n if isinstance(regexp, str):\n regexp = re.compile(regexp)\n return regexp.match(self._buffer, pos)\n\n @staticmethod\n @functools.lru_cache()\n def match_prefix(prefix: str, line: str) -> int:\n \"\"\"Check if the line starts with given prefix and\n return the position of the end of prefix.\n If the prefix is not matched, return -1.\n \"\"\"\n m = re.match(prefix, line.expandtabs(4))\n if not m:\n if re.match(prefix, line.expandtabs(4).replace(\"\\n\", \" \" * 99 + \"\\n\")):\n return len(line) - 1\n return -1\n pos = m.end()\n if pos == 0:\n return 0\n for i in range(1, len(line) + 1):\n if len(line[:i].expandtabs(4)) >= pos:\n return i\n return -1 # pragma: no cover\n\n def expect_re(self, regexp: Union[Pattern[str], str]) -> Optional[Match[str]]:\n \"\"\"Test against the given regular expression and returns the match object.\n\n :param regexp: the expression to be tested.\n :returns: the match object.\n \"\"\"\n prefix_len = self.match_prefix(\n self.prefix, self.next_line(require_prefix=False) # type: ignore\n )\n if prefix_len >= 0:\n match = self._expect_re(regexp, self.pos + prefix_len)\n self.match = match\n return match\n else:\n return None\n\n def next_line(self, require_prefix: bool = True) -> Optional[str]:\n \"\"\"Return the next line in the source.\n\n :param require_prefix: if False, the whole line will be returned.\n otherwise, return the line with prefix stripped or None if the prefix\n is not matched.\n \"\"\"\n if require_prefix:\n m = self.expect_re(r\"(?m)[^\\n]*?$\\n?\")\n else:\n m = self._expect_re(r\"(?m)[^\\n]*$\\n?\", self.pos)\n self.match = m\n if m:\n return m.group()\n return None\n\n def consume(self) -> None:\n \"\"\"Consume the body of source. ``pos`` will move forward.\"\"\"\n if self.match:\n self.pos = self.match.end()\n if self.match.group()[-1:] == \"\\n\":\n self._update_prefix()\n self.match = None\n\n def anchor(self) -> None:\n \"\"\"Pin the current parsing position.\"\"\"\n self._anchor = self.pos\n\n def reset(self) -> None:\n \"\"\"Reset the position to the last anchor.\"\"\"\n self.pos = self._anchor\n\n def _update_prefix(self) -> None:\n for s in self._states:\n if hasattr(s, \"_second_prefix\"):\n s._prefix = s._second_prefix # type: ignore\n\n\ndef normalize_label(label: str) -> str:\n \"\"\"Return the normalized form of link label.\"\"\"\n return re.sub(r\"\\s+\", \" \", label).strip().casefold()\n\n\ndef load_extension_object(name: str) -> Callable:\n \"\"\"Load extension object from a string.\n First try `marko.ext.` if possible\n \"\"\"\n module = None\n if \".\" not in name:\n try:\n module = import_module(f\"marko.ext.{name}\")\n except ImportError:\n pass\n if module is None:\n try:\n module = import_module(name)\n except ImportError:\n raise ImportError(\n f\"Extension {name} cannot be found. Please check the name.\"\n )\n\n try:\n maker = getattr(module, \"make_extension\")\n except AttributeError:\n raise AttributeError(\n f\"Module {name} does not have 'make_extension' attributte.\"\n )\n return maker\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "frostming__marko-f904b655d0e4", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/frostming__marko-f904b655d0e4", "repo_key": "frostming__marko", "repo": "frostming/marko", "base_commit": "f7dfd20d1106bef06e2b7513b15be70ef8786f0a", "source_files": ["marko/block.py", "marko/helpers.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Config class is missing `from_environ` method\n\n## Description\nThe current configuration class does not provide a method to load settings directly from environment variables.\n\nExpected behavior: The config class should include a `from_environ` method to initialize configuration values based on environment variables.\nActual behavior: There is no `from_environ` method available on the config class, preventing easy configuration via environment variables.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `d61c0822bf0b` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### README.rst\n```python\n============================================================\nenviron_config: Configuration with env variables for Python.\n============================================================\n\n.. image:: https://travis-ci.org/hynek/environ_config.svg?branch=master\n :target: https://travis-ci.org/hynek/environ_config\n :alt: CI status\n\n.. image:: https://codecov.io/gh/hynek/environ_config/branch/master/graph/badge.svg\n :target: https://codecov.io/gh/hynek/environ_config\n :alt: Test Coverage\n\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n :target: https://github.com/ambv/black\n :alt: Code style: black\n\n.. begin\n\n``environ_config`` allows you to configure your applications using environment variables \u2013 as recommended in `The Twelve-Factor App `_ methodology \u2013 with elegant, boilerplate-free, and declarative code:\n\n.. code-block:: pycon\n\n >>> import environ\n >>> # Extracts secrets from Vault-via-envconsul: 'secret/your-app':\n >>> vault = environ.secrets.VaultEnvSecrets(vault_prefix=\"SECRET_YOUR_APP\")\n >>> @environ.config(prefix=\"APP\")\n ... class AppConfig:\n ... @environ.config\n ... class DB:\n ... name = environ.var(\"default_db\")\n ... host = environ.var(\"default.host\")\n ... port = environ.var(5432, converter=int) # Use attrs's converters and validators!\n ... user = environ.var(\"default_user\")\n ... password = vault.secret()\n ...\n ... env = environ.var()\n ... lang = environ.var(name=\"LANG\") # It's possible to overwrite the names of variables.\n ... db = environ.group(DB)\n ... awesome = environ.bool_var()\n >>> cfg = environ.to_config(\n ... AppConfig,\n ... environ={\n ... \"APP_ENV\": \"dev\",\n ... \"APP_DB_HOST\": \"localhost\",\n ... \"LANG\": \"C\",\n ... \"APP_AWESOME\": \"yes\", # true and 1 work too, everything else is False\n ... # Vault-via-envconsul-style var name:\n ... \"SECRET_YOUR_APP_DB_PASSWORD\": \"s3kr3t\",\n ... }) # Uses os.environ by default.\n >>> cfg\n AppConfig(env='dev', lang='C', db=AppConfig.DB(name='default_db', host='localhost', port=5432, user='default_user', password=), awesome=True)\n >>> cfg.db.password\n 's3kr3t'\n\n\nFeatures\n========\n\n- Declarative & boilerplate-free.\n- Nested config from flat env variable names.\n- Default & mandatory values: enforce configuration structure without writing a line of code.\n- Helpful debug logging that will tell you which variables are present and what ``environ_config`` is looking for.\n- Built on top of `attrs `_ which gives you data validation and conversion for free.\n- Plugable secrets extraction.\n Ships with:\n\n * `HashiCorp Vault `_ support via `envconsul `_.\n * INI files, because secrets in env variables are `icky `_.\n- Pass any dict into ``environ.to_config(AppConfig, {\"your\": \"config\"})`` instead of loading from the environment.\n- Built in dynamic help documentation generation via ``environ.generate_help``.\n\n.. code-block:: pycon\n\n >>> import environ\n >>> @environ.config(prefix=\"APP\")\n ... class AppConfig:\n ... @environ.config\n ... class SubConfig:\n ... sit = environ.var(help=\"Another example message.\")\n ... amet = environ.var()\n ... lorem = environ.var('ipsum')\n ... dolor = environ.bool_var(True, help=\"An example message.\")\n ... subconfig = environ.group(SubConfig)\n ...\n >>> print(environ.generate_help(AppConfig))\n APP_LOREM (Optional)\n APP_DOLOR (Optional): An example message.\n APP_SUBCONFIG_SIT (Required): Another example message.\n APP_SUBCONFIG_AMET (Required)\n >>> print(environ.generate_help(AppConfig, display_defaults=True))\n APP_LOREM (Optional, Default=ipsum)\n APP_DOLOR (Optional, Default=True): An example message.\n APP_SUBCONFIG_SIT (Required): Another example message.\n APP_SUBCONFIG_AMET (Required)\n\n\nProject Information\n===================\n\n``environ_config`` is released under the `Apache License 2.0 `_ license.\nIt targets Python 2.7, 3.5 and newer, and PyPy.\n\n```\n\n### src/environ/_environ_config.py\n```python\n# Copyright 2017 Hynek Schlawack\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 the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport logging\nimport os\n\nimport attr\n\nfrom .exceptions import MissingEnvValueError\n\n\nlog = logging.getLogger(__name__)\n\n\nCNF_KEY = \"environ_config\"\n\n\n@attr.s\nclass Raise(object):\n pass\n\n\nRAISE = Raise()\n\n\ndef config(maybe_cls=None, prefix=\"APP\"):\n def wrap(cls):\n cls._prefix = prefix\n return attr.s(cls, slots=True)\n\n if maybe_cls is None:\n return wrap\n else:\n return wrap(maybe_cls)\n\n\n@attr.s(slots=True)\nclass _ConfigEntry(object):\n name = attr.ib(default=None)\n default = attr.ib(default=RAISE)\n sub_cls = attr.ib(default=None)\n callback = attr.ib(default=None)\n help = attr.ib(default=None)\n\n\ndef var(default=RAISE, converter=None, name=None, validator=None, help=None):\n return attr.ib(\n default=default,\n metadata={CNF_KEY: _ConfigEntry(name, default, None, None, help)},\n converter=converter,\n validator=validator,\n )\n\n\ndef _env_to_bool(val):\n \"\"\"\n Convert *val* to a bool if it's not a bool in the first place.\n \"\"\"\n if isinstance(val, bool):\n return val\n val = val.strip().lower()\n if val in (\"1\", \"true\", \"yes\"):\n return True\n\n return False\n\n\ndef bool_var(default=RAISE, name=None, help=None):\n return var(default=default, name=name, converter=_env_to_bool, help=help)\n\n\ndef group(cls):\n return attr.ib(\n default=None, metadata={CNF_KEY: _ConfigEntry(None, None, cls, True)}\n )\n\n\ndef to_config(config_cls, environ=os.environ):\n if config_cls._prefix:\n app_prefix = (config_cls._prefix,)\n else:\n app_prefix = ()\n\n def default_get(environ, metadata, prefix, name):\n ce = metadata[CNF_KEY]\n if ce.name is not None:\n var = ce.name\n else:\n var = (\"_\".join(app_prefix + prefix + (name,))).upper()\n\n log.debug(\"looking for env var '%s'.\" % (var,))\n val = environ.get(var, ce.default)\n if val is RAISE:\n raise MissingEnvValueError(var)\n return val\n\n return _to_config(config_cls, default_get, environ, ())\n\n\ndef _to_config(config_cls, default_get, environ, prefix):\n vals = {}\n for a in attr.fields(config_cls):\n try:\n ce = a.metadata[CNF_KEY]\n except KeyError:\n continue\n if ce.sub_cls is None:\n get = ce.callback or default_get\n val = get(environ, a.metadata, prefix, a.name)\n else:\n val = _to_config(\n ce.sub_cls,\n default_get,\n environ,\n prefix + ((a.name if prefix else a.name),),\n )\n\n vals[a.name] = val\n return config_cls(**vals)\n\n\ndef _format_help_dicts(help_dicts, display_defaults=False):\n \"\"\"\n Format the output of _generate_help_dicts into a str\n \"\"\"\n help_strs = []\n for help_dict in help_dicts:\n help_str = \"%s (%s\" % (\n help_dict[\"var_name\"],\n \"Required\" if help_dict[\"required\"] else \"Optional\",\n )\n if help_dict.get(\"default\") and display_defaults:\n help_str += \", Default=%s)\" % help_dict[\"default\"]\n else:\n help_str += \")\"\n if help_dict.get(\"help_str\"):\n help_str += \": %s\" % help_dict[\"help_str\"]\n help_strs.append(help_str)\n\n return \"\\n\".join(help_strs)\n\n\ndef _generate_help_dicts(config_cls, _prefix=None):\n \"\"\"\n Generate dictionaries for use in building help strings.\n\n Every dictionary includes the keys...\n\n var_name: The env var that should be set to populate the value.\n required: A bool, True if the var is required, False if it's optional.\n\n Conditionally, the following are included...\n\n default: Included if an optional variable has a default set\n help_str: Included if the var uses the help kwarg to provide additional\n context for the value.\n\n Conditional key inclusion is meant to differentiate between exclusion\n vs explicitly setting a value to None.\n \"\"\"\n help_dicts = []\n if _prefix is None:\n _prefix = config_cls._prefix\n for a in attr.fields(config_cls):\n try:\n ce = a.metadata[CNF_KEY]\n except KeyError:\n continue\n if ce.sub_cls is None: # Base case for \"leaves\".\n if ce.name is None:\n var_name = \"_\".join((_prefix, a.name)).upper()\n else:\n var_name = ce.name\n req = ce.default == RAISE\n help_dict = {\"var_name\": var_name, \"required\": req}\n if not req:\n help_dict[\"default\"] = ce.default\n if ce.help is not None:\n help_dict[\"help_str\"] = ce.help\n help_dicts.append(help_dict)\n else: # Construct the new prefix and recurse.\n help_dicts += _generate_help_dicts(\n ce.sub_cls, _prefix=\"_\".join((_prefix, a.name)).upper()\n )\n return help_dicts\n\n\ndef generate_help(config_cls, **kwargs):\n \"\"\"\n Autogenerate a help string for a config class.\n\n If a callable is provided via the \"formatter\" kwarg it\n will be provided with the help dictionaries as an argument\n and any other kwargs provided to this function. That callable\n should return the help text string.\n \"\"\"\n try:\n formatter = kwargs.pop(\"formatter\")\n except KeyError:\n formatter = _format_help_dicts\n help_dicts = _generate_help_dicts(config_cls)\n return formatter(help_dicts, **kwargs)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "hynek__environ-config-079644d378ac", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/hynek__environ-config-079644d378ac", "repo_key": "hynek__environ-config", "repo": "hynek/environ-config", "base_commit": "d61c0822bf0b6516932534e0496bd3f360a3e5e2", "source_files": ["README.rst", "src/environ/_environ_config.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `group_by_prefix` incorrectly groups items with similar prefixes\n\n## Description\nWhen using `group_by_prefix`, items whose names share a common prefix but are intended to be distinct groups are incorrectly grouped together. For example, if a dataset contains `image_130.jpg` and `image_1300.jpg`, both files are treated as belonging to the same group.\n\nExpected behavior: `image_130.jpg` and `image_1300.jpg` should be recognized as separate groups if their full names (excluding extension) are distinct.\nActual behavior: `image_130.jpg` and `image_1300.jpg` are grouped together due to an overly broad prefix matching logic.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `25ce6a9838c6` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### README.md\n```python\n# `split-folders` [![Build Status](https://img.shields.io/github/workflow/status/jfilter/split-folders/Test)](https://github.com/jfilter/split-folders/actions/workflows/test.yml) [![PyPI](https://img.shields.io/pypi/v/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Downloads](https://img.shields.io/pypi/dm/split-folders)](https://pypistats.org/packages/split-folders)\n\nSplit folders with files (e.g. images) into **train**, **validation** and **test** (dataset) folders.\n\nThe input folder should have the following format:\n\n```\ninput/\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n```\n\nIn order to give you this:\n\n```\noutput/\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n```\n\nThis should get you started to do some serious deep learning on your data. [Read here](https://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set) why it's a good idea to split your data intro three different sets.\n\n- Split files into a training set and a validation set (and optionally a test set).\n- Works on any file types.\n- The files get shuffled.\n- A [seed](https://docs.python.org/3/library/random.html#random.seed) makes splits reproducible.\n- Allows randomized [oversampling](https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis) for imbalanced datasets.\n- Optionally group files by prefix.\n- Optionally split files by file format(s).\n- (Should) work on all operating systems.\n\n## Install\n\nThis package is Python only and there are no external dependencies.\n\n```bash\npip install split-folders\n```\n\nOptionally, you may install [tqdm](https://github.com/tqdm/tqdm) to get a progress bar when moving files.\n\n```bash\npip install split-folders[full]\n```\n\n## Usage\n\nYou can use `split-folders` as Python module or as a Command Line Interface (CLI).\n\nIf your datasets is balanced (each class has the same number of samples), choose `ratio` otherwise `fixed`.\nNB: oversampling is turned off by default.\nOversampling is only applied to the _train_ folder since having duplicates in _val_ or _test_ would be considered cheating.\n\n### Module\n\n```python\nimport splitfolders\n\n# Split with a ratio.\n# To only split into training and validation set, set a tuple to `ratio`, i.e, `(.8, .2)`.\nsplitfolders.ratio(\"input_folder\", output=\"output\",\n seed=1337, ratio=(.8, .1, .1), group_prefix=None, formats=None, move=False) # default values\n\n# Split val/test with a fixed number of items, e.g. `(100, 100)`, for each set.\n# To only split into training and validation set, use a single number to `fixed`, i.e., `10`.\n# Set 3 values, e.g. `(300, 100, 100)`, to limit the number of training values.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=(100, 100), oversample=False, group_prefix=None, formats=None, move=False) # default values\n\n# Use `fixed=\"auto\"` with oversampling to auto-compute the val size from the smallest class.\n# Allocates ~20% of the smallest class to validation, rest to training.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=\"auto\", oversample=True)\n\n# Split into k folds for cross-validation.\n# Each fold directory contains train/ and val/ subdirectories.\n# Uses symlinks by default to avoid k\u00d7 disk usage.\nsplitfolders.kfold(\"input_folder\", output=\"output\",\n seed=1337, k=5, group_prefix=None, formats=None, move=\"symlink\") # default values\n```\n\nOccasionally, you may have things that comprise more than a single file (e.g. picture (.png) + annotation (.txt)).\n`splitfolders` lets you split files into equally-sized groups based on their prefix.\nSet `group_prefix` to the length of the group (e.g. `2`).\nBut now _all_ files should be part of groups.\n\nAlso, there might be some instances when you have multiple file formats in these folders. Provide one or multiple extension(s) to `formats` for splitting the files in a list (e.g. `formats = ['.jpeg','.png']`).\n\nSet\n- `move=True` or `move='move'` if you want to move the files instead of copying.\n- `move=False` or `move='copy'` if you want to copy the files. (default behavior)\n- `move='symlink'` if you want to symlink (i.e. create shortcuts `ln -s`) instead of copying.\n\n### CLI\n\n```\nUsage:\n splitfolders [--output] [--ratio] [--fixed] [--kfold] [--seed] [--oversample] [--group_prefix] [--formats] [--move] folder_with_images\nOptions:\n --output path to the output folder. defaults to `output`. Get created if non-existent.\n --ratio the ratio to split. e.g. for train/val/test `.8 .1 .1 --` or for train/val `.8 .2 --`.\n --fixed set the absolute number of items per validation/test set. The remaining items constitute\n the training set. e.g. for train/val/test `100 100` or for train/val `100`.\n Set 3 values, e.g. `300 100 100`, to limit the number of training values.\n Use `auto` to auto-compute from the smallest class (requires --oversample).\n --kfold split into k folds for cross-validation. e.g. `5` for 5-fold CV. Uses symlinks by default.\n --seed set seed value for shuffling the items. defaults to 1337.\n --oversample enable oversampling of imbalanced datasets, works only with --fixed.\n --group_prefix split files into equally-sized groups based on their prefix\n --formats split the files based on specified extension(s)\n --move move the files instead of copying\n --symlink symlink(create shortcut) the files instead of copying\nExample:\n splitfolders --ratio .8 .1 .1 -- folder_with_images\n splitfolders --kfold 5 folder_with_images\n```\n\nBecause of some [Python quirks](https://github.com/jfilter/split-folders/issues/19) you have to prepend ` --` after using `--ratio`.\n\nInstead of the command `splitfolders` you can also use `split_folders` or `split-folders`.\n\n## Development\n\nInstall and use [poetry](https://python-poetry.org/).\n\n## Contributing\n\nIf you have a **question**, found a **bug** or want to propose a new **feature**, have a look at the [issues page](https://github.com/jfilter/split-folders/issues).\n\n**Pull requests** are especially welcomed when they fix bugs or improve the code quality.\n\n## License\n\nMIT\n\n```\n\n### splitfolders/cli.py\n```python\nimport argparse\n\nfrom .split import fixed, kfold, ratio\n\n\ndef run():\n parser = argparse.ArgumentParser(\n description=(\n \"Split folders with files (e.g. images) by copying them\"\n \" into training, validation and test (dataset) folders.\"\n )\n )\n parser.add_argument(\n \"--output\",\n default=\"output\",\n help=\"directory where to write the resulting split folders, defaults to `output`\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=\"1337\",\n help=\"a seed value to make your split reproducible\",\n )\n parser.add_argument(\n \"--ratio\",\n nargs=\"+\",\n type=float,\n help=\"the ratio to split. e.g. for train/val/test `.8 .1 .1` or for train/val `.8 .2`\",\n )\n parser.add_argument(\n \"--fixed\",\n nargs=\"+\",\n type=str,\n help=(\n \"set the absolute number of items per validation/test set.\"\n \" The remaining items get to the training.\"\n \" e.g. for train/val/test `100 100` or for train/val `100`.\"\n \" Set 3 values, e.g. `300 100 100`, to limit the number of training values.\"\n ' Use `auto` to auto-compute from the smallest class (requires --oversample).'\n ),\n )\n parser.add_argument(\n \"--kfold\",\n type=int,\n default=None,\n help=\"split into k folds for cross-validation. e.g. `5` for 5-fold CV. Each fold has train/ and val/ subdirs.\",\n )\n parser.add_argument(\n \"--oversample\",\n action=\"store_true\",\n help=\"enable oversampling of imbalanced datasets\",\n )\n parser.add_argument(\n \"--group_prefix\",\n type=int,\n default=None,\n help=\"split files into equally-sized groups based on their prefix\",\n )\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n \"--move\",\n action=\"store_true\",\n help=\"move the files instead of copying\",\n )\n group.add_argument(\n \"--symlink\",\n action=\"store_true\",\n help=\"symlink(create shortcut) the files instead of copying\",\n )\n parser.add_argument(\n \"input\",\n help=(\n \"directory with the input data. The directory needs to have the labels\"\n \" as sub-directories. In those sub-directories are then the actual files\"\n \" that gets split.\"\n ),\n )\n parser.add_argument(\n \"--formats\",\n nargs=\"+\",\n type=str,\n default=None,\n help=\"specify the file format(s) which should be considered for spliting the data e.g. `.png .jpeg .jpg`\",\n )\n\n args = parser.parse_args()\n\n if args.symlink:\n args.move = \"symlink\"\n\n if args.ratio:\n ratio(args.input, args.output, args.seed, args.ratio, args.group_prefix, args.move, args.formats)\n elif args.fixed:\n if args.fixed == [\"auto\"]:\n fixed_value = \"auto\"\n else:\n fixed_value = [int(x) for x in args.fixed]\n fixed(\n args.input,\n args.output,\n args.seed,\n fixed_value,\n args.oversample,\n args.group_prefix,\n args.move,\n args.formats,\n )\n elif args.kfold:\n kfold(\n args.input,\n args.output,\n args.seed,\n args.kfold,\n args.group_prefix,\n args.move if args.move else \"symlink\",\n args.formats,\n )\n else:\n print(\"Please specify either your `--ratio`, `--fixed`, or `--kfold` for the split. see -h for more help.\")\n\n```\n\n### splitfolders/split.py\n```python\n\"\"\"Splits a folder with the given format:\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n\ninto this resulting format:\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n\"\"\"\n\nimport os\nimport random\nimport shutil\nfrom pathlib import Path\n\nfrom .utils import list_dirs, list_files\n\ntry:\n from tqdm import tqdm\n\n use_tqdm = True\nexcept ImportError:\n use_tqdm = False\n\n\ndef check_input_format(input):\n p_input = Path(input)\n if not p_input.exists():\n err_msg = f'The provided input folder \"{input}\" does not exists.'\n if not p_input.is_absolute():\n err_msg += f' Your relative path cannot be found from the current working directory \"{Path.cwd()}\".'\n raise ValueError(err_msg)\n\n if not p_input.is_dir():\n raise ValueError(f'The provided input folder \"{input}\" is not a directory')\n\n dirs = list_dirs(input)\n if len(dirs) == 0:\n raise ValueError(\n f'The input data is not in a right format. Within your folder \"{input}\"'\n \" there are no directories. Consult the documentation how to the folder\"\n \" structure should look like.\"\n )\n\n\ndef _get_copy_fn(move):\n \"\"\"Return a function(src, dst_dir) that copies/moves/symlinks a file into dst_dir.\"\"\"\n if move is True or move == \"move\":\n base_fn = shutil.move\n elif move is False or move == \"copy\":\n base_fn = shutil.copy2\n elif move == \"symlink\":\n base_fn = None # handled below\n else:\n raise ValueError(f\"Invalid value for move: {move!r}. Use True, False, or 'symlink'.\")\n\n def copy_fn(src, dst_dir):\n src = Path(src)\n dst_dir = Path(dst_dir)\n if move == \"symlink\":\n dst = dst_dir / src.name\n try:\n os.symlink(src.resolve(), dst)\n except FileExistsError:\n pass\n else:\n base_fn(str(src), str(dst_dir))\n\n return copy_fn\n\n\ndef valid_extensions(formats):\n \"\"\"\n Check if an extension starts with `.`\n \"\"\"\n if formats is None:\n return\n invalid_ext = [s for s in formats if not s.startswith(\".\")]\n if invalid_ext:\n raise ValueError(f\"Extensions must start with '.': {invalid_ext}\")\n\n\ndef ratio(input, output=\"output\", seed=1337, ratio=(0.8, 0.1, 0.1), group_prefix=None, move=False, formats=None):\n if not round(sum(ratio), 5) == 1: # round for floating imprecision\n raise ValueError(\"The sums of `ratio` is over 1.\")\n if len(ratio) not in (2, 3):\n raise ValueError(\"`ratio` should\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n for class_dir in list_dirs(input):\n split_class_dir_ratio(\n class_dir, output, ratio, seed, prog_bar if use_tqdm else None, group_prefix, move, formats\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef fixed(\n input, output=\"output\", seed=1337, fixed=(100, 100), oversample=False, group_prefix=None, move=False, formats=None\n):\n check_input_format(input)\n valid_extensions(formats)\n\n if fixed == \"auto\":\n if not oversample:\n raise ValueError(\n '`fixed=\"auto\"` requires `oversample=True`. For non-oversampled splits, use `ratio` instead.'\n )\n # Count files per class and derive fixed from the smallest class\n classes_dirs = list_dirs(input)\n counts = []\n for class_dir in classes_dirs:\n files = list_files(class_dir, formats)\n if group_prefix is not None:\n files = group_by_prefix(files, group_prefix)\n counts.append(len(files))\n min_count = min(counts)\n fixed = [max(1, min_count // 5)]\n else:\n if isinstance(fixed, int):\n fixed = [fixed]\n\n if len(fixed) not in (1, 2, 3):\n raise ValueError(\"`fixed` should be an integer or a list of 2 or 3 integers\")\n\n if len(fixed) == 3 and oversample:\n raise ValueError(\"Using fixed with 3 values together with oversampling is not implemented.\")\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n classes_dirs = list_dirs(input)\n num_items = []\n for class_dir in classes_dirs:\n num_items.append(\n split_class_dir_fixed(\n class_dir, output, fixed, seed, prog_bar if use_tqdm else None, group_prefix, move, formats\n )\n )\n\n if use_tqdm:\n prog_bar.close()\n\n if not oversample:\n return\n\n num_max_items = max(num_items)\n iteration = zip(num_items, classes_dirs)\n\n if use_tqdm:\n iteration = tqdm(iteration, desc=\"Oversampling\", unit=\" classes\")\n\n for num_items, class_dir in iteration:\n class_name = Path(class_dir).name\n full_path = Path(output) / \"train\" / class_name\n train_files = list_files(full_path, formats)\n\n if group_prefix is not None:\n train_files = group_by_prefix(train_files, group_prefix)\n\n for i in range(num_max_items - num_items):\n f_chosen = random.choice(train_files)\n\n if not isinstance(f_chosen, tuple):\n f_chosen = (f_chosen,)\n\n for f_orig in f_chosen:\n new_name = f_orig.stem + \"_\" + str(i) + f_orig.suffix\n f_dest = f_orig.with_name(new_name)\n if move == \"symlink\":\n try:\n os.symlink(f_orig.resolve(), f_dest)\n except FileExistsError:\n pass\n elif move is True or move == \"move\":\n shutil.move(str(f_orig), str(f_dest))\n else:\n shutil.copy2(str(f_orig), str(f_dest))\n\n\ndef kfold(input, output=\"output\", seed=1337, k=5, group_prefix=None, move=\"symlink\", formats=None):\n if k < 2:\n raise ValueError(\"`k` must be 2 or greater.\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n for class_dir in list_dirs(input):\n split_class_dir_kfold(class_dir, output, k, seed, prog_bar if use_tqdm else None, group_prefix, move, formats)\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef split_class_dir_kfold(class_dir, output, k, seed, prog_bar, group_prefix, move, formats):\n \"\"\"\n Splits a class folder into k folds for cross-validation.\n Each fold directory gets train/ and val/ subdirectories.\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, formats)\n\n # Partition files into k roughly equal chunks\n fold_size = len(files) // k\n remainder = len(files) % k\n partitions = []\n idx = 0\n for i in range(k):\n size = fold_size + (1 if i < remainder else 0)\n partitions.append(files[idx : idx + size])\n idx += size\n\n # For each fold, val = partition i, train = all other partitions\n for i in range(k):\n val_files = partitions[i]\n train_files = [f for j, part in enumerate(partitions) if j != i for f in part]\n fold_output = str(Path(output) / f\"fold_{i + 1}\")\n li = [(train_files, \"train\"), (val_files, \"val\")]\n copy_files(li, class_dir, fold_output, prog_bar, move)\n\n\ndef group_by_prefix(files, len_pairs):\n \"\"\"\n Split files into groups of len `len_pairs` based on their prefix.\n \"\"\"\n results = []\n results_set = set() # for fast lookup, only file names\n for f in files:\n if f.name in results_set:\n continue\n f_sub = f.name\n for _ in range(len(f_sub)):\n matches = [x for x in files if x.name not in results_set and x.name.startswith(f_sub) and f.name != x.name]\n if len(matches) == len_pairs - 1:\n results.append((f, *matches))\n results_set.update((f.name, *[x.name for x in matches]))\n break\n elif len(matches) < len_pairs - 1:\n f_sub = f_sub[:-1]\n else:\n raise ValueError(\n f\"The length of pairs has to be equal. Coudn't find {len_pairs - 1}\"\n f\" matches for {f}. Found {len(matches)} matches.\"\n )\n else:\n raise ValueError(f\"No adequate matches found for {f}.\")\n\n if len(results_set) != len(files):\n raise ValueError(f\"Could not find enough matches ({len(results_set)}) for all files ({len(files)})\")\n return results\n\n\ndef setup_files(class_dir, seed, group_prefix=None, formats=None):\n \"\"\"\n Returns shuffeld list of filenames\n \"\"\"\n random.seed(seed) # make sure its reproducible\n\n files = list_files(class_dir, formats)\n\n if group_prefix is not None:\n files = group_by_prefix(files, group_prefix)\n\n files.sort()\n random.shuffle(files)\n return files\n\n\ndef split_class_dir_ratio(class_dir, output, ratio, seed, prog_bar, group_prefix, move, formats):\n \"\"\"\n Splits a class folder\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, formats)\n\n # the data was shuffled already\n split_train_idx = int(ratio[0] * len(files))\n split_val_idx = split_train_idx + int(ratio[1] * len(files))\n\n li = split_files(files, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_files(li, class_dir, output, prog_bar, move)\n\n\ndef split_class_dir_fixed(class_dir, output, fixed, seed, prog_bar, group_prefix, move, formats):\n \"\"\"\n Splits a class folder and returns the total number of files\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, formats)\n\n if not len(files) >= sum(fixed):\n raise ValueError(\n f'The number of samples in class \"{class_dir.stem}\" are too few.'\n f\" There are only {len(files)} samples available but your fixed parameter\"\n f\" {fixed} requires at least {sum(fixed)} files.\"\n \" You may want to split your classes by ratio.\"\n )\n\n # the data was shuffeld already\n if len(fixed) <= 2:\n split_train_idx = len(files) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n else:\n split_train_idx = fixed[0]\n split_val_idx = fixed[0] + fixed[1]\n\n li = split_files(\n files,\n split_train_idx,\n split_val_idx,\n len(fixed) >= 2,\n None if len(fixed) != 3 else fixed[2],\n )\n copy_files(li, class_dir, output, prog_bar, move)\n return len(files)\n\n\ndef split_files(files, split_train_idx, split_val_idx, use_test, max_test=None):\n \"\"\"\n Splits the files along the provided indices\n \"\"\"\n files_train = files[:split_train_idx]\n files_val = files[split_train_idx:split_val_idx] if use_test else files[split_train_idx:]\n\n li = [(files_train, \"train\"), (files_val, \"val\")]\n\n # optional test folder\n if use_test:\n files_test = files[split_val_idx:]\n if max_test is not None:\n files_test = files_test[:max_test]\n\n li.append((files_test, \"test\"))\n return li\n\n\ndef copy_files(files_type, class_dir, output, prog_bar, move):\n \"\"\"\n Copies the files from the input folder to the output folder\n \"\"\"\n copy_fn = _get_copy_fn(move)\n\n class_name = Path(class_dir).name\n for files, folder_type in files_type:\n full_path = Path(output) / folder_type / class_name\n\n full_path.mkdir(parents=True, exist_ok=True)\n for f in files:\n if prog_bar is not None:\n prog_bar.update()\n if isinstance(f, tuple):\n for x in f:\n copy_fn(x, full_path)\n else:\n copy_fn(f, full_path)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "jfilter__split-folders-2551252bc5af", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/jfilter__split-folders-2551252bc5af", "repo_key": "jfilter__split-folders", "repo": "jfilter/split-folders", "base_commit": "25ce6a9838c61cdd709ef390df77e56111cfc502", "source_files": ["README.md", "splitfolders/cli.py", "splitfolders/grouping.py", "splitfolders/split.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `fixed=\"auto\"` validation split fails or is incorrect when `oversample=True`\n\n## Description\nWhen configuring a dataset with `oversample=True`, setting the validation split parameter to `fixed=\"auto\"` does not result in the expected automatic computation of the validation set size. Instead of allocating approximately 20% of the smallest class to validation, the operation either fails or produces an incorrect validation split.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `cef6ff3e976a` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### README.md\n```python\n# `split-folders` [![Build Status](https://img.shields.io/github/workflow/status/jfilter/split-folders/Test)](https://github.com/jfilter/split-folders/actions/workflows/test.yml) [![PyPI](https://img.shields.io/pypi/v/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Downloads](https://img.shields.io/pypi/dm/split-folders)](https://pypistats.org/packages/split-folders)\n\nSplit folders with files (e.g. images) into **train**, **validation** and **test** (dataset) folders.\n\nThe input folder should have the following format:\n\n```\ninput/\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n```\n\nIn order to give you this:\n\n```\noutput/\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n```\n\nThis should get you started to do some serious deep learning on your data. [Read here](https://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set) why it's a good idea to split your data intro three different sets.\n\n- Split files into a training set and a validation set (and optionally a test set).\n- Works on any file types.\n- The files get shuffled.\n- A [seed](https://docs.python.org/3/library/random.html#random.seed) makes splits reproducible.\n- Allows randomized [oversampling](https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis) for imbalanced datasets.\n- Optionally group files by prefix.\n- Optionally split files by file format(s).\n- (Should) work on all operating systems.\n\n## Install\n\nThis package is Python only and there are no external dependencies.\n\n```bash\npip install split-folders\n```\n\nOptionally, you may install [tqdm](https://github.com/tqdm/tqdm) to get a progress bar when moving files.\n\n```bash\npip install split-folders[full]\n```\n\n## Usage\n\nYou can use `split-folders` as Python module or as a Command Line Interface (CLI).\n\nIf your datasets is balanced (each class has the same number of samples), choose `ratio` otherwise `fixed`.\nNB: oversampling is turned off by default.\nOversampling is only applied to the _train_ folder since having duplicates in _val_ or _test_ would be considered cheating.\n\n### Module\n\n```python\nimport splitfolders\n\n# Split with a ratio.\n# To only split into training and validation set, set a tuple to `ratio`, i.e, `(.8, .2)`.\nsplitfolders.ratio(\"input_folder\", output=\"output\",\n seed=1337, ratio=(.8, .1, .1), group_prefix=None, formats=None, move=False) # default values\n\n# Split val/test with a fixed number of items, e.g. `(100, 100)`, for each set.\n# To only split into training and validation set, use a single number to `fixed`, i.e., `10`.\n# Set 3 values, e.g. `(300, 100, 100)`, to limit the number of training values.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=(100, 100), oversample=False, group_prefix=None, formats=None, move=False) # default values\n\n# Split into k folds for cross-validation.\n# Each fold directory contains train/ and val/ subdirectories.\n# Uses symlinks by default to avoid k\u00d7 disk usage.\nsplitfolders.kfold(\"input_folder\", output=\"output\",\n seed=1337, k=5, group_prefix=None, formats=None, move=\"symlink\") # default values\n```\n\nOccasionally, you may have things that comprise more than a single file (e.g. picture (.png) + annotation (.txt)).\n`splitfolders` lets you split files into equally-sized groups based on their prefix.\nSet `group_prefix` to the length of the group (e.g. `2`).\nBut now _all_ files should be part of groups.\n\nAlso, there might be some instances when you have multiple file formats in these folders. Provide one or multiple extension(s) to `formats` for splitting the files in a list (e.g. `formats = ['.jpeg','.png']`).\n\nSet\n- `move=True` or `move='move'` if you want to move the files instead of copying.\n- `move=False` or `move='copy'` if you want to copy the files. (default behavior)\n- `move='symlink'` if you want to symlink (i.e. create shortcuts `ln -s`) instead of copying.\n\n### CLI\n\n```\nUsage:\n splitfolders [--output] [--ratio] [--fixed] [--kfold] [--seed] [--oversample] [--group_prefix] [--formats] [--move] folder_with_images\nOptions:\n --output path to the output folder. defaults to `output`. Get created if non-existent.\n --ratio the ratio to split. e.g. for train/val/test `.8 .1 .1 --` or for train/val `.8 .2 --`.\n --fixed set the absolute number of items per validation/test set. The remaining items constitute\n the training set. e.g. for train/val/test `100 100` or for train/val `100`.\n Set 3 values, e.g. `300 100 100`, to limit the number of training values.\n --kfold split into k folds for cross-validation. e.g. `5` for 5-fold CV. Uses symlinks by default.\n --seed set seed value for shuffling the items. defaults to 1337.\n --oversample enable oversampling of imbalanced datasets, works only with --fixed.\n --group_prefix split files into equally-sized groups based on their prefix\n --formats split the files based on specified extension(s)\n --move move the files instead of copying\n --symlink symlink(create shortcut) the files instead of copying\nExample:\n splitfolders --ratio .8 .1 .1 -- folder_with_images\n splitfolders --kfold 5 folder_with_images\n```\n\nBecause of some [Python quirks](https://github.com/jfilter/split-folders/issues/19) you have to prepend ` --` after using `--ratio`.\n\nInstead of the command `splitfolders` you can also use `split_folders` or `split-folders`.\n\n## Development\n\nInstall and use [poetry](https://python-poetry.org/).\n\n## Contributing\n\nIf you have a **question**, found a **bug** or want to propose a new **feature**, have a look at the [issues page](https://github.com/jfilter/split-folders/issues).\n\n**Pull requests** are especially welcomed when they fix bugs or improve the code quality.\n\n## License\n\nMIT\n\n```\n\n### splitfolders/cli.py\n```python\nimport argparse\n\nfrom .split import fixed, kfold, ratio\n\n\ndef run():\n parser = argparse.ArgumentParser(\n description=(\n \"Split folders with files (e.g. images) by copying them\"\n \" into training, validation and test (dataset) folders.\"\n )\n )\n parser.add_argument(\n \"--output\",\n default=\"output\",\n help=\"directory where to write the resulting split folders, defaults to `output`\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=\"1337\",\n help=\"a seed value to make your split reproducible\",\n )\n parser.add_argument(\n \"--ratio\",\n nargs=\"+\",\n type=float,\n help=\"the ratio to split. e.g. for train/val/test `.8 .1 .1` or for train/val `.8 .2`\",\n )\n parser.add_argument(\n \"--fixed\",\n nargs=\"+\",\n type=int,\n help=(\n \"set the absolute number of items per validation/test set.\"\n \" The remaining items get to the training.\"\n \" e.g. for train/val/test `100 100` or for train/val `100`.\"\n \" Set 3 values, e.g. `300 100 100`, to limit the number of training values.\"\n ),\n )\n parser.add_argument(\n \"--kfold\",\n type=int,\n default=None,\n help=\"split into k folds for cross-validation. e.g. `5` for 5-fold CV. Each fold has train/ and val/ subdirs.\",\n )\n parser.add_argument(\n \"--oversample\",\n action=\"store_true\",\n help=\"enable oversampling of imbalanced datasets\",\n )\n parser.add_argument(\n \"--group_prefix\",\n type=int,\n default=None,\n help=\"split files into equally-sized groups based on their prefix\",\n )\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n \"--move\",\n action=\"store_true\",\n help=\"move the files instead of copying\",\n )\n group.add_argument(\n \"--symlink\",\n action=\"store_true\",\n help=\"symlink(create shortcut) the files instead of copying\",\n )\n parser.add_argument(\n \"input\",\n help=(\n \"directory with the input data. The directory needs to have the labels\"\n \" as sub-directories. In those sub-directories are then the actual files\"\n \" that gets split.\"\n ),\n )\n parser.add_argument(\n \"--formats\",\n nargs=\"+\",\n type=str,\n default=None,\n help=\"specify the file format(s) which should be considered for spliting the data e.g. `.png .jpeg .jpg`\",\n )\n\n args = parser.parse_args()\n\n if args.symlink:\n args.move = \"symlink\"\n\n if args.ratio:\n ratio(args.input, args.output, args.seed, args.ratio, args.group_prefix, args.move, args.formats)\n elif args.fixed:\n fixed(\n args.input,\n args.output,\n args.seed,\n args.fixed,\n args.oversample,\n args.group_prefix,\n args.move,\n args.formats,\n )\n elif args.kfold:\n kfold(\n args.input,\n args.output,\n args.seed,\n args.kfold,\n args.group_prefix,\n args.move if args.move else \"symlink\",\n args.formats,\n )\n else:\n print(\"Please specify either your `--ratio`, `--fixed`, or `--kfold` for the split. see -h for more help.\")\n\n```\n\n### splitfolders/split.py\n```python\n\"\"\"Splits a folder with the given format:\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n\ninto this resulting format:\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n\"\"\"\n\nimport os\nimport random\nimport shutil\nfrom pathlib import Path\n\nfrom .utils import list_dirs, list_files\n\ntry:\n from tqdm import tqdm\n\n use_tqdm = True\nexcept ImportError:\n use_tqdm = False\n\n\ndef check_input_format(input):\n p_input = Path(input)\n if not p_input.exists():\n err_msg = f'The provided input folder \"{input}\" does not exists.'\n if not p_input.is_absolute():\n err_msg += f' Your relative path cannot be found from the current working directory \"{Path.cwd()}\".'\n raise ValueError(err_msg)\n\n if not p_input.is_dir():\n raise ValueError(f'The provided input folder \"{input}\" is not a directory')\n\n dirs = list_dirs(input)\n if len(dirs) == 0:\n raise ValueError(\n f'The input data is not in a right format. Within your folder \"{input}\"'\n \" there are no directories. Consult the documentation how to the folder\"\n \" structure should look like.\"\n )\n\n\ndef _get_copy_fn(move):\n \"\"\"Return a function(src, dst_dir) that copies/moves/symlinks a file into dst_dir.\"\"\"\n if move is True or move == \"move\":\n base_fn = shutil.move\n elif move is False or move == \"copy\":\n base_fn = shutil.copy2\n elif move == \"symlink\":\n base_fn = None # handled below\n else:\n raise ValueError(f\"Invalid value for move: {move!r}. Use True, False, or 'symlink'.\")\n\n def copy_fn(src, dst_dir):\n src = Path(src)\n dst_dir = Path(dst_dir)\n if move == \"symlink\":\n dst = dst_dir / src.name\n try:\n os.symlink(src.resolve(), dst)\n except FileExistsError:\n pass\n else:\n base_fn(str(src), str(dst_dir))\n\n return copy_fn\n\n\ndef valid_extensions(formats):\n \"\"\"\n Check if an extension starts with `.`\n \"\"\"\n if formats is None:\n return\n invalid_ext = [s for s in formats if not s.startswith(\".\")]\n if invalid_ext:\n raise ValueError(f\"Extensions must start with '.': {invalid_ext}\")\n\n\ndef ratio(input, output=\"output\", seed=1337, ratio=(0.8, 0.1, 0.1), group_prefix=None, move=False, formats=None):\n if not round(sum(ratio), 5) == 1: # round for floating imprecision\n raise ValueError(\"The sums of `ratio` is over 1.\")\n if len(ratio) not in (2, 3):\n raise ValueError(\"`ratio` should\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n for class_dir in list_dirs(input):\n split_class_dir_ratio(\n class_dir, output, ratio, seed, prog_bar if use_tqdm else None, group_prefix, move, formats\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef fixed(\n input, output=\"output\", seed=1337, fixed=(100, 100), oversample=False, group_prefix=None, move=False, formats=None\n):\n if isinstance(fixed, int):\n fixed = [fixed]\n\n if len(fixed) not in (1, 2, 3):\n raise ValueError(\"`fixed` should be an integer or a list of 2 or 3 integers\")\n\n if len(fixed) == 3 and oversample:\n raise ValueError(\"Using fixed with 3 values together with oversampling is not implemented.\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n classes_dirs = list_dirs(input)\n num_items = []\n for class_dir in classes_dirs:\n num_items.append(\n split_class_dir_fixed(\n class_dir, output, fixed, seed, prog_bar if use_tqdm else None, group_prefix, move, formats\n )\n )\n\n if use_tqdm:\n prog_bar.close()\n\n if not oversample:\n return\n\n num_max_items = max(num_items)\n iteration = zip(num_items, classes_dirs)\n\n if use_tqdm:\n iteration = tqdm(iteration, desc=\"Oversampling\", unit=\" classes\")\n\n for num_items, class_dir in iteration:\n class_name = Path(class_dir).name\n full_path = Path(output) / \"train\" / class_name\n train_files = list_files(full_path, formats)\n\n if group_prefix is not None:\n train_files = group_by_prefix(train_files, group_prefix)\n\n for i in range(num_max_items - num_items):\n f_chosen = random.choice(train_files)\n\n if not isinstance(f_chosen, tuple):\n f_chosen = (f_chosen,)\n\n for f_orig in f_chosen:\n new_name = f_orig.stem + \"_\" + str(i) + f_orig.suffix\n f_dest = f_orig.with_name(new_name)\n if move == \"symlink\":\n try:\n os.symlink(f_orig.resolve(), f_dest)\n except FileExistsError:\n pass\n elif move is True or move == \"move\":\n shutil.move(str(f_orig), str(f_dest))\n else:\n shutil.copy2(str(f_orig), str(f_dest))\n\n\ndef kfold(input, output=\"output\", seed=1337, k=5, group_prefix=None, move=\"symlink\", formats=None):\n if k < 2:\n raise ValueError(\"`k` must be 2 or greater.\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n for class_dir in list_dirs(input):\n split_class_dir_kfold(class_dir, output, k, seed, prog_bar if use_tqdm else None, group_prefix, move, formats)\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef split_class_dir_kfold(class_dir, output, k, seed, prog_bar, group_prefix, move, formats):\n \"\"\"\n Splits a class folder into k folds for cross-validation.\n Each fold directory gets train/ and val/ subdirectories.\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, formats)\n\n # Partition files into k roughly equal chunks\n fold_size = len(files) // k\n remainder = len(files) % k\n partitions = []\n idx = 0\n for i in range(k):\n size = fold_size + (1 if i < remainder else 0)\n partitions.append(files[idx : idx + size])\n idx += size\n\n # For each fold, val = partition i, train = all other partitions\n for i in range(k):\n val_files = partitions[i]\n train_files = [f for j, part in enumerate(partitions) if j != i for f in part]\n fold_output = str(Path(output) / f\"fold_{i + 1}\")\n li = [(train_files, \"train\"), (val_files, \"val\")]\n copy_files(li, class_dir, fold_output, prog_bar, move)\n\n\ndef group_by_prefix(files, len_pairs):\n \"\"\"\n Split files into groups of len `len_pairs` based on their prefix.\n \"\"\"\n results = []\n results_set = set() # for fast lookup, only file names\n for f in files:\n if f.name in results_set:\n continue\n f_sub = f.name\n for _ in range(len(f_sub)):\n matches = [x for x in files if x.name not in results_set and x.name.startswith(f_sub) and f.name != x.name]\n if len(matches) == len_pairs - 1:\n results.append((f, *matches))\n results_set.update((f.name, *[x.name for x in matches]))\n break\n elif len(matches) < len_pairs - 1:\n f_sub = f_sub[:-1]\n else:\n raise ValueError(\n f\"The length of pairs has to be equal. Coudn't find {len_pairs - 1}\"\n f\" matches for {f}. Found {len(matches)} matches.\"\n )\n else:\n raise ValueError(f\"No adequate matches found for {f}.\")\n\n if len(results_set) != len(files):\n raise ValueError(f\"Could not find enough matches ({len(results_set)}) for all files ({len(files)})\")\n return results\n\n\ndef setup_files(class_dir, seed, group_prefix=None, formats=None):\n \"\"\"\n Returns shuffeld list of filenames\n \"\"\"\n random.seed(seed) # make sure its reproducible\n\n files = list_files(class_dir, formats)\n\n if group_prefix is not None:\n files = group_by_prefix(files, group_prefix)\n\n files.sort()\n random.shuffle(files)\n return files\n\n\ndef split_class_dir_ratio(class_dir, output, ratio, seed, prog_bar, group_prefix, move, formats):\n \"\"\"\n Splits a class folder\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, formats)\n\n # the data was shuffled already\n split_train_idx = int(ratio[0] * len(files))\n split_val_idx = split_train_idx + int(ratio[1] * len(files))\n\n li = split_files(files, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_files(li, class_dir, output, prog_bar, move)\n\n\ndef split_class_dir_fixed(class_dir, output, fixed, seed, prog_bar, group_prefix, move, formats):\n \"\"\"\n Splits a class folder and returns the total number of files\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, formats)\n\n if not len(files) >= sum(fixed):\n raise ValueError(\n f'The number of samples in class \"{class_dir.stem}\" are too few.'\n f\" There are only {len(files)} samples available but your fixed parameter\"\n f\" {fixed} requires at least {sum(fixed)} files.\"\n \" You may want to split your classes by ratio.\"\n )\n\n # the data was shuffeld already\n if len(fixed) <= 2:\n split_train_idx = len(files) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n else:\n split_train_idx = fixed[0]\n split_val_idx = fixed[0] + fixed[1]\n\n li = split_files(\n files,\n split_train_idx,\n split_val_idx,\n len(fixed) >= 2,\n None if len(fixed) != 3 else fixed[2],\n )\n copy_files(li, class_dir, output, prog_bar, move)\n return len(files)\n\n\ndef split_files(files, split_train_idx, split_val_idx, use_test, max_test=None):\n \"\"\"\n Splits the files along the provided indices\n \"\"\"\n files_train = files[:split_train_idx]\n files_val = files[split_train_idx:split_val_idx] if use_test else files[split_train_idx:]\n\n li = [(files_train, \"train\"), (files_val, \"val\")]\n\n # optional test folder\n if use_test:\n files_test = files[split_val_idx:]\n if max_test is not None:\n files_test = files_test[:max_test]\n\n li.append((files_test, \"test\"))\n return li\n\n\ndef copy_files(files_type, class_dir, output, prog_bar, move):\n \"\"\"\n Copies the files from the input folder to the output folder\n \"\"\"\n copy_fn = _get_copy_fn(move)\n\n class_name = Path(class_dir).name\n for files, folder_type in files_type:\n full_path = Path(output) / folder_type / class_name\n\n full_path.mkdir(parents=True, exist_ok=True)\n for f in files:\n if prog_bar is not None:\n prog_bar.update()\n if isinstance(f, tuple):\n for x in f:\n copy_fn(x, full_path)\n else:\n copy_fn(f, full_path)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "jfilter__split-folders-25ce6a9838c6", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/jfilter__split-folders-25ce6a9838c6", "repo_key": "jfilter__split-folders", "repo": "jfilter/split-folders", "base_commit": "cef6ff3e976a7fb6f77d3a7bf948736c51d7833c", "source_files": ["README.md", "splitfolders/cli.py", "splitfolders/split.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Data splitting functions always shuffle files and do not support flat input directories.\n\n## Description\nCurrently, the `ratio()`, `fixed()`, and `kfold()` data splitting functions always randomize the order of files before splitting. This behavior is problematic for datasets where the order of files is significant, such as time series, as there is no option to preserve the original sorted order.\n\nFurthermore, the tool fails to correctly process input directories that contain files directly (a 'flat' structure) rather than being organized into class subdirectories. When provided with a flat directory, the tool does not split the files directly into train/val/test sets as expected, leading to errors or incorrect output.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `79543a5a9657` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### README.md\n```python\n# `split-folders` [![Build Status](https://img.shields.io/github/workflow/status/jfilter/split-folders/Test)](https://github.com/jfilter/split-folders/actions/workflows/test.yml) [![PyPI](https://img.shields.io/pypi/v/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Downloads](https://img.shields.io/pypi/dm/split-folders)](https://pypistats.org/packages/split-folders)\n\nSplit folders with files (e.g. images) into **train**, **validation** and **test** (dataset) folders.\n\nThe input folder should have the following format:\n\n```\ninput/\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n```\n\nIn order to give you this:\n\n```\noutput/\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n```\n\nThis should get you started to do some serious deep learning on your data. [Read here](https://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set) why it's a good idea to split your data intro three different sets.\n\n- Split files into a training set and a validation set (and optionally a test set).\n- Works on any file types.\n- The files get shuffled (can be disabled for time series data).\n- A [seed](https://docs.python.org/3/library/random.html#random.seed) makes splits reproducible.\n- Allows randomized [oversampling](https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis) for imbalanced datasets.\n- Optionally group files by prefix or by stem.\n- Optionally split files by file format(s).\n- Split parallel directories (e.g. `images/` + `annotations/`) in lockstep.\n- Custom grouping via callable.\n- (Should) work on all operating systems.\n\n## Install\n\nThis package is Python only and there are no external dependencies.\n\n```bash\npip install split-folders\n```\n\nOptionally, you may install [tqdm](https://github.com/tqdm/tqdm) to get a progress bar when moving files.\n\n```bash\npip install split-folders[full]\n```\n\n## Usage\n\nYou can use `split-folders` as Python module or as a Command Line Interface (CLI).\n\nIf your datasets is balanced (each class has the same number of samples), choose `ratio` otherwise `fixed`.\nNB: oversampling is turned off by default.\nOversampling is only applied to the _train_ folder since having duplicates in _val_ or _test_ would be considered cheating.\n\n### Module\n\n```python\nimport splitfolders\n\n# Split with a ratio.\n# To only split into training and validation set, set a tuple to `ratio`, i.e, `(.8, .2)`.\nsplitfolders.ratio(\"input_folder\", output=\"output\",\n seed=1337, ratio=(.8, .1, .1), group_prefix=None, group=None,\n formats=None, move=False, shuffle=True) # default values\n\n# Split val/test with a fixed number of items, e.g. `(100, 100)`, for each set.\n# To only split into training and validation set, use a single number to `fixed`, i.e., `10`.\n# Set 3 values, e.g. `(300, 100, 100)`, to limit the number of training values.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=(100, 100), oversample=False, group_prefix=None, group=None,\n formats=None, move=False, shuffle=True) # default values\n\n# Use `fixed=\"auto\"` with oversampling to auto-compute the val size from the smallest class.\n# Allocates ~20% of the smallest class to validation, rest to training.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=\"auto\", oversample=True)\n\n# Split into k folds for cross-validation.\n# Each fold directory contains train/ and val/ subdirectories.\n# Uses symlinks by default to avoid k\u00d7 disk usage.\nsplitfolders.kfold(\"input_folder\", output=\"output\",\n seed=1337, k=5, group_prefix=None, group=None,\n formats=None, move=\"symlink\", shuffle=True) # default values\n\n# Split without shuffling (e.g. for time series data).\nsplitfolders.ratio(\"input_folder\", output=\"output\",\n ratio=(.8, .1, .1), shuffle=False)\n```\n\n### Grouping files\n\nWhen your data has multiple files per sample (e.g. an image and its annotation), you need to keep them together during the split. There are several ways to do this.\n\n#### Group by prefix (`group_prefix`)\n\nThe legacy approach. Set `group_prefix` to the number of files per group (e.g. `2` for image + annotation pairs). Files are grouped by their filename stem (the part before the extension). All stems must have exactly `group_prefix` files.\n\n```\ninput/cats/\n img1.jpg img1.txt\n img2.jpg img2.txt\n```\n\n```python\nsplitfolders.ratio(\"input\", output=\"output\", group_prefix=2)\n```\n\n#### Group by stem (`group=\"stem\"`)\n\nA simpler alternative to `group_prefix`. Automatically groups files that share the same stem and discovers the group size. No need to specify how many files per group \u2014 it just requires every stem to have the same count.\n\n```python\nsplitfolders.ratio(\"input\", output=\"output\", group=\"stem\")\n```\n\nIf every stem has only one file (e.g. a folder of just `.jpg` files), `group=\"stem\"` behaves identically to no grouping.\n\n#### Group by sibling directories (`group=\"sibling\"`)\n\nFor datasets where file types live in **parallel directories** rather than alongside each other:\n\n```\ndata/\n images/\n im_1.jpg\n im_2.jpg\n annotations/\n im_1.xml\n im_2.xml\n```\n\nUse `group=\"sibling\"` to split all directories in lockstep, matching files across directories by stem:\n\n```python\nsplitfolders.ratio(\"data\", output=\"output\", group=\"sibling\")\n```\n\nThis produces:\n\n```\noutput/\n train/\n images/im_1.jpg\n annotations/im_1.xml\n val/\n images/im_2.jpg\n annotations/im_2.xml\n```\n\nRequirements:\n- The input must have at least 2 subdirectories.\n- Every stem must exist in every subdirectory.\n- Cannot be combined with `oversample=True`.\n\n#### Custom grouping (`group=callable`)\n\nFor advanced use cases, pass any callable that takes a list of `Path` objects and returns a list of tuples:\n\n```python\ndef my_grouping(files):\n # Custom logic to group files\n # Return: list of tuples of Path objects\n ...\n\nsplitfolders.ratio(\"input\", output=\"output\", group=my_grouping)\n```\n\nThis also covers **manifest-based splitting** (#41). For example, if you have a CSV that defines train/test assignments:\n\n```python\ndef group_from_manifest(files):\n manifest = load_my_csv(\"split_manifest.csv\")\n # return list of tuples grouped according to manifest\n ...\n\nsplitfolders.ratio(\"input\", output=\"output\", group=group_from_manifest)\n```\n\n> **Note:** `group_prefix` and `group` are mutually exclusive \u2014 setting both raises a `ValueError`.\n\n### File formats\n\nThere might be some instances when you have multiple file formats in these folders. Provide one or multiple extension(s) to `formats` for splitting only certain files (e.g. `formats=['.jpeg', '.png']`).\n\n### Move options\n\nSet\n- `move=True` or `move='move'` if you want to move the files instead of copying.\n- `move=False` or `move='copy'` if you want to copy the files. (default behavior)\n- `move='symlink'` if you want to symlink (i.e. create shortcuts `ln -s`) instead of copying.\n\n### CLI\n\n```\nUsage:\n splitfolders [--output] [--ratio] [--fixed] [--kfold] [--seed] [--oversample] [--group_prefix] [--group] [--formats] [--move] [--no-shuffle] folder_with_images\nOptions:\n --output path to the output folder. defaults to `output`. Get created if non-existent.\n --ratio the ratio to split. e.g. for train/val/test `.8 .1 .1 --` or for train/val `.8 .2 --`.\n --fixed set the absolute number of items per validation/test set. The remaining items constitute\n the training set. e.g. for train/val/test `100 100` or for train/val `100`.\n Set 3 values, e.g. `300 100 100`, to limit the number of training values.\n Use `auto` to auto-compute from the smallest class (requires --oversample).\n --kfold split into k folds for cross-validation. e.g. `5` for 5-fold CV. Uses symlinks by default.\n --seed set seed value for shuffling the items. defaults to 1337.\n --oversample enable oversampling of imbalanced datasets, works only with --fixed.\n --group_prefix split files into equally-sized groups based on their prefix\n --group grouping strategy: 'stem' or 'sibling' (mutually exclusive with --group_prefix)\n --formats split the files based on specified extension(s)\n --move move the files instead of copying\n --symlink symlink(create shortcut) the files instead of copying\n --no-shuffle do not shuffle files before splitting (useful for time series data)\nExample:\n splitfolders --ratio .8 .1 .1 -- folder_with_images\n splitfolders --kfold 5 folder_with_images\n splitfolders --group stem --ratio .8 .1 .1 -- folder_with_images\n splitfolders --group sibling --ratio .8 .1 .1 -- data_with_parallel_dirs\n```\n\nBecause of some [Python quirks](https://github.com/jfilter/split-folders/issues/19) you have to prepend ` --` after using `--ratio`.\n\nInstead of the command `splitfolders` you can also use `split_folders` or `split-folders`.\n\n## Development\n\nInstall and use [poetry](https://python-poetry.org/).\n\n## Contributing\n\nIf you have a **question**, found a **bug** or want to propose a new **feature**, have a look at the [issues page](https://github.com/jfilter/split-folders/issues).\n\n**Pull requests** are especially welcomed when they fix bugs or improve the code quality.\n\n## License\n\nMIT\n\n```\n\n### splitfolders/split.py\n```python\n\"\"\"Splits a folder with the given format:\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n\ninto this resulting format:\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n\"\"\"\n\nimport os\nimport random\nimport shutil\nfrom pathlib import Path\n\nfrom .grouping import resolve_grouping, setup_sibling_files\nfrom .utils import list_dirs, list_files\n\ntry:\n from tqdm import tqdm\n\n use_tqdm = True\nexcept ImportError:\n use_tqdm = False\n\n\ndef check_input_format(input):\n p_input = Path(input)\n if not p_input.exists():\n err_msg = f'The provided input folder \"{input}\" does not exists.'\n if not p_input.is_absolute():\n err_msg += f' Your relative path cannot be found from the current working directory \"{Path.cwd()}\".'\n raise ValueError(err_msg)\n\n if not p_input.is_dir():\n raise ValueError(f'The provided input folder \"{input}\" is not a directory')\n\n dirs = list_dirs(input)\n if len(dirs) == 0:\n raise ValueError(\n f'The input data is not in a right format. Within your folder \"{input}\"'\n \" there are no directories. Consult the documentation how to the folder\"\n \" structure should look like.\"\n )\n\n\ndef _get_copy_fn(move):\n \"\"\"Return a function(src, dst_dir) that copies/moves/symlinks a file into dst_dir.\"\"\"\n if move is True or move == \"move\":\n base_fn = shutil.move\n elif move is False or move == \"copy\":\n base_fn = shutil.copy2\n elif move == \"symlink\":\n base_fn = None # handled below\n else:\n raise ValueError(f\"Invalid value for move: {move!r}. Use True, False, or 'symlink'.\")\n\n def copy_fn(src, dst_dir):\n src = Path(src)\n dst_dir = Path(dst_dir)\n if move == \"symlink\":\n dst = dst_dir / src.name\n try:\n os.symlink(src.resolve(), dst)\n except FileExistsError:\n pass\n else:\n base_fn(str(src), str(dst_dir))\n\n return copy_fn\n\n\ndef valid_extensions(formats):\n \"\"\"\n Check if an extension starts with `.`\n \"\"\"\n if formats is None:\n return\n invalid_ext = [s for s in formats if not s.startswith(\".\")]\n if invalid_ext:\n raise ValueError(f\"Extensions must start with '.': {invalid_ext}\")\n\n\ndef ratio(\n input, output=\"output\", seed=1337, ratio=(0.8, 0.1, 0.1),\n group_prefix=None, group=None, move=False, formats=None, shuffle=True,\n):\n if not round(sum(ratio), 5) == 1: # round for floating imprecision\n raise ValueError(\"The sums of `ratio` is over 1.\")\n if len(ratio) not in (2, 3):\n raise ValueError(\"`ratio` should\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n if group == \"sibling\":\n split_sibling_dirs_ratio(\n input, output, ratio, seed, prog_bar if use_tqdm else None, move, formats, shuffle,\n )\n else:\n for class_dir in list_dirs(input):\n split_class_dir_ratio(\n class_dir, output, ratio, seed, prog_bar if use_tqdm else None,\n group_prefix, group, move, formats, shuffle,\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef fixed(\n input, output=\"output\", seed=1337, fixed=(100, 100), oversample=False,\n group_prefix=None, group=None, move=False, formats=None, shuffle=True,\n):\n check_input_format(input)\n valid_extensions(formats)\n\n if group == \"sibling\" and oversample:\n raise ValueError(\"Cannot use `oversample=True` with `group='sibling'` (no classes to balance).\")\n\n if fixed == \"auto\":\n if not oversample:\n raise ValueError(\n '`fixed=\"auto\"` requires `oversample=True`. For non-oversampled splits, use `ratio` instead.'\n )\n # Count files per class and derive fixed from the smallest class\n classes_dirs = list_dirs(input)\n counts = []\n for class_dir in classes_dirs:\n files = list_files(class_dir, formats)\n files = resolve_grouping(files, group_prefix, group)\n counts.append(len(files))\n min_count = min(counts)\n fixed = [max(1, min_count // 5)]\n else:\n if isinstance(fixed, int):\n fixed = [fixed]\n\n if len(fixed) not in (1, 2, 3):\n raise ValueError(\"`fixed` should be an integer or a list of 2 or 3 integers\")\n\n if len(fixed) == 3 and oversample:\n raise ValueError(\"Using fixed with 3 values together with oversampling is not implemented.\")\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n if group == \"sibling\":\n split_sibling_dirs_fixed(\n input, output, fixed, seed, prog_bar if use_tqdm else None, move, formats, shuffle,\n )\n if use_tqdm:\n prog_bar.close()\n return\n\n classes_dirs = list_dirs(input)\n num_items = []\n for class_dir in classes_dirs:\n num_items.append(\n split_class_dir_fixed(\n class_dir, output, fixed, seed, prog_bar if use_tqdm else None,\n group_prefix, group, move, formats, shuffle,\n )\n )\n\n if use_tqdm:\n prog_bar.close()\n\n if not oversample:\n return\n\n num_max_items = max(num_items)\n iteration = zip(num_items, classes_dirs)\n\n if use_tqdm:\n iteration = tqdm(iteration, desc=\"Oversampling\", unit=\" classes\")\n\n for num_items, class_dir in iteration:\n class_name = Path(class_dir).name\n full_path = Path(output) / \"train\" / class_name\n train_files = list_files(full_path, formats)\n train_files = resolve_grouping(train_files, group_prefix, group)\n\n for i in range(num_max_items - num_items):\n f_chosen = random.choice(train_files)\n\n if not isinstance(f_chosen, tuple):\n f_chosen = (f_chosen,)\n\n for f_orig in f_chosen:\n new_name = f_orig.stem + \"_\" + str(i) + f_orig.suffix\n f_dest = f_orig.with_name(new_name)\n if move == \"symlink\":\n try:\n os.symlink(f_orig.resolve(), f_dest)\n except FileExistsError:\n pass\n elif move is True or move == \"move\":\n shutil.move(str(f_orig), str(f_dest))\n else:\n shutil.copy2(str(f_orig), str(f_dest))\n\n\ndef kfold(\n input, output=\"output\", seed=1337, k=5, group_prefix=None, group=None,\n move=\"symlink\", formats=None, shuffle=True,\n):\n if k < 2:\n raise ValueError(\"`k` must be 2 or greater.\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n if group == \"sibling\":\n split_sibling_dirs_kfold(\n input, output, k, seed, prog_bar if use_tqdm else None, move, formats, shuffle,\n )\n else:\n for class_dir in list_dirs(input):\n split_class_dir_kfold(\n class_dir, output, k, seed, prog_bar if use_tqdm else None,\n group_prefix, group, move, formats, shuffle,\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef split_class_dir_kfold(class_dir, output, k, seed, prog_bar, group_prefix, group, move, formats, shuffle=True):\n \"\"\"\n Splits a class folder into k folds for cross-validation.\n Each fold directory gets train/ and val/ subdirectories.\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, group, formats, shuffle)\n\n # Partition files into k roughly equal chunks\n fold_size = len(files) // k\n remainder = len(files) % k\n partitions = []\n idx = 0\n for i in range(k):\n size = fold_size + (1 if i < remainder else 0)\n partitions.append(files[idx : idx + size])\n idx += size\n\n # For each fold, val = partition i, train = all other partitions\n for i in range(k):\n val_files = partitions[i]\n train_files = [f for j, part in enumerate(partitions) if j != i for f in part]\n fold_output = str(Path(output) / f\"fold_{i + 1}\")\n li = [(train_files, \"train\"), (val_files, \"val\")]\n copy_files(li, class_dir, fold_output, prog_bar, move)\n\n\ndef setup_files(class_dir, seed, group_prefix=None, group=None, formats=None, shuffle=True):\n \"\"\"\n Returns sorted (and optionally shuffled) list of filenames\n \"\"\"\n random.seed(seed) # make sure its reproducible\n\n files = list_files(class_dir, formats)\n files = resolve_grouping(files, group_prefix, group)\n\n files.sort()\n if shuffle:\n random.shuffle(files)\n return files\n\n\ndef split_class_dir_ratio(class_dir, output, ratio, seed, prog_bar, group_prefix, group, move, formats, shuffle=True):\n \"\"\"\n Splits a class folder\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, group, formats, shuffle)\n\n # the data was shuffled already\n split_train_idx = int(ratio[0] * len(files))\n split_val_idx = split_train_idx + int(ratio[1] * len(files))\n\n li = split_files(files, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_files(li, class_dir, output, prog_bar, move)\n\n\ndef split_class_dir_fixed(class_dir, output, fixed, seed, prog_bar, group_prefix, group, move, formats, shuffle=True):\n \"\"\"\n Splits a class folder and returns the total number of files\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, group, formats, shuffle)\n\n if not len(files) >= sum(fixed):\n raise ValueError(\n f'The number of samples in class \"{class_dir.stem}\" are too few.'\n f\" There are only {len(files)} samples available but your fixed parameter\"\n f\" {fixed} requires at least {sum(fixed)} files.\"\n \" You may want to split your classes by ratio.\"\n )\n\n # the data was shuffeld already\n if len(fixed) <= 2:\n split_train_idx = len(files) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n else:\n split_train_idx = fixed[0]\n split_val_idx = fixed[0] + fixed[1]\n\n li = split_files(\n files,\n split_train_idx,\n split_val_idx,\n len(fixed) >= 2,\n None if len(fixed) != 3 else fixed[2],\n )\n copy_files(li, class_dir, output, prog_bar, move)\n return len(files)\n\n\ndef split_files(files, split_train_idx, split_val_idx, use_test, max_test=None):\n \"\"\"\n Splits the files along the provided indices\n \"\"\"\n files_train = files[:split_train_idx]\n files_val = files[split_train_idx:split_val_idx] if use_test else files[split_train_idx:]\n\n li = [(files_train, \"train\"), (files_val, \"val\")]\n\n # optional test folder\n if use_test:\n files_test = files[split_val_idx:]\n if max_test is not None:\n files_test = files_test[:max_test]\n\n li.append((files_test, \"test\"))\n return li\n\n\ndef copy_files(files_type, class_dir, output, prog_bar, move):\n \"\"\"\n Copies the files from the input folder to the output folder\n \"\"\"\n copy_fn = _get_copy_fn(move)\n\n class_name = Path(class_dir).name\n for files, folder_type in files_type:\n full_path = Path(output) / folder_type / class_name\n\n full_path.mkdir(parents=True, exist_ok=True)\n for f in files:\n if prog_bar is not None:\n prog_bar.update()\n if isinstance(f, tuple):\n for x in f:\n copy_fn(x, full_path)\n else:\n copy_fn(f, full_path)\n\n\ndef copy_sibling_files(files_type, type_dir_names, output, prog_bar, move):\n \"\"\"\n Copies files in sibling mode: each group is a tuple of files across type dirs.\n Output structure: output/split_name/type_dir_name/filename\n \"\"\"\n copy_fn = _get_copy_fn(move)\n\n for files, folder_type in files_type:\n for group in files:\n if prog_bar is not None:\n prog_bar.update()\n for type_dir_name, f in zip(type_dir_names, group):\n full_path = Path(output) / folder_type / type_dir_name\n full_path.mkdir(parents=True, exist_ok=True)\n copy_fn(f, full_path)\n\n\ndef split_sibling_dirs_ratio(input_dir, output, ratio, seed, prog_bar, move, formats, shuffle=True):\n type_dir_names, groups = setup_sibling_files(input_dir, seed, formats, shuffle)\n\n split_train_idx = int(ratio[0] * len(groups))\n split_val_idx = split_train_idx + int(ratio[1] * len(groups))\n\n li = split_files(groups, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_sibling_files(li, type_dir_names, output, prog_bar, move)\n\n\ndef split_sibling_dirs_fixed(input_dir, output, fixed, seed, prog_bar, move, formats, shuffle=True):\n type_dir_names, groups = setup_sibling_files(input_dir, seed, formats, shuffle)\n\n if not len(groups) >= sum(fixed):\n raise ValueError(\n f\"Not enough file groups for the requested fixed split.\"\n f\" There are only {len(groups)} groups but fixed={fixed} requires at least {sum(fixed)}.\"\n )\n\n if len(fixed) <= 2:\n split_train_idx = len(groups) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n else:\n split_train_idx = fixed[0]\n split_val_idx = fixed[0] + fixed[1]\n\n li = split_files(\n groups,\n split_train_idx,\n split_val_idx,\n len(fixed) >= 2,\n None if len(fixed) != 3 else fixed[2],\n )\n copy_sibling_files(li, type_dir_names, output, prog_bar, move)\n\n\ndef split_sibling_dirs_kfold(input_dir, output, k, seed, prog_bar, move, formats, shuffle=True):\n type_dir_names, groups = setup_sibling_files(input_dir, seed, formats, shuffle)\n\n fold_size = len(groups) // k\n remainder = len(groups) % k\n partitions = []\n idx = 0\n for i in range(k):\n size = fold_size + (1 if i < remainder else 0)\n partitions.append(groups[idx : idx + size])\n idx += size\n\n for i in range(k):\n val_files = partitions[i]\n train_files = [f for j, part in enumerate(partitions) if j != i for f in part]\n fold_output = str(Path(output) / f\"fold_{i + 1}\")\n li = [(train_files, \"train\"), (val_files, \"val\")]\n copy_sibling_files(li, type_dir_names, fold_output, prog_bar, move)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "jfilter__split-folders-4112f01983ca", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/jfilter__split-folders-4112f01983ca", "repo_key": "jfilter__split-folders", "repo": "jfilter/split-folders", "base_commit": "79543a5a9657192656f13b6cda295960a7df6b77", "source_files": ["README.md", "splitfolders/split.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Data splitting always shuffles data, disrupting temporal order for time series\n\n## Description\nWhen using the data splitting functions such as `ratio()`, `fixed()`, or `kfold()`, the input data is invariably shuffled before being split. This behavior is problematic for datasets where the order of elements is significant, such as time series data, as it destroys the temporal sequence.\n\n**Expected behavior:** Users should be able to split data while preserving its original sorted order, particularly for time series analysis where maintaining chronological sequence is critical.\n**Actual behavior:** All data splitting operations currently randomize the data, making them unsuitable for applications requiring ordered splits.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `2551252bc5af` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### README.md\n```python\n# `split-folders` [![Build Status](https://img.shields.io/github/workflow/status/jfilter/split-folders/Test)](https://github.com/jfilter/split-folders/actions/workflows/test.yml) [![PyPI](https://img.shields.io/pypi/v/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Downloads](https://img.shields.io/pypi/dm/split-folders)](https://pypistats.org/packages/split-folders)\n\nSplit folders with files (e.g. images) into **train**, **validation** and **test** (dataset) folders.\n\nThe input folder should have the following format:\n\n```\ninput/\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n```\n\nIn order to give you this:\n\n```\noutput/\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n```\n\nThis should get you started to do some serious deep learning on your data. [Read here](https://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set) why it's a good idea to split your data intro three different sets.\n\n- Split files into a training set and a validation set (and optionally a test set).\n- Works on any file types.\n- The files get shuffled.\n- A [seed](https://docs.python.org/3/library/random.html#random.seed) makes splits reproducible.\n- Allows randomized [oversampling](https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis) for imbalanced datasets.\n- Optionally group files by prefix or by stem.\n- Optionally split files by file format(s).\n- Split parallel directories (e.g. `images/` + `annotations/`) in lockstep.\n- Custom grouping via callable.\n- (Should) work on all operating systems.\n\n## Install\n\nThis package is Python only and there are no external dependencies.\n\n```bash\npip install split-folders\n```\n\nOptionally, you may install [tqdm](https://github.com/tqdm/tqdm) to get a progress bar when moving files.\n\n```bash\npip install split-folders[full]\n```\n\n## Usage\n\nYou can use `split-folders` as Python module or as a Command Line Interface (CLI).\n\nIf your datasets is balanced (each class has the same number of samples), choose `ratio` otherwise `fixed`.\nNB: oversampling is turned off by default.\nOversampling is only applied to the _train_ folder since having duplicates in _val_ or _test_ would be considered cheating.\n\n### Module\n\n```python\nimport splitfolders\n\n# Split with a ratio.\n# To only split into training and validation set, set a tuple to `ratio`, i.e, `(.8, .2)`.\nsplitfolders.ratio(\"input_folder\", output=\"output\",\n seed=1337, ratio=(.8, .1, .1), group_prefix=None, group=None,\n formats=None, move=False) # default values\n\n# Split val/test with a fixed number of items, e.g. `(100, 100)`, for each set.\n# To only split into training and validation set, use a single number to `fixed`, i.e., `10`.\n# Set 3 values, e.g. `(300, 100, 100)`, to limit the number of training values.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=(100, 100), oversample=False, group_prefix=None, group=None,\n formats=None, move=False) # default values\n\n# Use `fixed=\"auto\"` with oversampling to auto-compute the val size from the smallest class.\n# Allocates ~20% of the smallest class to validation, rest to training.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=\"auto\", oversample=True)\n\n# Split into k folds for cross-validation.\n# Each fold directory contains train/ and val/ subdirectories.\n# Uses symlinks by default to avoid k\u00d7 disk usage.\nsplitfolders.kfold(\"input_folder\", output=\"output\",\n seed=1337, k=5, group_prefix=None, group=None,\n formats=None, move=\"symlink\") # default values\n```\n\n### Grouping files\n\nWhen your data has multiple files per sample (e.g. an image and its annotation), you need to keep them together during the split. There are several ways to do this.\n\n#### Group by prefix (`group_prefix`)\n\nThe legacy approach. Set `group_prefix` to the number of files per group (e.g. `2` for image + annotation pairs). Files are grouped by their filename stem (the part before the extension). All stems must have exactly `group_prefix` files.\n\n```\ninput/cats/\n img1.jpg img1.txt\n img2.jpg img2.txt\n```\n\n```python\nsplitfolders.ratio(\"input\", output=\"output\", group_prefix=2)\n```\n\n#### Group by stem (`group=\"stem\"`)\n\nA simpler alternative to `group_prefix`. Automatically groups files that share the same stem and discovers the group size. No need to specify how many files per group \u2014 it just requires every stem to have the same count.\n\n```python\nsplitfolders.ratio(\"input\", output=\"output\", group=\"stem\")\n```\n\nIf every stem has only one file (e.g. a folder of just `.jpg` files), `group=\"stem\"` behaves identically to no grouping.\n\n#### Group by sibling directories (`group=\"sibling\"`)\n\nFor datasets where file types live in **parallel directories** rather than alongside each other:\n\n```\ndata/\n images/\n im_1.jpg\n im_2.jpg\n annotations/\n im_1.xml\n im_2.xml\n```\n\nUse `group=\"sibling\"` to split all directories in lockstep, matching files across directories by stem:\n\n```python\nsplitfolders.ratio(\"data\", output=\"output\", group=\"sibling\")\n```\n\nThis produces:\n\n```\noutput/\n train/\n images/im_1.jpg\n annotations/im_1.xml\n val/\n images/im_2.jpg\n annotations/im_2.xml\n```\n\nRequirements:\n- The input must have at least 2 subdirectories.\n- Every stem must exist in every subdirectory.\n- Cannot be combined with `oversample=True`.\n\n#### Custom grouping (`group=callable`)\n\nFor advanced use cases, pass any callable that takes a list of `Path` objects and returns a list of tuples:\n\n```python\ndef my_grouping(files):\n # Custom logic to group files\n # Return: list of tuples of Path objects\n ...\n\nsplitfolders.ratio(\"input\", output=\"output\", group=my_grouping)\n```\n\nThis also covers **manifest-based splitting** (#41). For example, if you have a CSV that defines train/test assignments:\n\n```python\ndef group_from_manifest(files):\n manifest = load_my_csv(\"split_manifest.csv\")\n # return list of tuples grouped according to manifest\n ...\n\nsplitfolders.ratio(\"input\", output=\"output\", group=group_from_manifest)\n```\n\n> **Note:** `group_prefix` and `group` are mutually exclusive \u2014 setting both raises a `ValueError`.\n\n### File formats\n\nThere might be some instances when you have multiple file formats in these folders. Provide one or multiple extension(s) to `formats` for splitting only certain files (e.g. `formats=['.jpeg', '.png']`).\n\n### Move options\n\nSet\n- `move=True` or `move='move'` if you want to move the files instead of copying.\n- `move=False` or `move='copy'` if you want to copy the files. (default behavior)\n- `move='symlink'` if you want to symlink (i.e. create shortcuts `ln -s`) instead of copying.\n\n### CLI\n\n```\nUsage:\n splitfolders [--output] [--ratio] [--fixed] [--kfold] [--seed] [--oversample] [--group_prefix] [--group] [--formats] [--move] folder_with_images\nOptions:\n --output path to the output folder. defaults to `output`. Get created if non-existent.\n --ratio the ratio to split. e.g. for train/val/test `.8 .1 .1 --` or for train/val `.8 .2 --`.\n --fixed set the absolute number of items per validation/test set. The remaining items constitute\n the training set. e.g. for train/val/test `100 100` or for train/val `100`.\n Set 3 values, e.g. `300 100 100`, to limit the number of training values.\n Use `auto` to auto-compute from the smallest class (requires --oversample).\n --kfold split into k folds for cross-validation. e.g. `5` for 5-fold CV. Uses symlinks by default.\n --seed set seed value for shuffling the items. defaults to 1337.\n --oversample enable oversampling of imbalanced datasets, works only with --fixed.\n --group_prefix split files into equally-sized groups based on their prefix\n --group grouping strategy: 'stem' or 'sibling' (mutually exclusive with --group_prefix)\n --formats split the files based on specified extension(s)\n --move move the files instead of copying\n --symlink symlink(create shortcut) the files instead of copying\nExample:\n splitfolders --ratio .8 .1 .1 -- folder_with_images\n splitfolders --kfold 5 folder_with_images\n splitfolders --group stem --ratio .8 .1 .1 -- folder_with_images\n splitfolders --group sibling --ratio .8 .1 .1 -- data_with_parallel_dirs\n```\n\nBecause of some [Python quirks](https://github.com/jfilter/split-folders/issues/19) you have to prepend ` --` after using `--ratio`.\n\nInstead of the command `splitfolders` you can also use `split_folders` or `split-folders`.\n\n## Development\n\nInstall and use [poetry](https://python-poetry.org/).\n\n## Contributing\n\nIf you have a **question**, found a **bug** or want to propose a new **feature**, have a look at the [issues page](https://github.com/jfilter/split-folders/issues).\n\n**Pull requests** are especially welcomed when they fix bugs or improve the code quality.\n\n## License\n\nMIT\n\n```\n\n### splitfolders/cli.py\n```python\nimport argparse\n\nfrom .split import fixed, kfold, ratio\n\n\ndef run():\n parser = argparse.ArgumentParser(\n description=(\n \"Split folders with files (e.g. images) by copying them\"\n \" into training, validation and test (dataset) folders.\"\n )\n )\n parser.add_argument(\n \"--output\",\n default=\"output\",\n help=\"directory where to write the resulting split folders, defaults to `output`\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=\"1337\",\n help=\"a seed value to make your split reproducible\",\n )\n parser.add_argument(\n \"--ratio\",\n nargs=\"+\",\n type=float,\n help=\"the ratio to split. e.g. for train/val/test `.8 .1 .1` or for train/val `.8 .2`\",\n )\n parser.add_argument(\n \"--fixed\",\n nargs=\"+\",\n type=str,\n help=(\n \"set the absolute number of items per validation/test set.\"\n \" The remaining items get to the training.\"\n \" e.g. for train/val/test `100 100` or for train/val `100`.\"\n \" Set 3 values, e.g. `300 100 100`, to limit the number of training values.\"\n ' Use `auto` to auto-compute from the smallest class (requires --oversample).'\n ),\n )\n parser.add_argument(\n \"--kfold\",\n type=int,\n default=None,\n help=\"split into k folds for cross-validation. e.g. `5` for 5-fold CV. Each fold has train/ and val/ subdirs.\",\n )\n parser.add_argument(\n \"--oversample\",\n action=\"store_true\",\n help=\"enable oversampling of imbalanced datasets\",\n )\n parser.add_argument(\n \"--group_prefix\",\n type=int,\n default=None,\n help=\"split files into equally-sized groups based on their prefix\",\n )\n parser.add_argument(\n \"--group\",\n type=str,\n default=None,\n help=\"grouping strategy: 'stem' or 'sibling'\",\n )\n move_group = parser.add_mutually_exclusive_group()\n move_group.add_argument(\n \"--move\",\n action=\"store_true\",\n help=\"move the files instead of copying\",\n )\n move_group.add_argument(\n \"--symlink\",\n action=\"store_true\",\n help=\"symlink(create shortcut) the files instead of copying\",\n )\n parser.add_argument(\n \"input\",\n help=(\n \"directory with the input data. The directory needs to have the labels\"\n \" as sub-directories. In those sub-directories are then the actual files\"\n \" that gets split.\"\n ),\n )\n parser.add_argument(\n \"--formats\",\n nargs=\"+\",\n type=str,\n default=None,\n help=\"specify the file format(s) which should be considered for spliting the data e.g. `.png .jpeg .jpg`\",\n )\n\n args = parser.parse_args()\n\n if args.group_prefix is not None and args.group is not None:\n parser.error(\"--group_prefix and --group are mutually exclusive.\")\n\n if args.symlink:\n args.move = \"symlink\"\n\n if args.ratio:\n ratio(args.input, args.output, args.seed, args.ratio, args.group_prefix, args.group, args.move, args.formats)\n elif args.fixed:\n if args.fixed == [\"auto\"]:\n fixed_value = \"auto\"\n else:\n fixed_value = [int(x) for x in args.fixed]\n fixed(\n args.input,\n args.output,\n args.seed,\n fixed_value,\n args.oversample,\n args.group_prefix,\n args.group,\n args.move,\n args.formats,\n )\n elif args.kfold:\n kfold(\n args.input,\n args.output,\n args.seed,\n args.kfold,\n args.group_prefix,\n args.group,\n args.move if args.move else \"symlink\",\n args.formats,\n )\n else:\n print(\"Please specify either your `--ratio`, `--fixed`, or `--kfold` for the split. see -h for more help.\")\n\n```\n\n### splitfolders/grouping.py\n```python\nfrom collections import defaultdict\n\n\ndef group_by_prefix(files, len_pairs):\n \"\"\"Groups files by Path.stem, validates each group has len_pairs members.\"\"\"\n stem_groups = defaultdict(list)\n for f in files:\n stem_groups[f.stem].append(f)\n for stem, group in stem_groups.items():\n if len(group) != len_pairs:\n raise ValueError(\n f\"Expected {len_pairs} files with stem '{stem}', found {len(group)}\"\n )\n return [tuple(sorted(g)) for g in sorted(stem_groups.values(), key=lambda g: g[0])]\n\n\ndef resolve_grouping(files, group_prefix=None, group=None):\n \"\"\"Central dispatcher. Validates mutual exclusivity, routes to the right strategy.\"\"\"\n if group_prefix is not None and group is not None:\n raise ValueError(\"Cannot use both `group_prefix` and `group`.\")\n if group_prefix is not None:\n return group_by_prefix(files, group_prefix)\n if group is None:\n return files\n if group == \"stem\":\n return group_by_stem(files)\n if callable(group):\n return group(files)\n if group == \"sibling\":\n return files # sibling handled at orchestration level, not here\n raise ValueError(f\"Unknown group value: {group!r}.\")\n\n\ndef group_by_stem(files):\n \"\"\"Groups files by stem. Auto-discovers group size. Validates all groups same size.\n If group size is 1 (no actual grouping), returns flat list of Paths.\"\"\"\n stem_groups = defaultdict(list)\n for f in files:\n stem_groups[f.stem].append(f)\n\n sizes = {len(g) for g in stem_groups.values()}\n if len(sizes) != 1:\n size_details = {stem: len(g) for stem, g in stem_groups.items()}\n raise ValueError(\n f\"All stems must have the same number of files. Found sizes: {size_details}\"\n )\n\n group_size = sizes.pop()\n if group_size == 1:\n return sorted(files)\n\n return [tuple(sorted(g)) for g in sorted(stem_groups.values(), key=lambda g: g[0])]\n\n\ndef setup_sibling_files(input_dir, seed, formats=None):\n \"\"\"Lists type dirs, groups files by stem across all dirs.\n Validates every stem exists in every dir. Returns (type_dir_names, groups).\"\"\"\n from .utils import list_dirs, list_files\n\n type_dirs = sorted(list_dirs(input_dir))\n if len(type_dirs) < 2:\n raise ValueError(\n f\"group='sibling' requires at least 2 subdirectories, found {len(type_dirs)}.\"\n )\n\n type_dir_names = [d.name for d in type_dirs]\n\n # Collect stems per type dir\n stems_per_dir = {}\n files_per_dir = {}\n for td in type_dirs:\n dir_files = list_files(td, formats)\n files_per_dir[td.name] = {f.stem: f for f in dir_files}\n stems_per_dir[td.name] = set(files_per_dir[td.name].keys())\n\n # Validate: every stem must exist in every dir\n all_stems = set()\n for s in stems_per_dir.values():\n all_stems |= s\n\n for stem in sorted(all_stems):\n for dir_name, stems in stems_per_dir.items():\n if stem not in stems:\n raise ValueError(\n f\"Stem '{stem}' missing in directory '{dir_name}'. \"\n \"All stems must exist in every subdirectory for group='sibling'.\"\n )\n\n # Build groups: each group is a dict mapping type_dir_name -> Path\n import random\n\n random.seed(seed)\n sorted_stems = sorted(all_stems)\n random.shuffle(sorted_stems)\n\n groups = []\n for stem in sorted_stems:\n group = tuple(files_per_dir[dn][stem] for dn in type_dir_names)\n groups.append(group)\n\n return type_dir_names, groups\n\n```\n\n### splitfolders/split.py\n```python\n\"\"\"Splits a folder with the given format:\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n\ninto this resulting format:\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n\"\"\"\n\nimport os\nimport random\nimport shutil\nfrom pathlib import Path\n\nfrom .grouping import resolve_grouping, setup_sibling_files\nfrom .utils import list_dirs, list_files\n\ntry:\n from tqdm import tqdm\n\n use_tqdm = True\nexcept ImportError:\n use_tqdm = False\n\n\ndef check_input_format(input):\n p_input = Path(input)\n if not p_input.exists():\n err_msg = f'The provided input folder \"{input}\" does not exists.'\n if not p_input.is_absolute():\n err_msg += f' Your relative path cannot be found from the current working directory \"{Path.cwd()}\".'\n raise ValueError(err_msg)\n\n if not p_input.is_dir():\n raise ValueError(f'The provided input folder \"{input}\" is not a directory')\n\n dirs = list_dirs(input)\n if len(dirs) == 0:\n raise ValueError(\n f'The input data is not in a right format. Within your folder \"{input}\"'\n \" there are no directories. Consult the documentation how to the folder\"\n \" structure should look like.\"\n )\n\n\ndef _get_copy_fn(move):\n \"\"\"Return a function(src, dst_dir) that copies/moves/symlinks a file into dst_dir.\"\"\"\n if move is True or move == \"move\":\n base_fn = shutil.move\n elif move is False or move == \"copy\":\n base_fn = shutil.copy2\n elif move == \"symlink\":\n base_fn = None # handled below\n else:\n raise ValueError(f\"Invalid value for move: {move!r}. Use True, False, or 'symlink'.\")\n\n def copy_fn(src, dst_dir):\n src = Path(src)\n dst_dir = Path(dst_dir)\n if move == \"symlink\":\n dst = dst_dir / src.name\n try:\n os.symlink(src.resolve(), dst)\n except FileExistsError:\n pass\n else:\n base_fn(str(src), str(dst_dir))\n\n return copy_fn\n\n\ndef valid_extensions(formats):\n \"\"\"\n Check if an extension starts with `.`\n \"\"\"\n if formats is None:\n return\n invalid_ext = [s for s in formats if not s.startswith(\".\")]\n if invalid_ext:\n raise ValueError(f\"Extensions must start with '.': {invalid_ext}\")\n\n\ndef ratio(\n input, output=\"output\", seed=1337, ratio=(0.8, 0.1, 0.1),\n group_prefix=None, group=None, move=False, formats=None,\n):\n if not round(sum(ratio), 5) == 1: # round for floating imprecision\n raise ValueError(\"The sums of `ratio` is over 1.\")\n if len(ratio) not in (2, 3):\n raise ValueError(\"`ratio` should\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n if group == \"sibling\":\n split_sibling_dirs_ratio(input, output, ratio, seed, prog_bar if use_tqdm else None, move, formats)\n else:\n for class_dir in list_dirs(input):\n split_class_dir_ratio(\n class_dir, output, ratio, seed, prog_bar if use_tqdm else None, group_prefix, group, move, formats\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef fixed(\n input, output=\"output\", seed=1337, fixed=(100, 100), oversample=False,\n group_prefix=None, group=None, move=False, formats=None,\n):\n check_input_format(input)\n valid_extensions(formats)\n\n if group == \"sibling\" and oversample:\n raise ValueError(\"Cannot use `oversample=True` with `group='sibling'` (no classes to balance).\")\n\n if fixed == \"auto\":\n if not oversample:\n raise ValueError(\n '`fixed=\"auto\"` requires `oversample=True`. For non-oversampled splits, use `ratio` instead.'\n )\n # Count files per class and derive fixed from the smallest class\n classes_dirs = list_dirs(input)\n counts = []\n for class_dir in classes_dirs:\n files = list_files(class_dir, formats)\n files = resolve_grouping(files, group_prefix, group)\n counts.append(len(files))\n min_count = min(counts)\n fixed = [max(1, min_count // 5)]\n else:\n if isinstance(fixed, int):\n fixed = [fixed]\n\n if len(fixed) not in (1, 2, 3):\n raise ValueError(\"`fixed` should be an integer or a list of 2 or 3 integers\")\n\n if len(fixed) == 3 and oversample:\n raise ValueError(\"Using fixed with 3 values together with oversampling is not implemented.\")\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n if group == \"sibling\":\n split_sibling_dirs_fixed(input, output, fixed, seed, prog_bar if use_tqdm else None, move, formats)\n if use_tqdm:\n prog_bar.close()\n return\n\n classes_dirs = list_dirs(input)\n num_items = []\n for class_dir in classes_dirs:\n num_items.append(\n split_class_dir_fixed(\n class_dir, output, fixed, seed, prog_bar if use_tqdm else None, group_prefix, group, move, formats\n )\n )\n\n if use_tqdm:\n prog_bar.close()\n\n if not oversample:\n return\n\n num_max_items = max(num_items)\n iteration = zip(num_items, classes_dirs)\n\n if use_tqdm:\n iteration = tqdm(iteration, desc=\"Oversampling\", unit=\" classes\")\n\n for num_items, class_dir in iteration:\n class_name = Path(class_dir).name\n full_path = Path(output) / \"train\" / class_name\n train_files = list_files(full_path, formats)\n train_files = resolve_grouping(train_files, group_prefix, group)\n\n for i in range(num_max_items - num_items):\n f_chosen = random.choice(train_files)\n\n if not isinstance(f_chosen, tuple):\n f_chosen = (f_chosen,)\n\n for f_orig in f_chosen:\n new_name = f_orig.stem + \"_\" + str(i) + f_orig.suffix\n f_dest = f_orig.with_name(new_name)\n if move == \"symlink\":\n try:\n os.symlink(f_orig.resolve(), f_dest)\n except FileExistsError:\n pass\n elif move is True or move == \"move\":\n shutil.move(str(f_orig), str(f_dest))\n else:\n shutil.copy2(str(f_orig), str(f_dest))\n\n\ndef kfold(input, output=\"output\", seed=1337, k=5, group_prefix=None, group=None, move=\"symlink\", formats=None):\n if k < 2:\n raise ValueError(\"`k` must be 2 or greater.\")\n\n check_input_format(input)\n valid_extensions(formats)\n\n if use_tqdm:\n prog_bar = tqdm(desc=\"Copying files\", unit=\" files\")\n\n if group == \"sibling\":\n split_sibling_dirs_kfold(input, output, k, seed, prog_bar if use_tqdm else None, move, formats)\n else:\n for class_dir in list_dirs(input):\n split_class_dir_kfold(\n class_dir, output, k, seed, prog_bar if use_tqdm else None,\n group_prefix, group, move, formats,\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef split_class_dir_kfold(class_dir, output, k, seed, prog_bar, group_prefix, group, move, formats):\n \"\"\"\n Splits a class folder into k folds for cross-validation.\n Each fold directory gets train/ and val/ subdirectories.\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, group, formats)\n\n # Partition files into k roughly equal chunks\n fold_size = len(files) // k\n remainder = len(files) % k\n partitions = []\n idx = 0\n for i in range(k):\n size = fold_size + (1 if i < remainder else 0)\n partitions.append(files[idx : idx + size])\n idx += size\n\n # For each fold, val = partition i, train = all other partitions\n for i in range(k):\n val_files = partitions[i]\n train_files = [f for j, part in enumerate(partitions) if j != i for f in part]\n fold_output = str(Path(output) / f\"fold_{i + 1}\")\n li = [(train_files, \"train\"), (val_files, \"val\")]\n copy_files(li, class_dir, fold_output, prog_bar, move)\n\n\ndef setup_files(class_dir, seed, group_prefix=None, group=None, formats=None):\n \"\"\"\n Returns shuffled list of filenames\n \"\"\"\n random.seed(seed) # make sure its reproducible\n\n files = list_files(class_dir, formats)\n files = resolve_grouping(files, group_prefix, group)\n\n files.sort()\n random.shuffle(files)\n return files\n\n\ndef split_class_dir_ratio(class_dir, output, ratio, seed, prog_bar, group_prefix, group, move, formats):\n \"\"\"\n Splits a class folder\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, group, formats)\n\n # the data was shuffled already\n split_train_idx = int(ratio[0] * len(files))\n split_val_idx = split_train_idx + int(ratio[1] * len(files))\n\n li = split_files(files, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_files(li, class_dir, output, prog_bar, move)\n\n\ndef split_class_dir_fixed(class_dir, output, fixed, seed, prog_bar, group_prefix, group, move, formats):\n \"\"\"\n Splits a class folder and returns the total number of files\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix, group, formats)\n\n if not len(files) >= sum(fixed):\n raise ValueError(\n f'The number of samples in class \"{class_dir.stem}\" are too few.'\n f\" There are only {len(files)} samples available but your fixed parameter\"\n f\" {fixed} requires at least {sum(fixed)} files.\"\n \" You may want to split your classes by ratio.\"\n )\n\n # the data was shuffeld already\n if len(fixed) <= 2:\n split_train_idx = len(files) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n else:\n split_train_idx = fixed[0]\n split_val_idx = fixed[0] + fixed[1]\n\n li = split_files(\n files,\n split_train_idx,\n split_val_idx,\n len(fixed) >= 2,\n None if len(fixed) != 3 else fixed[2],\n )\n copy_files(li, class_dir, output, prog_bar, move)\n return len(files)\n\n\ndef split_files(files, split_train_idx, split_val_idx, use_test, max_test=None):\n \"\"\"\n Splits the files along the provided indices\n \"\"\"\n files_train = files[:split_train_idx]\n files_val = files[split_train_idx:split_val_idx] if use_test else files[split_train_idx:]\n\n li = [(files_train, \"train\"), (files_val, \"val\")]\n\n # optional test folder\n if use_test:\n files_test = files[split_val_idx:]\n if max_test is not None:\n files_test = files_test[:max_test]\n\n li.append((files_test, \"test\"))\n return li\n\n\ndef copy_files(files_type, class_dir, output, prog_bar, move):\n \"\"\"\n Copies the files from the input folder to the output folder\n \"\"\"\n copy_fn = _get_copy_fn(move)\n\n class_name = Path(class_dir).name\n for files, folder_type in files_type:\n full_path = Path(output) / folder_type / class_name\n\n full_path.mkdir(parents=True, exist_ok=True)\n for f in files:\n if prog_bar is not None:\n prog_bar.update()\n if isinstance(f, tuple):\n for x in f:\n copy_fn(x, full_path)\n else:\n copy_fn(f, full_path)\n\n\ndef copy_sibling_files(files_type, type_dir_names, output, prog_bar, move):\n \"\"\"\n Copies files in sibling mode: each group is a tuple of files across type dirs.\n Output structure: output/split_name/type_dir_name/filename\n \"\"\"\n copy_fn = _get_copy_fn(move)\n\n for files, folder_type in files_type:\n for group in files:\n if prog_bar is not None:\n prog_bar.update()\n for type_dir_name, f in zip(type_dir_names, group):\n full_path = Path(output) / folder_type / type_dir_name\n full_path.mkdir(parents=True, exist_ok=True)\n copy_fn(f, full_path)\n\n\ndef split_sibling_dirs_ratio(input_dir, output, ratio, seed, prog_bar, move, formats):\n type_dir_names, groups = setup_sibling_files(input_dir, seed, formats)\n\n split_train_idx = int(ratio[0] * len(groups))\n split_val_idx = split_train_idx + int(ratio[1] * len(groups))\n\n li = split_files(groups, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_sibling_files(li, type_dir_names, output, prog_bar, move)\n\n\ndef split_sibling_dirs_fixed(input_dir, output, fixed, seed, prog_bar, move, formats):\n type_dir_names, groups = setup_sibling_files(input_dir, seed, formats)\n\n if not len(groups) >= sum(fixed):\n raise ValueError(\n f\"Not enough file groups for the requested fixed split.\"\n f\" There are only {len(groups)} groups but fixed={fixed} requires at least {sum(fixed)}.\"\n )\n\n if len(fixed) <= 2:\n split_train_idx = len(groups) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n else:\n split_train_idx = fixed[0]\n split_val_idx = fixed[0] + fixed[1]\n\n li = split_files(\n groups,\n split_train_idx,\n split_val_idx,\n len(fixed) >= 2,\n None if len(fixed) != 3 else fixed[2],\n )\n copy_sibling_files(li, type_dir_names, output, prog_bar, move)\n\n\ndef split_sibling_dirs_kfold(input_dir, output, k, seed, prog_bar, move, formats):\n type_dir_names, groups = setup_sibling_files(input_dir, seed, formats)\n\n fold_size = len(groups) // k\n remainder = len(groups) % k\n partitions = []\n idx = 0\n for i in range(k):\n size = fold_size + (1 if i < remainder else 0)\n partitions.append(groups[idx : idx + size])\n idx += size\n\n for i in range(k):\n val_files = partitions[i]\n train_files = [f for j, part in enumerate(partitions) if j != i for f in part]\n fold_output = str(Path(output) / f\"fold_{i + 1}\")\n li = [(train_files, \"train\"), (val_files, \"val\")]\n copy_sibling_files(li, type_dir_names, fold_output, prog_bar, move)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "jfilter__split-folders-79543a5a9657", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/jfilter__split-folders-79543a5a9657", "repo_key": "jfilter__split-folders", "repo": "jfilter/split-folders", "base_commit": "2551252bc5af7a57fd6c78ef2b8d49d5ffc3e40c", "source_files": ["README.md", "splitfolders/cli.py", "splitfolders/grouping.py", "splitfolders/split.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Training process does not limit the number of training samples\n\n## Description\nWhen attempting to configure a fixed limit on the number of training samples, the system proceeds to use all available samples, ignoring the specified limit. The expected behavior is for the training process to respect the configured limit and only utilize the specified number of training samples.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `a16b7f38f94b` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### README.md\n```python\n# `split-folders` [![Build Status](https://img.shields.io/github/workflow/status/jfilter/split-folders/Test)](https://github.com/jfilter/split-folders/actions/workflows/test.yml) [![PyPI](https://img.shields.io/pypi/v/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/split-folders.svg)](https://pypi.org/project/split-folders/) [![PyPI - Downloads](https://img.shields.io/pypi/dm/split-folders)](https://pypistats.org/packages/split-folders)\n\nSplit folders with files (e.g. images) into **train**, **validation** and **test** (dataset) folders.\n\nThe input folder should have the following format:\n\n```\ninput/\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n```\n\nIn order to give you this:\n\n```\noutput/\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n```\n\nThis should get you started to do some serious deep learning on your data. [Read here](https://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set) why it's a good idea to split your data intro three different sets.\n\n- Split files into a training set and a validation set (and optionally a test set).\n- Works on any file types.\n- The files get shuffled.\n- A [seed](https://docs.python.org/3/library/random.html#random.seed) makes splits reproducible.\n- Allows randomized [oversampling](https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis) for imbalanced datasets.\n- Optionally group files by prefix.\n- (Should) work on all operating systems.\n\n## Install\n\nThis package is Python only and there are no external dependencies.\n\n```bash\npip install split-folders\n```\n\nOptionally, you may install [tqdm](https://github.com/tqdm/tqdm) to get get a progress bar when moving files.\n\n```bash\npip install split-folders[full]\n```\n\n## Usage\n\nYou can use `split-folders` as Python module or as a Command Line Interface (CLI).\n\nIf your datasets is balanced (each class has the same number of samples), choose `ratio` otherwise `fixed`.\nNB: oversampling is turned off by default.\nOversampling is only applied to the _train_ folder since having duplicates in _val_ or _test_ would be considered cheating.\n\n### Module\n\n```python\nimport splitfolders # or import split_folders\n\n# Split with a ratio.\n# To only split into training and validation set, set a tuple to `ratio`, i.e, `(.8, .2)`.\nsplitfolders.ratio(\"input_folder\", output=\"output\",\n seed=1337, ratio=(.8, .1, .1), group_prefix=None, move=False) # default values\n\n# Split val/test with a fixed number of items e.g. 100 for each set.\n# To only split into training and validation set, use a single number to `fixed`, i.e., `10`.\nsplitfolders.fixed(\"input_folder\", output=\"output\",\n seed=1337, fixed=(100, 100), oversample=False, group_prefix=None, move=False) # default values\n```\n\nOccasionally, you may have things that comprise more than a single file (e.g. picture (.png) + annotation (.txt)).\n`splitfolders` lets you split files into equally-sized groups based on their prefix.\nSet `group_prefix` to the length of the group (e.g. `2`).\nBut now _all_ files should be part of groups.\n\nSet `move=True` if you want to move the files instead of copying.\n\n### CLI\n\n```\nUsage:\n splitfolders [--output] [--ratio] [--fixed] [--seed] [--oversample] [--group_prefix] [--move] folder_with_images\nOptions:\n --output path to the output folder. defaults to `output`. Get created if non-existent.\n --ratio the ratio to split. e.g. for train/val/test `.8 .1 .1 --` or for train/val `.8 .2 --`.\n --fixed set the absolute number of items per validation/test set. The remaining items constitute\n the training set. e.g. for train/val/test `100 100` or for train/val `100`.\n --seed set seed value for shuffling the items. defaults to 1337.\n --oversample enable oversampling of imbalanced datasets, works only with --fixed.\n --group_prefix split files into equally-sized groups based on their prefix\n --move move the files instead of copying\nExample:\n splitfolders --ratio .8 .1 .1 -- folder_with_images\n```\n\nBecause of some [Python quirks](https://github.com/jfilter/split-folders/issues/19) you have to prepend ` --` afer using `--ratio`.\n\nInstead of the command `splitfolders` you can also use `split_folders` or `split-folders`.\n\n## Development\n\nInstall and use [poetry](https://python-poetry.org/).\n\n## Contributing\n\nIf you have a **question**, found a **bug** or want to propose a new **feature**, have a look at the [issues page](https://github.com/jfilter/split-folders/issues).\n\n**Pull requests** are especially welcomed when they fix bugs or improve the code quality.\n\n## License\n\nMIT\n\n```\n\n### splitfolders/cli.py\n```python\nimport argparse\n\nfrom .split import fixed, ratio\n\n\ndef run():\n parser = argparse.ArgumentParser(\n description=\"Split folders with files (e.g. images) into training, validation and test(dataset) folders.\"\n )\n parser.add_argument(\n \"--output\",\n default=\"output\",\n help=\"directory where to write the resulting split folders, defaults to `output`\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=\"1337\",\n help=\"a seed value to make your split reproducible\",\n )\n parser.add_argument(\n \"--ratio\",\n nargs=\"+\",\n type=float,\n help=\"the ratio to split. e.g. for train/val/test `.8 .1 .1` or for train/val `.8 .2`\",\n )\n parser.add_argument(\n \"--fixed\",\n nargs=\"+\",\n type=int,\n help=\"set the absolute number of items per validation/test set. The remaining items get to the training. e.g. for train/val/test `100 100` or for train/val `100`\",\n )\n parser.add_argument(\n \"--oversample\",\n action=\"store_true\",\n help=\"enable oversampling of imbalanced datasets\",\n )\n parser.add_argument(\n \"--group_prefix\",\n type=int,\n default=None,\n help=\"split files into equally-sized groups based on their prefix\",\n )\n parser.add_argument(\n \"--move\",\n action=\"store_true\",\n help=\"move the files instead of copying\",\n )\n parser.add_argument(\n \"input\",\n help=\"directory with the input data. The directory needs to have the labels as sub-directories. In those sub-directories are then the actual files that gets split.\",\n )\n\n args = parser.parse_args()\n\n if args.ratio:\n ratio(\n args.input, args.output, args.seed, args.ratio, args.group_prefix, args.move\n )\n else:\n if args.fixed:\n fixed(\n args.input,\n args.output,\n args.seed,\n args.fixed,\n args.oversample,\n args.group_prefix,\n args.move,\n )\n else:\n print(\n \"Please specify either your `--ratio` or your `--fixed` number of items for the split. see -h for more help.\"\n )\n\n```\n\n### splitfolders/split.py\n```python\n\"\"\"Splits a folder with the given format:\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n\ninto this resulting format:\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n\"\"\"\n\nfrom pathlib import Path\nimport random\nimport shutil\nfrom os import path\n\nfrom .utils import list_dirs, list_files\n\ntry:\n from tqdm import tqdm\n\n use_tqdm = True\nexcept ImportError:\n use_tqdm = False\n\n\ndef ratio(\n input,\n output=\"output\",\n seed=1337,\n ratio=(0.8, 0.1, 0.1),\n group_prefix=None,\n move=False,\n):\n if not round(sum(ratio), 5) == 1: # round for floating imprecision\n raise ValueError(\"The sums of `ratio` is over 1.\")\n if not len(ratio) in (2, 3):\n raise ValueError(\"`ratio` should\")\n\n if use_tqdm:\n prog_bar = tqdm(desc=f\"Copying files\", unit=\" files\")\n\n for class_dir in list_dirs(input):\n split_class_dir_ratio(\n class_dir,\n output,\n ratio,\n seed,\n prog_bar if use_tqdm else None,\n group_prefix,\n move,\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef fixed(\n input,\n output=\"output\",\n seed=1337,\n fixed=(100, 100),\n oversample=False,\n group_prefix=None,\n move=False,\n):\n if isinstance(fixed, int):\n fixed = [fixed]\n\n assert len(fixed) in (1, 2)\n\n if use_tqdm:\n prog_bar = tqdm(desc=f\"Copying files\", unit=\" files\")\n\n classes_dirs = list_dirs(input)\n num_items = []\n for class_dir in classes_dirs:\n num_items.append(\n split_class_dir_fixed(\n class_dir,\n output,\n fixed,\n seed,\n prog_bar if use_tqdm else None,\n group_prefix,\n move,\n )\n )\n\n if use_tqdm:\n prog_bar.close()\n\n if not oversample:\n return\n\n num_max_items = max(num_items)\n iteration = zip(num_items, classes_dirs)\n\n if use_tqdm:\n iteration = tqdm(iteration, desc=\"Oversampling\", unit=\" classes\")\n\n copy_fun = shutil.move if move else shutil.copy2\n\n for num_items, class_dir in iteration:\n class_name = path.split(class_dir)[1]\n full_path = path.join(output, \"train\", class_name)\n train_files = list_files(full_path)\n\n if group_prefix is not None:\n train_files = group_by_prefix(train_files, group_prefix)\n\n for i in range(num_max_items - num_items):\n f_chosen = random.choice(train_files)\n\n if not type(f_chosen) is tuple:\n f_chosen = (f_chosen,)\n\n for f_orig in f_chosen:\n new_name = f_orig.stem + \"_\" + str(i) + f_orig.suffix\n f_dest = f_orig.with_name(new_name)\n copy_fun(f_orig, f_dest)\n\n\ndef group_by_prefix(files, len_pairs):\n \"\"\"\n Split files into groups of len `len_pairs` based on their prefix.\n \"\"\"\n results = []\n results_set = set() # for fast lookup, only file names\n for f in files:\n if f.name in results_set:\n continue\n f_sub = f.name\n for _ in range(len(f_sub)):\n matches = [\n x\n for x in files\n if x.name not in results_set\n and x.name.startswith(f_sub)\n and f.name != x.name\n ]\n if len(matches) == len_pairs - 1:\n results.append((f, *matches))\n results_set.update((f.name, *[x.name for x in matches]))\n break\n elif len(matches) < len_pairs - 1:\n f_sub = f_sub[:-1]\n else:\n raise ValueError(\n f\"The length of pairs has to be equal. Coudn't find {len_pairs - 1} matches for {f}. Found {len(matches)} matches.\"\n )\n else:\n raise ValueError(f\"No adequate matches found for {f}.\")\n\n if len(results_set) != len(files):\n raise ValueError(\n f\"Could not find enough matches ({len(results_set)}) for all files ({len(files)})\"\n )\n return results\n\n\ndef setup_files(class_dir, seed, group_prefix=None):\n \"\"\"\n Returns shuffeld list of filenames\n \"\"\"\n random.seed(seed) # make sure its reproducible\n\n files = list_files(class_dir)\n\n if group_prefix is not None:\n files = group_by_prefix(files, group_prefix)\n\n files.sort()\n random.shuffle(files)\n return files\n\n\ndef split_class_dir_ratio(class_dir, output, ratio, seed, prog_bar, group_prefix, move):\n \"\"\"\n Splits a class folder\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix)\n\n # the data was shuffled already\n split_train_idx = int(ratio[0] * len(files))\n split_val_idx = split_train_idx + int(ratio[1] * len(files))\n\n li = split_files(files, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_files(li, class_dir, output, prog_bar, move)\n\n\ndef split_class_dir_fixed(class_dir, output, fixed, seed, prog_bar, group_prefix, move):\n \"\"\"\n Splits a class folder and returns the total number of files\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix)\n\n if not len(files) > sum(fixed):\n raise ValueError(\n f'The number of samples in class \"{class_dir.stem}\" are too few. There are only {len(files)} samples available but your fixed parameter {fixed} requires at least {sum(fixed)} files. You may want to split your classes by ratio.'\n )\n\n # the data was shuffeld already\n split_train_idx = len(files) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n\n li = split_files(files, split_train_idx, split_val_idx, len(fixed) == 2)\n copy_files(li, class_dir, output, prog_bar, move)\n return len(files)\n\n\ndef split_files(files, split_train_idx, split_val_idx, use_test):\n \"\"\"\n Splits the files along the provided indices\n \"\"\"\n files_train = files[:split_train_idx]\n files_val = (\n files[split_train_idx:split_val_idx] if use_test else files[split_train_idx:]\n )\n\n li = [(files_train, \"train\"), (files_val, \"val\")]\n\n # optional test folder\n if use_test:\n files_test = files[split_val_idx:]\n li.append((files_test, \"test\"))\n return li\n\n\ndef copy_files(files_type, class_dir, output, prog_bar, move):\n \"\"\"\n Copies the files from the input folder to the output folder\n \"\"\"\n\n copy_fun = shutil.move if move else shutil.copy2\n\n # get the last part within the file\n class_name = path.split(class_dir)[1]\n for (files, folder_type) in files_type:\n full_path = path.join(output, folder_type, class_name)\n\n Path(full_path).mkdir(parents=True, exist_ok=True)\n for f in files:\n if not prog_bar is None:\n prog_bar.update()\n if type(f) == tuple:\n for x in f:\n copy_fun(x, full_path)\n else:\n copy_fun(f, full_path)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "jfilter__split-folders-85fde3471cb0", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/jfilter__split-folders-85fde3471cb0", "repo_key": "jfilter__split-folders", "repo": "jfilter/split-folders", "base_commit": "a16b7f38f94b7ac49f004215451a30428999b726", "source_files": ["README.md", "splitfolders/cli.py", "splitfolders/split.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Unclear error message when insufficient files are provided for the `fixed` operation.\n\n## Description\nWhen attempting to perform the `fixed` operation, if an insufficient number of input files are provided, the system returns an unhelpful or vague error message. This makes it difficult for users to understand why the operation failed or what action is needed to resolve the issue. The expected behavior is for the error message to clearly and explicitly state that more files are required for the `fixed` operation to proceed successfully.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `f3104f872df7` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### split_folders/split.py\n```python\n\"\"\"Splits a folder with the given format:\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n\ninto this resulting format:\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n\"\"\"\n\nimport pathlib\nimport random\nimport shutil\nfrom os import path, listdir\n\n\ndef list_dirs(directory):\n \"\"\"Returns all directories in a given directory\n \"\"\"\n return [f for f in pathlib.Path(directory).iterdir() if f.is_dir()]\n\n\ndef list_files(directory):\n \"\"\"Returns all files in a given directory\n \"\"\"\n return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]\n\n\ndef ratio(input, output=\"output\", seed=1337, ratio=(.8, .1, .1)):\n assert sum(ratio) == 1\n assert len(ratio) in (2, 3)\n\n for class_dir in list_dirs(input):\n split_class_dir_ratio(class_dir, output, ratio, seed)\n\n\ndef fixed(input, output=\"output\", seed=1337, fixed=(100, 100), oversample=False):\n # make sure its reproducible\n if isinstance(fixed, int):\n fixed = (fixed)\n\n assert len(fixed) in (1, 2)\n\n dirs = list_dirs(input)\n lens = []\n for class_dir in dirs:\n lens.append(split_class_dir_fixed(class_dir, output, fixed, seed))\n\n if not oversample:\n return\n\n max_len = max(lens)\n\n for length, class_dir in zip(lens, dirs):\n class_name = path.split(class_dir)[1]\n full_path = path.join(output, 'train', class_name)\n train_files = list_files(full_path)\n for i in range(max_len - length):\n f_orig = random.choice(train_files)\n new_name = f_orig.stem + '_' + str(i) + f_orig.suffix\n f_dest = f_orig.with_name(new_name)\n shutil.copy2(f_orig, f_dest)\n\n\ndef setup_files(class_dir, seed):\n \"\"\"Returns shuffled files\n \"\"\"\n # make sure its reproducible\n random.seed(seed)\n\n files = list_files(class_dir)\n\n files.sort()\n random.shuffle(files)\n return files\n\n\ndef split_class_dir_fixed(class_dir, output, fixed, seed):\n \"\"\"Splits one very class folder\n \"\"\"\n files = setup_files(class_dir, seed)\n\n assert len(files) > sum(fixed)\n\n split_train = len(files) - sum(fixed)\n split_val = split_train + fixed[0]\n\n li = split_files(files, split_train, split_val, len(fixed) == 2)\n copy_files(li, class_dir, output)\n return len(files)\n\n\ndef split_class_dir_ratio(class_dir, output, ratio, seed):\n \"\"\"Splits one very class folder\n \"\"\"\n files = setup_files(class_dir, seed)\n\n split_train = int(ratio[0] * len(files))\n split_val = split_train + int(ratio[1] * len(files))\n\n li = split_files(files, split_train, split_val, len(ratio) == 3)\n copy_files(li, class_dir, output)\n\n\ndef split_files(files, split_train, split_val, use_test):\n \"\"\"Splits the files along the provided indices\n \"\"\"\n files_train = files[:split_train]\n files_val = files[split_train:split_val] if use_test else files[split_train:]\n\n li = [(files_train, 'train'), (files_val, 'val')]\n\n # optional test folder\n if use_test:\n files_test = files[split_val:]\n li.append((files_test, 'test'))\n return li\n\n\ndef copy_files(files_type, class_dir, output):\n \"\"\"Copies the files from the input folder to the output folder\n \"\"\"\n # get the last part within the file\n class_name = path.split(class_dir)[1]\n for (files, folder_type) in files_type:\n full_path = path.join(output, folder_type, class_name)\n\n pathlib.Path(full_path).mkdir(\n parents=True, exist_ok=True)\n for f in files:\n shutil.copy2(f, full_path)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "jfilter__split-folders-9c147d162a1e", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/jfilter__split-folders-9c147d162a1e", "repo_key": "jfilter__split-folders", "repo": "jfilter/split-folders", "base_commit": "f3104f872df7394bff79fb217e3132a9a7805ab7", "source_files": ["split_folders/split.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Application does not validate input folder format\n\n## Description\nWhen an input folder is provided that does not adhere to the required format, the application currently proceeds without any immediate warning or error message. This can lead to subsequent failures or incorrect processing without clearly indicating that the initial input was malformed. The expected behavior is for the application to validate the input folder's format upon submission and display a clear warning to the user if it is incorrect.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `85fde3471cb0` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### splitfolders/split.py\n```python\n\"\"\"Splits a folder with the given format:\n class1/\n img1.jpg\n img2.jpg\n ...\n class2/\n imgWhatever.jpg\n ...\n ...\n\ninto this resulting format:\n train/\n class1/\n img1.jpg\n ...\n class2/\n imga.jpg\n ...\n val/\n class1/\n img2.jpg\n ...\n class2/\n imgb.jpg\n ...\n test/\n class1/\n img3.jpg\n ...\n class2/\n imgc.jpg\n ...\n\"\"\"\n\nfrom pathlib import Path\nimport random\nimport shutil\nfrom os import path\n\nfrom .utils import list_dirs, list_files\n\ntry:\n from tqdm import tqdm\n\n use_tqdm = True\nexcept ImportError:\n use_tqdm = False\n\n\ndef ratio(\n input,\n output=\"output\",\n seed=1337,\n ratio=(0.8, 0.1, 0.1),\n group_prefix=None,\n move=False,\n):\n if not round(sum(ratio), 5) == 1: # round for floating imprecision\n raise ValueError(\"The sums of `ratio` is over 1.\")\n if not len(ratio) in (2, 3):\n raise ValueError(\"`ratio` should\")\n\n if use_tqdm:\n prog_bar = tqdm(desc=f\"Copying files\", unit=\" files\")\n\n for class_dir in list_dirs(input):\n split_class_dir_ratio(\n class_dir,\n output,\n ratio,\n seed,\n prog_bar if use_tqdm else None,\n group_prefix,\n move,\n )\n\n if use_tqdm:\n prog_bar.close()\n\n\ndef fixed(\n input,\n output=\"output\",\n seed=1337,\n fixed=(100, 100),\n oversample=False,\n group_prefix=None,\n move=False,\n):\n if isinstance(fixed, int):\n fixed = [fixed]\n\n if not len(fixed) in (1, 2, 3):\n raise ValueError(\"`fixed` should be an integer or a list of 2 or 3 integers\")\n\n if len(fixed) == 3 and oversample:\n raise ValueError(\n \"Using fixed with 3 values together with oversampling is not implemented.\"\n )\n\n if use_tqdm:\n prog_bar = tqdm(desc=f\"Copying files\", unit=\" files\")\n\n classes_dirs = list_dirs(input)\n num_items = []\n for class_dir in classes_dirs:\n num_items.append(\n split_class_dir_fixed(\n class_dir,\n output,\n fixed,\n seed,\n prog_bar if use_tqdm else None,\n group_prefix,\n move,\n )\n )\n\n if use_tqdm:\n prog_bar.close()\n\n if not oversample:\n return\n\n num_max_items = max(num_items)\n iteration = zip(num_items, classes_dirs)\n\n if use_tqdm:\n iteration = tqdm(iteration, desc=\"Oversampling\", unit=\" classes\")\n\n copy_fun = shutil.move if move else shutil.copy2\n\n for num_items, class_dir in iteration:\n class_name = path.split(class_dir)[1]\n full_path = path.join(output, \"train\", class_name)\n train_files = list_files(full_path)\n\n if group_prefix is not None:\n train_files = group_by_prefix(train_files, group_prefix)\n\n for i in range(num_max_items - num_items):\n f_chosen = random.choice(train_files)\n\n if not type(f_chosen) is tuple:\n f_chosen = (f_chosen,)\n\n for f_orig in f_chosen:\n new_name = f_orig.stem + \"_\" + str(i) + f_orig.suffix\n f_dest = f_orig.with_name(new_name)\n copy_fun(f_orig, f_dest)\n\n\ndef group_by_prefix(files, len_pairs):\n \"\"\"\n Split files into groups of len `len_pairs` based on their prefix.\n \"\"\"\n results = []\n results_set = set() # for fast lookup, only file names\n for f in files:\n if f.name in results_set:\n continue\n f_sub = f.name\n for _ in range(len(f_sub)):\n matches = [\n x\n for x in files\n if x.name not in results_set\n and x.name.startswith(f_sub)\n and f.name != x.name\n ]\n if len(matches) == len_pairs - 1:\n results.append((f, *matches))\n results_set.update((f.name, *[x.name for x in matches]))\n break\n elif len(matches) < len_pairs - 1:\n f_sub = f_sub[:-1]\n else:\n raise ValueError(\n f\"The length of pairs has to be equal. Coudn't find {len_pairs - 1} matches for {f}. Found {len(matches)} matches.\"\n )\n else:\n raise ValueError(f\"No adequate matches found for {f}.\")\n\n if len(results_set) != len(files):\n raise ValueError(\n f\"Could not find enough matches ({len(results_set)}) for all files ({len(files)})\"\n )\n return results\n\n\ndef setup_files(class_dir, seed, group_prefix=None):\n \"\"\"\n Returns shuffeld list of filenames\n \"\"\"\n random.seed(seed) # make sure its reproducible\n\n files = list_files(class_dir)\n\n if group_prefix is not None:\n files = group_by_prefix(files, group_prefix)\n\n files.sort()\n random.shuffle(files)\n return files\n\n\ndef split_class_dir_ratio(class_dir, output, ratio, seed, prog_bar, group_prefix, move):\n \"\"\"\n Splits a class folder\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix)\n\n # the data was shuffled already\n split_train_idx = int(ratio[0] * len(files))\n split_val_idx = split_train_idx + int(ratio[1] * len(files))\n\n li = split_files(files, split_train_idx, split_val_idx, len(ratio) == 3)\n copy_files(li, class_dir, output, prog_bar, move)\n\n\ndef split_class_dir_fixed(class_dir, output, fixed, seed, prog_bar, group_prefix, move):\n \"\"\"\n Splits a class folder and returns the total number of files\n \"\"\"\n files = setup_files(class_dir, seed, group_prefix)\n\n if not len(files) > sum(fixed):\n raise ValueError(\n f'The number of samples in class \"{class_dir.stem}\" are too few. There are only {len(files)} samples available but your fixed parameter {fixed} requires at least {sum(fixed)} files. You may want to split your classes by ratio.'\n )\n\n # the data was shuffeld already\n if len(fixed) <= 2:\n split_train_idx = len(files) - sum(fixed)\n split_val_idx = split_train_idx + fixed[0]\n else:\n split_train_idx = fixed[0]\n split_val_idx = fixed[0] + fixed[1]\n\n li = split_files(\n files,\n split_train_idx,\n split_val_idx,\n len(fixed) >= 2,\n None if len(fixed) != 3 else fixed[2],\n )\n copy_files(li, class_dir, output, prog_bar, move)\n return len(files)\n\n\ndef split_files(files, split_train_idx, split_val_idx, use_test, max_test=None):\n \"\"\"\n Splits the files along the provided indices\n \"\"\"\n files_train = files[:split_train_idx]\n files_val = (\n files[split_train_idx:split_val_idx] if use_test else files[split_train_idx:]\n )\n\n li = [(files_train, \"train\"), (files_val, \"val\")]\n\n # optional test folder\n if use_test:\n files_test = files[split_val_idx:]\n if max_test is not None:\n files_test = files_test[:max_test]\n\n li.append((files_test, \"test\"))\n return li\n\n\ndef copy_files(files_type, class_dir, output, prog_bar, move):\n \"\"\"\n Copies the files from the input folder to the output folder\n \"\"\"\n\n copy_fun = shutil.move if move else shutil.copy2\n\n # get the last part within the file\n class_name = path.split(class_dir)[1]\n for (files, folder_type) in files_type:\n full_path = path.join(output, folder_type, class_name)\n\n Path(full_path).mkdir(parents=True, exist_ok=True)\n for f in files:\n if not prog_bar is None:\n prog_bar.update()\n if type(f) == tuple:\n for x in f:\n copy_fun(x, full_path)\n else:\n copy_fun(f, full_path)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "jfilter__split-folders-a757c75b77db", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/jfilter__split-folders-a757c75b77db", "repo_key": "jfilter__split-folders", "repo": "jfilter/split-folders", "base_commit": "85fde3471cb0f045f068ff7fcbaf7bbd4c5bb2a6", "source_files": ["splitfolders/split.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Alias aggregation produces nested lists and fails with TypeError for UniqueList targets\n\n## Description\nWhen aggregating aliases, two issues are observed:\n\n1. If an existing alias is a scalar and a new alias is a list, the resulting alias becomes a nested list. For example, adding `'value1'` then `['value2', 'value3']` to the same key results in `['value1', ['value2', 'value3']]` instead of the expected flat list `['value1', 'value2', 'value3']`.\n2. Attempting to aggregate aliases where both the existing and new targets are `UniqueList` instances results in a `TypeError: unhashable type: 'UniqueList'`. Alias aggregation should handle `UniqueList` targets without error.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `65a4beb1051a` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### sql_metadata/column_extractor.py\n```python\n\"\"\"Single-pass SQL metadata extraction from a sqlglot AST.\n\nWalks the AST in ``arg_types``-key order (which mirrors the left-to-right\nSQL text order) and collects columns, column aliases, CTE names, and\nsubquery names into a :class:`_Collector` accumulator. The\n:class:`ColumnExtractor` class encapsulates the walk and all helper methods,\nreplacing the earlier flat-function design with a cohesive class.\n\nThe public entry point is :meth:`ColumnExtractor.extract`, which returns an\n:class:`ExtractionResult` dataclass consumed by :attr:`Parser.columns`\nand friends.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\nfrom sqlglot import exp\n\nfrom sql_metadata.exceptions import InvalidQueryDefinition\nfrom sql_metadata.utils import UniqueList, last_segment\n\n# ---------------------------------------------------------------------------\n# Result dataclass\n# ---------------------------------------------------------------------------\n\n\n@dataclass(frozen=True)\nclass ExtractionResult:\n \"\"\"Immutable container for column extraction results.\n\n Returned by :meth:`ColumnExtractor.extract` and consumed by\n :class:`Parser` to populate its column/alias/CTE properties.\n Each field corresponds to a public ``Parser`` property.\n \"\"\"\n\n columns: UniqueList\n columns_dict: dict[str, UniqueList]\n alias_names: UniqueList\n alias_dict: dict[str, UniqueList]\n alias_map: dict[str, str | list[str]]\n cte_names: UniqueList\n subquery_names: UniqueList\n output_columns: list[str]\n\n\n# ---------------------------------------------------------------------------\n# Clause classification (pure functions, no state)\n# ---------------------------------------------------------------------------\n\n\n#: Simple key \u2192 clause-name lookup for most ``arg_types`` keys.\n_CLAUSE_MAP: dict[str, str] = {\n \"where\": \"where\",\n \"group\": \"group_by\",\n \"order\": \"order_by\",\n \"having\": \"having\",\n}\n\n#: Keys that map to the ``\"join\"`` clause section.\n_JOIN_KEYS = frozenset({\"on\", \"using\"})\n\n\ndef _classify_expressions_clause(parent_type: type) -> str:\n \"\"\"Resolve the clause for an ``\"expressions\"`` key based on the parent node.\n\n :param parent_type: The type of the parent AST node.\n :returns: ``\"update\"``, ``\"select\"``, or ``\"\"`` for other parents.\n \"\"\"\n if parent_type is exp.Update:\n return \"update\"\n if parent_type is exp.Select:\n return \"select\"\n return \"\"\n\n\ndef _classify_clause(key: str, parent_type: type) -> str:\n \"\"\"Map an ``arg_types`` key and parent node type to a ``columns_dict`` section.\n\n :param key: The ``arg_types`` key through which the child was reached.\n :param parent_type: The type of the parent AST node.\n :returns: Section name string, or ``\"\"`` if the key does not map.\n \"\"\"\n if key == \"expressions\":\n return _classify_expressions_clause(parent_type)\n if key in _JOIN_KEYS:\n return \"join\"\n return _CLAUSE_MAP.get(key, \"\")\n\n\n# ---------------------------------------------------------------------------\n# Pure helpers (no state)\n# ---------------------------------------------------------------------------\n\n\ndef _dfs(node: exp.Expression) -> Any:\n \"\"\"Yield *node* and all its descendants in depth-first order.\n\n :param node: Root expression node.\n :yields: Each expression node in DFS pre-order.\n \"\"\"\n yield node\n for child in node.iter_expressions():\n yield from _dfs(child)\n\n\n#: Functions whose first argument is a date-part unit keyword, not a column.\n_DATE_PART_FUNCTIONS = frozenset(\n {\n \"dateadd\",\n \"datediff\",\n \"datepart\",\n \"datename\",\n \"date_add\",\n \"date_sub\",\n \"date_diff\",\n \"date_trunc\",\n \"timestampadd\",\n \"timestampdiff\",\n }\n)\n\n\ndef _is_date_part_unit(node: exp.Column) -> bool:\n \"\"\"Return ``True`` if *node* is the date-part unit argument of a function.\n\n Functions like ``DATEADD``, ``DATEDIFF``, and ``DATE_TRUNC`` accept a\n date-part keyword (``DAY``, ``MONTH``, \u2026) as their first argument.\n sqlglot parses these keywords as ``exp.Column`` nodes, but they are not\n real columns and must be skipped during extraction.\n\n :param node: A column AST node to inspect.\n :type node: exp.Column\n :rtype: bool\n \"\"\"\n parent = node.parent\n if (\n isinstance(parent, exp.Anonymous)\n and parent.this.lower() in _DATE_PART_FUNCTIONS\n ):\n exprs = parent.expressions\n return len(exprs) > 0 and exprs[0] is node\n return False\n\n\n# ---------------------------------------------------------------------------\n# Collector \u2014 accumulates results during AST walk\n# ---------------------------------------------------------------------------\n\n\nclass _Collector:\n \"\"\"Mutable accumulator for metadata gathered during the AST walk.\"\"\"\n\n __slots__ = (\n \"columns\",\n \"columns_dict\",\n \"alias_names\",\n \"alias_dict\",\n \"alias_map\",\n \"cte_names\",\n \"cte_alias_names\",\n \"subquery_items\",\n \"output_columns\",\n )\n\n def __init__(self) -> None:\n self.columns = UniqueList()\n self.columns_dict: dict[str, UniqueList] = {}\n self.alias_names = UniqueList()\n self.alias_dict: dict[str, UniqueList] = {}\n self.alias_map: dict[str, str | list[str]] = {}\n self.cte_names = UniqueList()\n self.cte_alias_names: set[str] = set()\n self.subquery_items: list[tuple[int, str]] = []\n self.output_columns: list[str] = []\n\n def add_column(self, name: str, clause: str) -> None:\n \"\"\"Record a column name, filing it into the appropriate clause section.\n\n :param name: The column name to record.\n :type name: str\n :param clause: The SQL clause section (e.g. ``\"select\"``, ``\"where\"``).\n :type clause: str\n \"\"\"\n self.columns.append(name)\n if clause:\n self.columns_dict.setdefault(clause, UniqueList()).append(name)\n\n def add_alias(self, name: str, target: Any, clause: str) -> None:\n \"\"\"Record a column alias and its target expression.\n\n :param name: The alias name.\n :type name: str\n :param target: The source column name or expression the alias refers\n to, or ``None`` if not determinable.\n :type target: Any\n :param clause: The SQL clause section where the alias was defined.\n :type clause: str\n \"\"\"\n self.alias_names.append(name)\n if clause:\n self.alias_dict.setdefault(clause, UniqueList()).append(name)\n if target is not None:\n if name in self.alias_map:\n # Alias already exists \u2014 aggregate targets into a list\n existing = self.alias_map[name]\n if isinstance(existing, list):\n # Already a list \u2014 append new target\n if target not in existing:\n existing.append(target)\n else:\n # Single value \u2014 convert to list\n if existing != target:\n self.alias_map[name] = [existing, target]\n else:\n # First occurrence \u2014 store as-is\n self.alias_map[name] = target\n\n\n# ---------------------------------------------------------------------------\n# arg_types keys to skip during the walk.\n# ---------------------------------------------------------------------------\n\n_SKIP_KEYS = frozenset({\"conflict\", \"returning\", \"alternative\"})\n\n\n# ---------------------------------------------------------------------------\n# ColumnExtractor \u2014 the main class\n# ---------------------------------------------------------------------------\n\n\nclass ColumnExtractor:\n \"\"\"Single-pass DFS extraction of columns, aliases, CTEs, and subqueries.\n\n Walks the AST in ``arg_types``-key order (which mirrors the left-to-right\n SQL text order) and collects all metadata into an internal\n :class:`_Collector`. Call :meth:`extract` to run the walk and return an\n :class:`ExtractionResult`.\n\n The class is designed around a single public entry point\n (:meth:`extract`), which triggers a recursive depth-first traversal of\n the sqlglot AST. Specialised handler methods process leaf-like nodes\n (columns, aliases, CTEs, subqueries) while the walk engine manages\n clause classification and child iteration.\n\n :param ast: Root sqlglot AST node (e.g. ``Select``, ``Insert``,\n ``Create``).\n :param table_aliases: Pre-computed mapping of table alias names to\n their real (resolved) table names.\n :param cte_name_map: Optional mapping of placeholder CTE names\n (produced by :class:`SqlCleaner`) back to the original qualified\n CTE names.\n \"\"\"\n\n def __init__(\n self,\n ast: exp.Expression,\n table_aliases: dict[str, str],\n cte_name_map: dict[str, str] | None = None,\n ):\n self._ast = ast\n self._table_aliases = table_aliases\n self._cte_name_map = cte_name_map or {}\n self._collector = _Collector()\n self._cte_restore_map = self._cte_name_map\n\n # -------------------------------------------------------------------\n # Public API\n # -------------------------------------------------------------------\n\n def extract(self) -> ExtractionResult:\n \"\"\"Run the full extraction walk and return an immutable result.\n\n Orchestrates the three-phase extraction process:\n\n 1. **Seed** \u2014 pre-populate CTE names so downstream handlers can\n recognise CTE column-alias references.\n 2. **Walk** \u2014 depth-first traversal of the AST, dispatching each\n node to the appropriate handler.\n 3. **Finalise** \u2014 restore qualified CTE names, sort subquery\n names, and package everything into an :class:`ExtractionResult`.\n\n For ``CREATE TABLE`` statements without a ``SELECT`` body (pure\n DDL), only ``ColumnDef`` nodes are collected during the walk.\n\n Example SQL::\n\n SELECT a, b FROM t WHERE a > 1\n\n :returns: An :class:`ExtractionResult` containing columns,\n aliases, CTE names, subquery names, and output columns.\n \"\"\"\n c = self._collector\n\n self._seed_cte_names()\n\n # Reset cte_names \u2014 walk will re-collect them in text order\n c.cte_names = UniqueList()\n self._walk(self._ast)\n\n # Restore qualified CTE names (reverse placeholder mapping)\n final_cte = UniqueList()\n for name in c.cte_names:\n final_cte.append(self._cte_restore_map.get(name, name))\n\n alias_dict = c.alias_dict\n return ExtractionResult(\n columns=c.columns,\n columns_dict=c.columns_dict,\n alias_names=c.alias_names,\n alias_dict=alias_dict,\n alias_map=c.alias_map,\n cte_names=final_cte,\n subquery_names=self._build_subquery_names(),\n output_columns=c.output_columns,\n )\n\n # -------------------------------------------------------------------\n # Setup helpers\n # -------------------------------------------------------------------\n\n def _seed_cte_names(self) -> None:\n \"\"\"Pre-populate CTE names in the collector before the main walk.\n\n Scans the AST for all ``CTE`` nodes and records their alias\n names. This allows :meth:`_handle_column` to recognize\n references like ``cte_name.col`` as CTE column-alias references\n rather than regular columns.\n\n Example SQL::\n\n WITH sales AS (SELECT id FROM orders) SELECT sales.id FROM sales\n\n The seed step records ``\"sales\"`` so that ``sales.id`` in the\n outer SELECT can be identified as a CTE-qualified reference.\n \"\"\"\n for cte in self._ast.find_all(exp.CTE):\n alias = cte.alias\n if alias:\n self._collector.cte_names.append(\n self._cte_restore_map.get(alias, alias)\n )\n\n def _build_subquery_names(self) -> UniqueList:\n \"\"\"Sort collected subquery items by depth and return their names.\n\n Subqueries are collected during the walk with their nesting\n depth. This method sorts them innermost-first (descending depth)\n and returns a :class:`UniqueList` of alias names in that order.\n\n Example SQL::\n\n SELECT (SELECT 1) AS a, (SELECT 2) AS b FROM t\n\n :returns: A :class:`UniqueList` of subquery alias names, ordered\n from innermost to outermost.\n \"\"\"\n c = self._collector\n c.subquery_items.sort(key=lambda x: -x[0])\n names = UniqueList()\n for _, name in c.subquery_items:\n names.append(name)\n return names\n\n # -------------------------------------------------------------------\n # DFS walk engine\n # -------------------------------------------------------------------\n\n def _walk(\n self, node: exp.Expression, clause: str = \"\", depth: int = 0\n ) -> None:\n \"\"\"Perform a depth-first walk of the AST in ``arg_types`` key order.\n\n This is the core recursive method. For each node it first\n attempts leaf dispatch via :meth:`_dispatch_leaf`. If the node\n is not a leaf, it iterates the node's ``arg_types`` keys in\n declaration order (which mirrors SQL text order) and recurses\n into each populated child.\n\n :param node: The current AST node to process.\n :param clause: The current SQL clause context (e.g. ``\"select\"``,\n ``\"where\"``). Propagated to child nodes and used to file\n columns into ``columns_dict`` sections.\n :param depth: Current nesting depth, used to sort subqueries by\n depth (innermost first).\n \"\"\"\n assert node is not None\n\n if self._dispatch_leaf(node, clause, depth):\n return\n\n if hasattr(node, \"arg_types\"):\n self._walk_children(node, clause, depth)\n\n def _walk_children(self, node: exp.Expression, clause: str, depth: int) -> None:\n \"\"\"Iterate and recurse into children of *node* in ``arg_types`` key order.\n\n For each child key, determines the SQL clause context (e.g.\n ``\"where\"`` \u2192 ``where``, ``\"on\"`` \u2192 ``join``) via\n :func:`_classify_clause`. Special-case keys (SELECT expressions,\n INSERT schema, JOIN USING) are routed to dedicated handlers via\n :meth:`_process_child_key`; all others get the default recursive\n walk via :meth:`_recurse_child`.\n\n :param node: Parent AST node whose children are being iterated.\n :param clause: Inherited clause context from the parent.\n :param depth: Current nesting depth.\n \"\"\"\n for key in node.arg_types:\n if key in _SKIP_KEYS:\n continue\n child = node.args.get(key)\n if child is None:\n continue\n\n new_clause = _classify_clause(key, type(node)) or clause\n\n if not self._process_child_key(node, key, child, new_clause, depth):\n self._recurse_child(child, new_clause, depth)\n\n def _dispatch_leaf(self, node: exp.Expression, clause: str, depth: int) -> bool:\n \"\"\"Dispatch leaf-like AST nodes to their specialised handlers.\n\n Checks if *node* is a terminal or semi-terminal node type that\n should be handled directly rather than recursed into. Each\n branch delegates to the appropriate handler and returns ``True``\n to stop further recursion, or ``False`` to let the walk continue.\n\n :param node: The AST node to inspect.\n :param clause: Current clause context.\n :param depth: Current nesting depth.\n :returns: ``True`` if the node was handled (caller should stop\n recursion), ``False`` to continue the walk.\n \"\"\"\n if self._is_literal_values_without_subquery(node):\n # e.g. INSERT INTO t VALUES (1, 2) \u2014 skip literal value lists\n retur\n... [truncated 26896 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "macbre__sql-metadata-4ca0cd614a17", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/macbre__sql-metadata-4ca0cd614a17", "repo_key": "macbre__sql-metadata", "repo": "macbre/sql-metadata", "base_commit": "65a4beb1051adeb14b5878af0725deb9151dd475", "source_files": ["sql_metadata/column_extractor.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Column aliases in UNION queries are overwritten instead of aggregated\n\n## Description\nWhen a `UNION` query uses the same alias for columns from different branches, the alias mapping only retains the last encountered source column. This results in the loss of information about earlier source columns that share the same alias.\n\nFor example, given the query:\n```sql\nSELECT a.A as M FROM tab1 a UNION SELECT b.B as M FROM tab2 b\n```\n**Actual Behavior:** The alias `M` is mapped only to `tab2.B`, losing the reference to `tab1.A`.\n**Expected Behavior:** The alias `M` should be mapped to a collection containing both `tab1.A` and `tab2.B`.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `dd5ee369ed28` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### sql_metadata/column_extractor.py\n```python\n\"\"\"Single-pass SQL metadata extraction from a sqlglot AST.\n\nWalks the AST in ``arg_types``-key order (which mirrors the left-to-right\nSQL text order) and collects columns, column aliases, CTE names, and\nsubquery names into a :class:`_Collector` accumulator. The\n:class:`ColumnExtractor` class encapsulates the walk and all helper methods,\nreplacing the earlier flat-function design with a cohesive class.\n\nThe public entry point is :meth:`ColumnExtractor.extract`, which returns an\n:class:`ExtractionResult` dataclass consumed by :attr:`Parser.columns`\nand friends.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\nfrom sqlglot import exp\n\nfrom sql_metadata.exceptions import InvalidQueryDefinition\nfrom sql_metadata.utils import UniqueList, last_segment\n\n# ---------------------------------------------------------------------------\n# Result dataclass\n# ---------------------------------------------------------------------------\n\n\n@dataclass(frozen=True)\nclass ExtractionResult:\n \"\"\"Immutable container for column extraction results.\n\n Returned by :meth:`ColumnExtractor.extract` and consumed by\n :class:`Parser` to populate its column/alias/CTE properties.\n Each field corresponds to a public ``Parser`` property.\n \"\"\"\n\n columns: UniqueList\n columns_dict: dict[str, UniqueList]\n alias_names: UniqueList\n alias_dict: dict[str, UniqueList]\n alias_map: dict[str, str | list[str]]\n cte_names: UniqueList\n subquery_names: UniqueList\n output_columns: list[str]\n\n\n# ---------------------------------------------------------------------------\n# Clause classification (pure functions, no state)\n# ---------------------------------------------------------------------------\n\n\n#: Simple key \u2192 clause-name lookup for most ``arg_types`` keys.\n_CLAUSE_MAP: dict[str, str] = {\n \"where\": \"where\",\n \"group\": \"group_by\",\n \"order\": \"order_by\",\n \"having\": \"having\",\n}\n\n#: Keys that map to the ``\"join\"`` clause section.\n_JOIN_KEYS = frozenset({\"on\", \"using\"})\n\n\ndef _classify_expressions_clause(parent_type: type) -> str:\n \"\"\"Resolve the clause for an ``\"expressions\"`` key based on the parent node.\n\n :param parent_type: The type of the parent AST node.\n :returns: ``\"update\"``, ``\"select\"``, or ``\"\"`` for other parents.\n \"\"\"\n if parent_type is exp.Update:\n return \"update\"\n if parent_type is exp.Select:\n return \"select\"\n return \"\"\n\n\ndef _classify_clause(key: str, parent_type: type) -> str:\n \"\"\"Map an ``arg_types`` key and parent node type to a ``columns_dict`` section.\n\n :param key: The ``arg_types`` key through which the child was reached.\n :param parent_type: The type of the parent AST node.\n :returns: Section name string, or ``\"\"`` if the key does not map.\n \"\"\"\n if key == \"expressions\":\n return _classify_expressions_clause(parent_type)\n if key in _JOIN_KEYS:\n return \"join\"\n return _CLAUSE_MAP.get(key, \"\")\n\n\n# ---------------------------------------------------------------------------\n# Pure helpers (no state)\n# ---------------------------------------------------------------------------\n\n\ndef _dfs(node: exp.Expression) -> Any:\n \"\"\"Yield *node* and all its descendants in depth-first order.\n\n :param node: Root expression node.\n :yields: Each expression node in DFS pre-order.\n \"\"\"\n yield node\n for child in node.iter_expressions():\n yield from _dfs(child)\n\n\n#: Functions whose first argument is a date-part unit keyword, not a column.\n_DATE_PART_FUNCTIONS = frozenset(\n {\n \"dateadd\",\n \"datediff\",\n \"datepart\",\n \"datename\",\n \"date_add\",\n \"date_sub\",\n \"date_diff\",\n \"date_trunc\",\n \"timestampadd\",\n \"timestampdiff\",\n }\n)\n\n\ndef _is_date_part_unit(node: exp.Column) -> bool:\n \"\"\"Return ``True`` if *node* is the date-part unit argument of a function.\n\n Functions like ``DATEADD``, ``DATEDIFF``, and ``DATE_TRUNC`` accept a\n date-part keyword (``DAY``, ``MONTH``, \u2026) as their first argument.\n sqlglot parses these keywords as ``exp.Column`` nodes, but they are not\n real columns and must be skipped during extraction.\n\n :param node: A column AST node to inspect.\n :type node: exp.Column\n :rtype: bool\n \"\"\"\n parent = node.parent\n if (\n isinstance(parent, exp.Anonymous)\n and parent.this.lower() in _DATE_PART_FUNCTIONS\n ):\n exprs = parent.expressions\n return len(exprs) > 0 and exprs[0] is node\n return False\n\n\n# ---------------------------------------------------------------------------\n# Collector \u2014 accumulates results during AST walk\n# ---------------------------------------------------------------------------\n\n\nclass _Collector:\n \"\"\"Mutable accumulator for metadata gathered during the AST walk.\"\"\"\n\n __slots__ = (\n \"columns\",\n \"columns_dict\",\n \"alias_names\",\n \"alias_dict\",\n \"alias_map\",\n \"cte_names\",\n \"cte_alias_names\",\n \"subquery_items\",\n \"output_columns\",\n )\n\n def __init__(self) -> None:\n self.columns = UniqueList()\n self.columns_dict: dict[str, UniqueList] = {}\n self.alias_names = UniqueList()\n self.alias_dict: dict[str, UniqueList] = {}\n self.alias_map: dict[str, str | list[str]] = {}\n self.cte_names = UniqueList()\n self.cte_alias_names: set[str] = set()\n self.subquery_items: list[tuple[int, str]] = []\n self.output_columns: list[str] = []\n\n def add_column(self, name: str, clause: str) -> None:\n \"\"\"Record a column name, filing it into the appropriate clause section.\n\n :param name: The column name to record.\n :type name: str\n :param clause: The SQL clause section (e.g. ``\"select\"``, ``\"where\"``).\n :type clause: str\n \"\"\"\n self.columns.append(name)\n if clause:\n self.columns_dict.setdefault(clause, UniqueList()).append(name)\n\n def add_alias(self, name: str, target: Any, clause: str) -> None:\n \"\"\"Record a column alias and its target expression.\n\n :param name: The alias name.\n :type name: str\n :param target: The source column name or expression the alias refers\n to, or ``None`` if not determinable.\n :type target: Any\n :param clause: The SQL clause section where the alias was defined.\n :type clause: str\n \"\"\"\n self.alias_names.append(name)\n if clause:\n self.alias_dict.setdefault(clause, UniqueList()).append(name)\n if target is not None:\n self.alias_map[name] = target\n\n\n# ---------------------------------------------------------------------------\n# arg_types keys to skip during the walk.\n# ---------------------------------------------------------------------------\n\n_SKIP_KEYS = frozenset({\"conflict\", \"returning\", \"alternative\"})\n\n\n# ---------------------------------------------------------------------------\n# ColumnExtractor \u2014 the main class\n# ---------------------------------------------------------------------------\n\n\nclass ColumnExtractor:\n \"\"\"Single-pass DFS extraction of columns, aliases, CTEs, and subqueries.\n\n Walks the AST in ``arg_types``-key order (which mirrors the left-to-right\n SQL text order) and collects all metadata into an internal\n :class:`_Collector`. Call :meth:`extract` to run the walk and return an\n :class:`ExtractionResult`.\n\n The class is designed around a single public entry point\n (:meth:`extract`), which triggers a recursive depth-first traversal of\n the sqlglot AST. Specialised handler methods process leaf-like nodes\n (columns, aliases, CTEs, subqueries) while the walk engine manages\n clause classification and child iteration.\n\n :param ast: Root sqlglot AST node (e.g. ``Select``, ``Insert``,\n ``Create``).\n :param table_aliases: Pre-computed mapping of table alias names to\n their real (resolved) table names.\n :param cte_name_map: Optional mapping of placeholder CTE names\n (produced by :class:`SqlCleaner`) back to the original qualified\n CTE names.\n \"\"\"\n\n def __init__(\n self,\n ast: exp.Expression,\n table_aliases: dict[str, str],\n cte_name_map: dict[str, str] | None = None,\n ):\n self._ast = ast\n self._table_aliases = table_aliases\n self._cte_name_map = cte_name_map or {}\n self._collector = _Collector()\n self._cte_restore_map = self._cte_name_map\n\n # -------------------------------------------------------------------\n # Public API\n # -------------------------------------------------------------------\n\n def extract(self) -> ExtractionResult:\n \"\"\"Run the full extraction walk and return an immutable result.\n\n Orchestrates the three-phase extraction process:\n\n 1. **Seed** \u2014 pre-populate CTE names so downstream handlers can\n recognise CTE column-alias references.\n 2. **Walk** \u2014 depth-first traversal of the AST, dispatching each\n node to the appropriate handler.\n 3. **Finalise** \u2014 restore qualified CTE names, sort subquery\n names, and package everything into an :class:`ExtractionResult`.\n\n For ``CREATE TABLE`` statements without a ``SELECT`` body (pure\n DDL), only ``ColumnDef`` nodes are collected during the walk.\n\n Example SQL::\n\n SELECT a, b FROM t WHERE a > 1\n\n :returns: An :class:`ExtractionResult` containing columns,\n aliases, CTE names, subquery names, and output columns.\n \"\"\"\n c = self._collector\n\n self._seed_cte_names()\n\n # Reset cte_names \u2014 walk will re-collect them in text order\n c.cte_names = UniqueList()\n self._walk(self._ast)\n\n # Restore qualified CTE names (reverse placeholder mapping)\n final_cte = UniqueList()\n for name in c.cte_names:\n final_cte.append(self._cte_restore_map.get(name, name))\n\n alias_dict = c.alias_dict\n return ExtractionResult(\n columns=c.columns,\n columns_dict=c.columns_dict,\n alias_names=c.alias_names,\n alias_dict=alias_dict,\n alias_map=c.alias_map,\n cte_names=final_cte,\n subquery_names=self._build_subquery_names(),\n output_columns=c.output_columns,\n )\n\n # -------------------------------------------------------------------\n # Setup helpers\n # -------------------------------------------------------------------\n\n def _seed_cte_names(self) -> None:\n \"\"\"Pre-populate CTE names in the collector before the main walk.\n\n Scans the AST for all ``CTE`` nodes and records their alias\n names. This allows :meth:`_handle_column` to recognize\n references like ``cte_name.col`` as CTE column-alias references\n rather than regular columns.\n\n Example SQL::\n\n WITH sales AS (SELECT id FROM orders) SELECT sales.id FROM sales\n\n The seed step records ``\"sales\"`` so that ``sales.id`` in the\n outer SELECT can be identified as a CTE-qualified reference.\n \"\"\"\n for cte in self._ast.find_all(exp.CTE):\n alias = cte.alias\n if alias:\n self._collector.cte_names.append(\n self._cte_restore_map.get(alias, alias)\n )\n\n def _build_subquery_names(self) -> UniqueList:\n \"\"\"Sort collected subquery items by depth and return their names.\n\n Subqueries are collected during the walk with their nesting\n depth. This method sorts them innermost-first (descending depth)\n and returns a :class:`UniqueList` of alias names in that order.\n\n Example SQL::\n\n SELECT (SELECT 1) AS a, (SELECT 2) AS b FROM t\n\n :returns: A :class:`UniqueList` of subquery alias names, ordered\n from innermost to outermost.\n \"\"\"\n c = self._collector\n c.subquery_items.sort(key=lambda x: -x[0])\n names = UniqueList()\n for _, name in c.subquery_items:\n names.append(name)\n return names\n\n # -------------------------------------------------------------------\n # DFS walk engine\n # -------------------------------------------------------------------\n\n def _walk(\n self, node: exp.Expression, clause: str = \"\", depth: int = 0\n ) -> None:\n \"\"\"Perform a depth-first walk of the AST in ``arg_types`` key order.\n\n This is the core recursive method. For each node it first\n attempts leaf dispatch via :meth:`_dispatch_leaf`. If the node\n is not a leaf, it iterates the node's ``arg_types`` keys in\n declaration order (which mirrors SQL text order) and recurses\n into each populated child.\n\n :param node: The current AST node to process.\n :param clause: The current SQL clause context (e.g. ``\"select\"``,\n ``\"where\"``). Propagated to child nodes and used to file\n columns into ``columns_dict`` sections.\n :param depth: Current nesting depth, used to sort subqueries by\n depth (innermost first).\n \"\"\"\n assert node is not None\n\n if self._dispatch_leaf(node, clause, depth):\n return\n\n if hasattr(node, \"arg_types\"):\n self._walk_children(node, clause, depth)\n\n def _walk_children(self, node: exp.Expression, clause: str, depth: int) -> None:\n \"\"\"Iterate and recurse into children of *node* in ``arg_types`` key order.\n\n For each child key, determines the SQL clause context (e.g.\n ``\"where\"`` \u2192 ``where``, ``\"on\"`` \u2192 ``join``) via\n :func:`_classify_clause`. Special-case keys (SELECT expressions,\n INSERT schema, JOIN USING) are routed to dedicated handlers via\n :meth:`_process_child_key`; all others get the default recursive\n walk via :meth:`_recurse_child`.\n\n :param node: Parent AST node whose children are being iterated.\n :param clause: Inherited clause context from the parent.\n :param depth: Current nesting depth.\n \"\"\"\n for key in node.arg_types:\n if key in _SKIP_KEYS:\n continue\n child = node.args.get(key)\n if child is None:\n continue\n\n new_clause = _classify_clause(key, type(node)) or clause\n\n if not self._process_child_key(node, key, child, new_clause, depth):\n self._recurse_child(child, new_clause, depth)\n\n def _dispatch_leaf(self, node: exp.Expression, clause: str, depth: int) -> bool:\n \"\"\"Dispatch leaf-like AST nodes to their specialised handlers.\n\n Checks if *node* is a terminal or semi-terminal node type that\n should be handled directly rather than recursed into. Each\n branch delegates to the appropriate handler and returns ``True``\n to stop further recursion, or ``False`` to let the walk continue.\n\n :param node: The AST node to inspect.\n :param clause: Current clause context.\n :param depth: Current nesting depth.\n :returns: ``True`` if the node was handled (caller should stop\n recursion), ``False`` to continue the walk.\n \"\"\"\n if self._is_literal_values_without_subquery(node):\n # e.g. INSERT INTO t VALUES (1, 2) \u2014 skip literal value lists\n return True\n if isinstance(node, (exp.Star, exp.ColumnDef, exp.Identifier)):\n if isinstance(node, exp.ColumnDef):\n # e.g. CREATE TABLE t (col INT) \u2014 collect ColumnDef names\n self._collector.add_column(node.name, clause)\n # Star and Identifier are terminal \u2014 no further recursion\n return True\n if isinstance(node, exp.CTE):\n # e.g. WITH cte AS (SELECT ...) \u2014 delegate to CTE handler\n self._handle_cte(node, depth)\n return True\n if isinstance(node, exp.Column):\n # e.g. SELECT t.col FROM t \u2014\n... [truncated 26284 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "macbre__sql-metadata-65a4beb1051a", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/macbre__sql-metadata-65a4beb1051a", "repo_key": "macbre__sql-metadata", "repo": "macbre/sql-metadata", "base_commit": "dd5ee369ed28f84bc74810baa0877085224f8525", "source_files": ["sql_metadata/column_extractor.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** SQLGLot warnings for internal subquery re-rendering leak to users\n\n## Description\nWhen processing certain SQL queries, `sqlglot` generates \"unsupported-feature\" warnings related to internal re-rendering of subquery bodies. These warnings are currently displayed to the end-user.\n\n**Actual Behavior:**\nUsers observe `sqlglot` warnings (e.g., related to T-SQL `FOR XML PATH`) in their output, even though the SQL causing the warning is for internal processing.\n\n**Expected Behavior:**\nWarnings generated during internal `sqlglot` re-rendering of subqueries should be suppressed and not visible to the end-user.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `425b46326d4a` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### sql_metadata/nested_resolver.py\n```python\n\"\"\"Nested column resolution and CTE/subquery body extraction.\n\nThe :class:`NestedResolver` class owns the complete \"look inside nested\nqueries\" concern: rendering CTE/subquery AST nodes back to SQL, parsing\nthose bodies with sub-:class:`Parser` instances, and resolving\n``subquery.column`` references to actual columns.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from sql_metadata.parser import Parser\n\nfrom sqlglot import exp\nfrom sqlglot.generator import Generator\n\nfrom sql_metadata.utils import (\n UniqueList,\n last_segment,\n)\n\n# ---------------------------------------------------------------------------\n# Custom SQL generator \u2014 preserves function signatures\n# ---------------------------------------------------------------------------\n\n\nclass _PreservingGenerator(Generator):\n \"\"\"Custom SQL generator that preserves function signatures.\n\n sqlglot normalises certain functions when rendering SQL (e.g.\n ``IFNULL`` \u2192 ``COALESCE``, ``DIV`` \u2192 ``CAST(\u2026 / \u2026 AS INT)``).\n This generator overrides those transformations so that the output\n only differs from the input in keyword/function-name casing and\n explicit ``AS`` insertion.\n \"\"\"\n\n TRANSFORMS = {\n **Generator.TRANSFORMS,\n exp.CurrentDate: lambda self, e: \"CURRENT_DATE()\",\n exp.IntDiv: lambda self, e: (\n f\"{self.sql(e, 'this')} DIV {self.sql(e, 'expression')}\"\n ),\n }\n\n def coalesce_sql(self, expression: exp.Expression) -> str:\n \"\"\"Render ``COALESCE`` back to ``IFNULL`` for two-argument calls.\n\n :param expression: The ``exp.Coalesce`` AST node.\n :type expression: exp.Expression\n :returns: SQL string using ``IFNULL`` (2 args) or ``COALESCE``.\n :rtype: str\n \"\"\"\n args = [expression.this] + expression.expressions\n if len(args) == 2:\n return f\"IFNULL({self.sql(args[0])}, {self.sql(args[1])})\"\n args_sql = \", \".join(self.sql(a) for a in args)\n return f\"COALESCE({args_sql})\"\n\n def dateadd_sql(self, expression: exp.Expression) -> str:\n \"\"\"Render ``exp.DateAdd`` back to ``DATE_ADD(\u2026)`` syntax.\n\n :param expression: The ``exp.DateAdd`` AST node.\n :type expression: exp.Expression\n :rtype: str\n \"\"\"\n return (\n f\"DATE_ADD({self.sql(expression, 'this')}, \"\n f\"{self.sql(expression, 'expression')})\"\n )\n\n def datesub_sql(self, expression: exp.Expression) -> str:\n \"\"\"Render ``exp.DateSub`` back to ``DATE_SUB(\u2026)`` syntax.\n\n :param expression: The ``exp.DateSub`` AST node.\n :type expression: exp.Expression\n :rtype: str\n \"\"\"\n return (\n f\"DATE_SUB({self.sql(expression, 'this')}, \"\n f\"{self.sql(expression, 'expression')})\"\n )\n\n def tsordsadd_sql(self, expression: exp.Expression) -> str:\n \"\"\"Render ``exp.TsOrDsAdd`` as ``DATE_ADD`` or ``DATE_SUB``.\n\n When the interval multiplier is ``-1`` the expression is rendered\n as ``DATE_SUB`` instead, preserving the original SQL intent.\n\n :param expression: The ``exp.TsOrDsAdd`` AST node.\n :type expression: exp.Expression\n :rtype: str\n \"\"\"\n this = self.sql(expression, \"this\")\n expr_node = expression.expression\n if isinstance(expr_node, exp.Mul):\n right = expr_node.expression\n if (\n isinstance(right, exp.Neg)\n and isinstance(right.this, exp.Literal)\n and right.this.this == \"1\"\n ):\n left = self.sql(expr_node, \"this\")\n return f\"DATE_SUB({this}, {left})\"\n return f\"DATE_ADD({this}, {self.sql(expression, 'expression')})\"\n\n def not_sql(self, expression: exp.Expression) -> str:\n \"\"\"Render ``NOT`` expressions preserving ``IS NOT NULL`` and ``NOT IN``.\n\n sqlglot normalises ``IS NOT NULL`` to ``NOT (x IS NULL)`` and\n ``NOT IN`` to ``NOT (x IN (...))``; this override renders them\n back to their original idiomatic forms.\n\n :param expression: The ``exp.Not`` AST node.\n :type expression: exp.Expression\n :rtype: str\n \"\"\"\n child = expression.this\n if isinstance(child, exp.Is) and isinstance(child.expression, exp.Null):\n return f\"{self.sql(child, 'this')} IS NOT NULL\"\n if isinstance(child, exp.In):\n return f\"{self.sql(child, 'this')} NOT IN ({self.expressions(child)})\"\n # sqlglot stubs under-type not_sql's parameter and return type.\n return super().not_sql(expression) # type: ignore[arg-type, no-any-return]\n\n\n# ---------------------------------------------------------------------------\n# Resolution helpers\n# ---------------------------------------------------------------------------\n\n\ndef _is_qualified_reference(result: list[str]) -> bool:\n \"\"\"Check if *result* is a single dotted reference like ``['cte.col']``.\n\n :param result: Resolved column list to inspect.\n :type result: list[str]\n :rtype: bool\n \"\"\"\n return len(result) == 1 and \".\" in result[0]\n\n\ndef _is_not_already_resolved_qualified_reference(\n result: list[str], column: str\n) -> bool:\n \"\"\"Check if *result* is a qualified reference that differs from *column*.\n\n :param result: Resolved column list to inspect.\n :type result: list[str]\n :param column: The original column name before resolution.\n :type column: str\n :rtype: bool\n \"\"\"\n return _is_qualified_reference(result) and result != [column]\n\n\n# ---------------------------------------------------------------------------\n# NestedResolver class\n# ---------------------------------------------------------------------------\n\n\nclass NestedResolver:\n \"\"\"Resolve column references through subqueries and CTEs.\n\n Owns the complete lifecycle of nested query resolution:\n\n 1. **Body extraction** \u2014 render CTE/subquery AST nodes back to SQL\n via :class:`_PreservingGenerator`.\n 2. **Column resolution** \u2014 parse bodies with sub-Parsers and resolve\n ``subquery.column`` references to actual columns.\n 3. **Unqualified alias resolution** \u2014 detect column names that are actually\n aliases defined inside nested queries.\n\n :param ast: Root AST node (for body extraction).\n :param parser_factory: Callable that constructs a :class:`Parser` from\n a SQL string. Injected to break the ``parser.py`` \u2194 ``nested_resolver.py``\n import cycle \u2014 ``parser.py`` already imports this module, so it passes\n the ``Parser`` class itself at resolver-construction time.\n \"\"\"\n\n def __init__(\n self,\n ast: exp.Expression,\n parser_factory: Callable[[str], \"Parser\"],\n ) -> None:\n self._ast = ast\n self._parser_factory = parser_factory\n\n # Lazy caches\n self._subqueries_parsers: dict[str, \"Parser\"] = {}\n self._with_parsers: dict[str, \"Parser\"] = {}\n self._columns_aliases: dict[str, str | list[str]] = {}\n self._cached_cte_nodes: list[exp.CTE] | None = None\n\n # Set by resolve() caller\n self._subqueries_names: list[str] = []\n self._subqueries: dict[str, str] = {}\n self._with_names: list[str] = []\n self._with_queries: dict[str, str] = {}\n\n # -------------------------------------------------------------------\n # Public API \u2014 name extraction\n # -------------------------------------------------------------------\n\n def extract_cte_names(\n self,\n cte_name_map: dict[str, str],\n ) -> list[str]:\n \"\"\"Extract CTE names from the AST.\n\n Called by :attr:`Parser.with_names`.\n\n :param cte_name_map: Mapping of placeholder names to original\n qualified names, e.g. ``{\"db__DOT__cte\": \"db.cte\"}``.\n Built by :func:`SqlCleaner._normalize_cte_names` because\n sqlglot cannot parse dots in CTE names \u2014 they get rewritten\n to placeholders before parsing. This map restores the\n original names in the output.\n :returns: List of CTE names, e.g. ``[\"db.cte\", \"sales\"]``.\n \"\"\"\n return UniqueList([\n cte_name_map.get(cte.alias, cte.alias) for cte in self._cte_nodes()\n ])\n\n def extract_cte_bodies(\n self,\n cte_name_map: dict[str, str],\n ) -> dict[str, str]:\n \"\"\"Extract CTE body SQL for each CTE in the AST.\n\n :param cte_name_map: Placeholder-to-original mapping, e.g.\n ``{\"db__DOT__cte\": \"db.cte\"}``. See :meth:`extract_cte_names`\n for details.\n :returns: Mapping of ``{cte_name: body_sql}``,\n e.g. ``{\"db.cte\": \"SELECT id FROM t\"}``.\n \"\"\"\n results: dict[str, str] = {}\n for cte in self._cte_nodes():\n alias = cte.alias\n original_name = cte_name_map.get(alias, alias)\n results[original_name] = self._body_sql(cte.this)\n\n return results\n\n @staticmethod\n def extract_subqueries(\n ast: exp.Expression,\n ) -> tuple[list[str], dict[str, str]]:\n \"\"\"Extract subquery names and bodies in a single post-order walk.\n\n Aliased subqueries keep their alias as the name. Unaliased\n subqueries (e.g. ``WHERE id IN (SELECT \u2026)``) get auto-generated\n names ``subquery_1``, ``subquery_2``, etc.\n\n Example SQL::\n\n SELECT * FROM (SELECT id FROM t) AS sub\n WHERE id IN (SELECT id FROM t2)\n\n :returns: ``(names, bodies)`` where *names* is ordered innermost-first,\n e.g. ``([\"subquery_1\", \"sub\"], {...})``.\n \"\"\"\n names: list[str] = UniqueList()\n bodies: dict[str, str] = {}\n NestedResolver._walk_subqueries(ast, names, bodies, 0)\n return names, bodies\n\n # -------------------------------------------------------------------\n # Public API \u2014 column resolution\n # -------------------------------------------------------------------\n\n def resolve(\n self,\n columns: \"UniqueList\",\n columns_dict: dict[str, UniqueList],\n columns_aliases: dict[str, str | list[str]],\n subqueries_names: list[str],\n subqueries: dict[str, str],\n with_names: list[str],\n with_queries: dict[str, str],\n ) -> tuple[UniqueList, dict[str, UniqueList], dict[str, str | list[str]]]:\n \"\"\"Resolve columns that reference subqueries or CTEs.\n\n Two-phase resolution:\n\n 1. Replace ``subquery.column`` references with the actual column\n from the subquery/CTE definition.\n 2. Drop unqualified column names that are actually aliases defined\n inside a nested query.\n\n Also applies the resolution to *columns_dict*,\n but there instead of dropping we also resolve unqualified aliases.\n\n Example SQL::\n\n WITH cte AS (SELECT a FROM t)\n SELECT cte.a FROM cte\n\n :returns: Tuple of ``(columns, columns_dict, columns_aliases)``.\n \"\"\"\n self._subqueries_names = subqueries_names\n self._subqueries = subqueries\n self._with_names = with_names\n self._with_queries = with_queries\n self._columns_aliases = columns_aliases\n\n # For columns drop aliases as we need only actual columns\n columns = self._resolve_and_filter(columns, drop_unqualified_aliases=True)\n\n if columns_dict:\n # For columns_dict do not drop aliases but instead resolve them to columns.\n # That ensures the column is present in all the relevant sections regardless\n # if it's called directly or by alias i.e. SELECT a AS x FROM tbl ORDER BY x\n # the column a should appear both in select and order_by sections.\n for section, cols in list(columns_dict.items()):\n columns_dict[section] = self._resolve_and_filter(\n cols, drop_unqualified_aliases=False\n )\n\n return columns, columns_dict, self._columns_aliases\n\n def resolve_column_alias(\n self, alias: str | list[str], columns_aliases: dict[str, str | list[str]]\n ) -> list[str]:\n \"\"\"Public interface for alias resolution (used by parser.py).\n\n Example SQL::\n\n SELECT a AS x FROM t ORDER BY x\n\n Resolves ``\"x\"`` \u2192 ``\"a\"`` using the alias map.\n \"\"\"\n return self._resolve_column_alias(alias, columns_aliases)\n\n # -------------------------------------------------------------------\n # Resolution pipeline \u2014 callers before callees\n # -------------------------------------------------------------------\n\n def _resolve_and_filter(\n self, columns: \"UniqueList\", drop_unqualified_aliases: bool = True\n ) -> \"UniqueList\":\n \"\"\"Apply subquery/CTE resolution and unqualified-alias handling.\n\n Phase 1: resolve ``sub.col`` references via :meth:`_resolve_sub_queries`.\n Phase 2: detect unqualified names that are nested-query aliases.\n\n Example SQL::\n\n SELECT sub.id FROM (SELECT id FROM users) AS sub\n\n Phase 1 resolves ``sub.id`` \u2192 ``id``.\n Phase 2 checks if ``id`` is a nested alias (it is not, so it stays).\n \"\"\"\n resolved: list[str] = UniqueList()\n for col in columns:\n resolved.extend(self._resolve_sub_queries(col))\n\n final = UniqueList()\n for col in resolved:\n if \".\" in col:\n # e.g. schema.col \u2014 skip unqualified alias resolution\n final.append(col)\n continue\n new_cols = self._resolve_unqualified_through_nested(col)\n if new_cols != [col]:\n # e.g. SELECT x FROM (SELECT a AS x FROM t) AS sub\n # \u2014 \"x\" resolved to \"a\", drop the alias from columns\n if not drop_unqualified_aliases:\n final.extend(new_cols)\n continue\n # e.g. SELECT id FROM t \u2014 no alias match, keep as-is\n final.append(col)\n return final\n\n def _resolve_sub_queries(self, column: str) -> list[str]:\n \"\"\"Resolve a ``subquery.column`` reference to actual column(s).\n\n Tries subquery sources first, then CTE sources.\n\n Example SQL::\n\n SELECT sub.id FROM (SELECT id FROM users) AS sub\n\n Resolves ``\"sub.id\"`` \u2192 ``[\"id\"]``.\n \"\"\"\n result: list[str] = [column]\n for names, defs, cache in self._nested_sources():\n if _is_qualified_reference(result):\n # e.g. \"sub.id\" \u2014 still a qualified reference, try next source\n result = self._resolve_nested_query(\n subquery_alias=result[0],\n nested_queries_names=names,\n nested_queries=defs,\n already_parsed=cache,\n )\n # Recursively resolve chained CTE references: c3.a \u2192 c2.a \u2192 c1.a \u2192 a\n if _is_not_already_resolved_qualified_reference(result, column):\n return self._resolve_sub_queries(result[0])\n return result\n\n def _resolve_unqualified_through_nested(\n self, col_name: str\n ) -> list[str]:\n \"\"\"Resolve an unqualified column name through subquery/CTE alias definitions.\n\n Checks subquery aliases first (``check_columns=True``), then CTE\n aliases (``check_columns=False``).\n\n Example SQL::\n\n SELECT x FROM (SELECT a AS x FROM users) AS sub\n\n Resolves ``\"x\"`` \u2192 ``[\"a\"]`` (found as alias in subquery body).\n \"\"\"\n for i, (names, defs, cache) in enumerate(self._nested_sources()):\n # check_columns for subqueries only \u2014 prevents CTE aliases\n # from claiming subquery columns, e.g. in:\n # WITH cte AS (SELECT x AS name FROM t1)\n # SELECT name FROM (SELECT name FROM t2) AS sub\n # \"name\" is a real column in sub, not the CTE alias.\n result = self._lookup_alias_in_nested(\n col_name, names\n... [truncated 11215 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "macbre__sql-metadata-9af6df2d685d", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/macbre__sql-metadata-9af6df2d685d", "repo_key": "macbre__sql-metadata", "repo": "macbre/sql-metadata", "base_commit": "425b46326d4a7b7e937f3ef19b321df0512b9163", "source_files": ["sql_metadata/nested_resolver.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Missing extension point to modify loaded data before schema loading\n\n## Description\nCurrently, there is no mechanism to modify data loaded from a request location (e.g., query parameters, JSON body) *after* it has been loaded but *before* it is passed to the schema for validation and loading. For example, users need a way to strip whitespace from specific fields or perform other pre-processing steps on the raw input.\n\n**Actual Behavior:** Data is passed directly from the location loader to the schema without an intermediate modification step.\n**Expected Behavior:** Users should be able to define custom logic to transform or clean loaded data after it's retrieved from the request location but before the schema processes it.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `f953dff5c77b` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.rst\n```python\nChangelog\n---------\n\n8.0.0 (Unreleased)\n******************\n\nFeatures:\n\n* ``unknown`` defaults to `None` for body locations (`json`, `form` and\n `json_or_form`) (:issue:`580`).\n\n* Detection of fields as \"multi-value\" for unpacking lists from multi-dict\n types is now extensible with the ``is_multiple`` attribute. If a field sets\n ``is_multiple = True`` it will be detected as a multi-value field.\n (:issue:`563`)\n\n* If ``is_multiple`` is not set or is set to ``None``, webargs will check if the\n field is an instance of ``List`` or ``Tuple``.\n\n* A new attribute on ``Parser`` objects, ``Parser.KNOWN_MULTI_FIELDS`` can be\n used to set fields which should be detected as ``is_multiple=True`` even when\n the attribute is not set.\n\nSee docs on \"Multi-Field Detection\" for more details.\n\n7.0.1 (2020-12-14)\n******************\n\nBug fixes:\n\n* Fix `DelimitedList` and `DelimitedTuple` to pass additional keyword arguments\n through their `_serialize` methods to the child fields and fix type checking\n on these classes. (:issue:`569`)\n Thanks to :user:`decaz` for reporting.\n\n7.0.0 (2020-12-10)\n******************\n\nChanges:\n\n* *Backwards-incompatible*: Drop support for webapp2 (:pr:`565`).\n\n* Add type annotations to `Parser` class, `DelimitedList`, and\n `DelimitedTuple`. (:issue:`566`)\n\n7.0.0b2 (2020-12-01)\n********************\n\nFeatures:\n\n* `DjangoParser` now supports the `headers` location. (:issue:`540`)\n\n* `FalconParser` now supports a new `media` location, which uses\n Falcon's `media` decoding. (:issue:`253`)\n\n`media` behaves very similarly to the `json` location but also supports any\nregistered media handler. See the\n`Falcon documentation on media types\n`_ for more details.\n\nChanges:\n\n* `FalconParser` defaults to the `media` location instead of `json`. (:issue:`253`)\n* Test against Python 3.9 (:pr:`552`).\n* *Backwards-incompatible*: Drop support for Python 3.5 (:pr:`553`).\n\n7.0.0b1 (2020-09-11)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: Remove support for marshmallow2 (:issue:`539`)\n\n* *Backwards-incompatible*: Remove `dict2schema`\n\n Users desiring the `dict2schema` functionality may now rely upon\n `marshmallow.Schema.from_dict`. Rewrite any code using `dict2schema` like so:\n\n.. code-block:: python\n\n import marshmallow as ma\n\n # webargs 6.x and older\n from webargs import dict2schema\n\n myschema = dict2schema({\"q1\", ma.fields.Int()})\n\n # webargs 7.x\n myschema = ma.Schema.from_dict({\"q1\", ma.fields.Int()})\n\nFeatures:\n\n* Add ``unknown`` as a parameter to ``Parser.parse``, ``Parser.use_args``,\n ``Parser.use_kwargs``, and parser instantiation. When set, it will be passed\n to ``Schema.load``. When not set, the value passed will depend on the parser's\n settings. If set to ``None``, the schema's default behavior will be used (i.e.\n no value is passed to ``Schema.load``) and parser settings will be ignored.\n\nThis allows usages like\n\n.. code-block:: python\n\n import marshmallow as ma\n\n\n @parser.use_kwargs(\n {\"q1\": ma.fields.Int(), \"q2\": ma.fields.Int()}, location=\"query\", unknown=ma.EXCLUDE\n )\n def foo(q1, q2):\n ...\n\n* Defaults for ``unknown`` may be customized on parser classes via\n ``Parser.DEFAULT_UNKNOWN_BY_LOCATION``, which maps location names to values\n to use.\n\nUsages are varied, but include\n\n.. code-block:: python\n\n import marshmallow as ma\n from webargs.flaskparser import FlaskParser\n\n # as well as...\n class MyParser(FlaskParser):\n DEFAULT_UNKNOWN_BY_LOCATION = {\"query\": ma.INCLUDE}\n\n\n parser = MyParser()\n\nSetting the ``unknown`` value for a Parser instance has higher precedence. So\n\n.. code-block:: python\n\n parser = MyParser(unknown=ma.RAISE)\n\nwill always pass ``RAISE``, even when the location is ``query``.\n\n* By default, webargs will pass ``unknown=EXCLUDE`` for all locations except\n for request bodies (``json``, ``form``, and ``json_or_form``) and path\n parameters. Request bodies and path parameters will pass ``unknown=RAISE``.\n This behavior is defined by the default value for\n ``DEFAULT_UNKNOWN_BY_LOCATION``.\n\nChanges:\n\n* Registered `error_handler` callbacks are required to raise an exception.\n If a handler is invoked and no exception is raised, `webargs` will raise\n a `ValueError` (:issue:`527`)\n\n6.1.1 (2020-09-08)\n******************\n\nBug fixes:\n\n* Failure to validate flask headers would produce error data which contained\n tuples as keys, and was therefore not JSON-serializable. (:issue:`500`)\n These errors will now extract the headername as the key correctly.\n Thanks to :user:`shughes-uk` for reporting.\n\n6.1.0 (2020-04-05)\n******************\n\nFeatures:\n\n* Add ``fields.DelimitedTuple`` when using marshmallow 3. This behaves as a\n combination of ``fields.DelimitedList`` and ``marshmallow.fields.Tuple``. It\n takes an iterable of fields, plus a delimiter (defaults to ``,``), and parses\n delimiter-separated strings into tuples. (:pr:`509`)\n\n* Add ``__str__`` and ``__repr__`` to MultiDictProxy to make it easier to work\n with (:pr:`488`)\n\nSupport:\n\n* Various docs updates (:pr:`482`, :pr:`486`, :pr:`489`, :pr:`498`, :pr:`508`).\n Thanks :user:`lefterisjp`, :user:`timgates42`, and :user:`ugultopu` for the PRs.\n\n\n6.0.0 (2020-02-27)\n******************\n\nFeatures:\n\n* ``FalconParser``: Pass request content length to ``req.stream.read`` to\n provide compatibility with ``falcon.testing`` (:pr:`477`).\n Thanks :user:`suola` for the PR.\n\n* *Backwards-incompatible*: Factorize the ``use_args`` / ``use_kwargs`` branch\n in all parsers. When ``as_kwargs`` is ``False``, arguments are now\n consistently appended to the arguments list by the ``use_args`` decorator.\n Before this change, the ``PyramidParser`` would prepend the argument list on\n each call to ``use_args``. Pyramid view functions must reverse the order of\n their arguments. (:pr:`478`)\n\n6.0.0b8 (2020-02-16)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: Use keyword-only arguments (:pr:`472`).\n\n6.0.0b7 (2020-02-14)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: webargs will rewrite the error messages in\n ValidationErrors to be namespaced under the location which raised the error.\n The `messages` field on errors will therefore be one layer deeper with a\n single top-level key.\n\n6.0.0b6 (2020-01-31)\n********************\n\nRefactoring:\n\n* Remove the cache attached to webargs parsers. Due to changes between webargs\n v5 and v6, the cache is no longer considered useful.\n\nOther changes:\n\n* Import ``Mapping`` from ``collections.abc`` in pyramidparser.py (:pr:`471`).\n Thanks :user:`tirkarthi` for the PR.\n\n6.0.0b5 (2020-01-30)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: `DelimitedList` now requires that its input be a\n string and always serializes as a string. It can still serialize and deserialize\n using another field, e.g. `DelimitedList(Int())` is still valid and requires\n that the values in the list parse as ints.\n\n6.0.0b4 (2020-01-28)\n********************\n\nBug fixes:\n\n* :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched\n (bugfix from 5.5.3).\n\n6.0.0b3 (2020-01-21)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: Support Falcon 2.0. Drop support for Falcon 1.x\n (:pr:`459`). Thanks :user:`dodumosu` and :user:`Nateyo` for the PR.\n\n6.0.0b2 (2020-01-07)\n********************\n\nOther changes:\n\n* *Backwards-incompatible*: Drop support for Python 2 (:issue:`440`).\n Thanks :user:`hugovk` for the PR.\n\n6.0.0b1 (2020-01-06)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: Schemas will now load all data from a location, not\n only data specified by fields. As a result, schemas with validators which\n examine the full input data may change in behavior. The `unknown` parameter\n on schemas may be used to alter this. For example,\n `unknown=marshmallow.EXCLUDE` will produce a behavior similar to webargs v5.\n\nBug fixes:\n\n* *Backwards-incompatible*: All parsers now require the Content-Type to be set\n correctly when processing JSON request bodies. This impacts ``DjangoParser``,\n ``FalconParser``, ``FlaskParser``, and ``PyramidParser``\n\nRefactoring:\n\n* *Backwards-incompatible*: Schema fields may not specify a location any\n longer, and `Parser.use_args` and `Parser.use_kwargs` now accept `location`\n (singular) instead of `locations` (plural). Instead of using a single field or\n schema with multiple `locations`, users are recommended to make multiple\n calls to `use_args` or `use_kwargs` with a distinct schema per location. For\n example, code should be rewritten like this:\n\n.. code-block:: python\n\n # webargs 5.x and older\n @parser.use_args(\n {\n \"q1\": ma.fields.Int(location=\"query\"),\n \"q2\": ma.fields.Int(location=\"query\"),\n \"h1\": ma.fields.Int(location=\"headers\"),\n },\n locations=(\"query\", \"headers\"),\n )\n def foo(q1, q2, h1):\n ...\n\n\n # webargs 6.x\n @parser.use_args({\"q1\": ma.fields.Int(), \"q2\": ma.fields.Int()}, location=\"query\")\n @parser.use_args({\"h1\": ma.fields.Int()}, location=\"headers\")\n def foo(q1, q2, h1):\n ...\n\n* The `location_handler` decorator has been removed and replaced with\n `location_loader`. `location_loader` serves the same purpose (letting you\n write custom hooks for loading data) but its expected method signature is\n different. See the docs on `location_loader` for proper usage.\n\nThanks :user:`sirosen` for the PR!\n\n5.5.3 (2020-01-28)\n******************\n\nBug fixes:\n\n* :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched.\n\n5.5.2 (2019-10-06)\n******************\n\nBug fixes:\n\n* Handle ``UnicodeDecodeError`` when parsing JSON payloads (:issue:`427`).\n Thanks :user:`lindycoder` for the catch and patch.\n\n5.5.1 (2019-09-15)\n******************\n\nBug fixes:\n\n* Remove usage of deprecated ``Field.fail`` when using marshmallow 3.\n\n5.5.0 (2019-09-07)\n******************\n\nSupport:\n\n* Various docs updates (:pr:`414`, :pr:`421`).\n\nRefactoring:\n\n* Don't mutate ``globals()`` in ``webargs.fields`` (:pr:`411`).\n* Use marshmallow 3's ``Schema.from_dict`` if available (:pr:`415`).\n\n5.4.0 (2019-07-23)\n******************\n\nChanges:\n\n* Use explicit type check for `fields.DelimitedList` when deciding to\n parse value with `getlist()` (`#406 (comment) `_ ).\n\nSupport:\n\n* Add \"Parsing Lists in Query Strings\" section to docs (:issue:`406`).\n\n5.3.2 (2019-06-19)\n******************\n\nBug fixes:\n\n* marshmallow 3.0.0rc7 compatibility (:pr:`395`).\n\n5.3.1 (2019-05-05)\n******************\n\nBug fixes:\n\n* marshmallow 3.0.0rc6 compatibility (:pr:`384`).\n\n5.3.0 (2019-04-08)\n******************\n\nFeatures:\n\n* Add `\"path\"` location to ``AIOHTTPParser``, ``FlaskParser``, and\n ``PyramidParser`` (:pr:`379`). Thanks :user:`zhenhua32` for the PR.\n* Add ``webargs.__version_info__``.\n\n5.2.0 (2019-03-16)\n******************\n\nFeatures:\n\n* Make the schema class used when generating a schema from a\n dict overridable (:issue:`375`). Thanks :user:`ThiefMaster`.\n\n5.1.3 (2019-03-11)\n******************\n\nBug fixes:\n\n* :cve:`CVE-2019-9710`: Fix race condition between parallel requests when the cache is used\n (:issue:`371`). Thanks :user:`ThiefMaster` for reporting and fixing.\n\n5.1.2 (2019-02-03)\n******************\n\nBug fixes:\n\n* Remove lingering usages of ``ValidationError.status_code``\n (:issue:`365`). Thanks :user:`decaz` for reporting.\n* Avoid ``AttributeError`` on Python<3.5.4 (:issue:`366`).\n* Fix incorrect type annotations for ``error_headers``.\n* Fix outdated docs (:issue:`367`). Thanks :user:`alexandersoto` for reporting.\n\n5.1.1.post0 (2019-01-30)\n************************\n\n* Include LICENSE in sdist (:issue:`364`).\n\n5.1.1 (2019-01-28)\n******************\n\nBug fixes:\n\n* Fix installing ``simplejson`` on Python 2 by\n distributing a Python 2-only wheel (:issue:`363`).\n\n5.1.0 (2019-01-11)\n******************\n\nFeatures:\n\n* Error handlers for `AsyncParser` classes may be coroutine functions.\n* Add type annotations to `AsyncParser` and `AIOHTTPParser`.\n\nBug fixes:\n\n* Fix compatibility with Flask<1.0 (:issue:`355`).\n Thanks :user:`hoatle` for reporting.\n* Address warning on Python 3.7 about importing from ``collections.abc``.\n\n5.0.0 (2019-01-03)\n******************\n\nFeatures:\n\n* *Backwards-incompatible*: A 400 HTTPError is raised when an\n invalid JSON payload is passed. (:issue:`329`).\n Thanks :user:`zedrdave` for reporting.\n\nOther changes:\n\n* *Backwards-incompatible*: `webargs.argmap2schema` is removed. Use\n `webargs.dict2schema` instead.\n* *Backwards-incompatible*: `webargs.ValidationError` is removed.\n Use `marshmallow.ValidationError` instead.\n\n\n.. code-block:: python\n\n # <5.0.0\n from webargs import ValidationError\n\n\n def auth_validator(value):\n # ...\n raise ValidationError(\"Authentication failed\", status_code=401)\n\n\n @use_args({\"auth\": fields.Field(validate=auth_validator)})\n def auth_view(args):\n return jsonify(args)\n\n\n # >=5.0.0\n from marshmallow import ValidationError\n\n\n def auth_validator(value):\n # ...\n raise ValidationError(\"Authentication failed\")\n\n\n @use_args({\"auth\": fields.Field(validate=auth_validator)}, error_status_code=401)\n def auth_view(args):\n return jsonify(args)\n\n\n* *Backwards-incompatible*: Missing arguments will no longer be filled\n in when using ``@use_kwargs`` (:issue:`342,307,252`). Use ``**kwargs``\n to account for non-required fields.\n\n.. code-block:: python\n\n # <5.0.0\n @use_kwargs(\n {\"first_name\": fields.Str(required=True), \"last_name\": fields.Str(required=False)}\n )\n def myview(first_name, last_name):\n # last_name is webargs.missing if it's missing from the request\n return {\"first_name\": first_name}\n\n\n # >=5.0.0\n @use_kwargs(\n {\"first_name\": fields.Str(required=True), \"last_name\": fields.Str(required=False)}\n )\n def myview(first_name, **kwargs):\n # last_name will not be in kwargs if it's missing from the request\n return {\"first_name\": first_name}\n\n\n* `simplejson `_ is now a required\n dependency on Python 2 (:pr:`334`).\n This ensures consistency of behavior across Python 2 and 3.\n\n4.4.1 (2018-01-03)\n******************\n\nBug fixes:\n\n* Remove usages of ``argmap2schema`` from ``fields.Nested``,\n ``AsyncParser``, and ``PyramidParser``.\n\n4.4.0 (2019-01-03)\n******************\n\n* *Deprecation*: ``argmap2schema`` is deprecated in favor of\n ``dict2schema`` (:pr:`352`).\n\n4.3.1 (2018-12-31)\n******************\n\n* Add ``force_all`` param to ``PyramidParser.use_args``.\n* Add warning about missing arguments to ``AsyncParser``.\n\n4.3.0 (2018-12-30)\n******************\n\n* *Deprecation*: Add warning about missing arguments getting added\n to parsed arguments dictionary (:issue:`342`). This behavior will be\n removed in version 5.0.0.\n\n4.2.0 (2018-12-27)\n******************\n\nFeatures:\n\n* Add ``force_all`` argument to ``use_args`` and ``use_kwargs``\n (:issue:`252`, :issue:`307`). Thanks :user:`piroux` for reporting.\n* *Deprecation*: The ``status_code`` and ``headers`` arguments to ``ValidationError``\n are deprecated. Pass ``error_status_code`` and ``error_headers`` to\n `Parser.parse`, `Parser.use_args`, and `Parser.use_kwargs` instead.\n (:issue:`327`, :issue:`336`).\n* Custom error handlers receive ``error_status_code`` and ``error_headers`` arguments.\n (:issue:`327`).\n\n.. code-block:: python\n\n # <4.2.0\n @parser.error_handler\n def handle_error(error, req, schema):\n raise CustomError(error.messages)\n\n\n class MyParser(FlaskParser):\n def handle_error(self, error, req, schema):\n # ...\n raise CustomError(error.messages)\n\n\n # >=4.2.0\n @parser.error_handler\n def handle_error(error, req, schema, status_code, headers):\n raise CustomError(error.messages)\n\n\n # OR\n\n\n @parser.error_handler\n\n... [truncated 22251 chars]\n\n```\n\n### docs/advanced.rst\n```python\nAdvanced Usage\n==============\n\nThis section includes guides for advanced usage patterns.\n\nCustom Location Handlers\n------------------------\n\nTo add your own custom location handler, write a function that receives a request, and a :class:`Schema `, then decorate that function with :func:`Parser.location_loader `.\n\n\n.. code-block:: python\n\n from webargs import fields\n from webargs.flaskparser import parser\n\n\n @parser.location_loader(\"data\")\n def load_data(request, schema):\n return request.data\n\n\n # Now 'data' can be specified as a location\n @parser.use_args({\"per_page\": fields.Int()}, location=\"data\")\n def posts(args):\n return \"displaying {} posts\".format(args[\"per_page\"])\n\n\n.. NOTE::\n\n The schema is passed so that it can be used to wrap multidict types and\n unpack List fields correctly. If you are writing a loader for a multidict\n type, consider looking at\n :class:`MultiDictProxy ` for an\n example of how to do this.\n\n\"meta\" Locations\n~~~~~~~~~~~~~~~~\n\nYou can define your own locations which mix data from several existing\nlocations.\n\nThe `json_or_form` location does this -- first trying to load data as JSON and\nthen falling back to a form body -- and its implementation is quite simple:\n\n\n.. code-block:: python\n\n def load_json_or_form(self, req, schema):\n \"\"\"Load data from a request, accepting either JSON or form-encoded\n data.\n\n The data will first be loaded as JSON, and, if that fails, it will be\n loaded as a form post.\n \"\"\"\n data = self.load_json(req, schema)\n if data is not missing:\n return data\n return self.load_form(req, schema)\n\n\nYou can imagine your own locations with custom behaviors like this.\nFor example, to mix query parameters and form body data, you might write the\nfollowing:\n\n.. code-block:: python\n\n from webargs import fields\n from webargs.multidictproxy import MultiDictProxy\n from webargs.flaskparser import parser\n\n\n @parser.location_loader(\"query_and_form\")\n def load_data(request, schema):\n # relies on the Flask (werkzeug) MultiDict type's implementation of\n # these methods, but when you're extending webargs, you may know things\n # about your framework of choice\n newdata = request.args.copy()\n newdata.update(request.form)\n return MultiDictProxy(newdata, schema)\n\n\n # Now 'query_and_form' means you can send these values in either location,\n # and they will be *mixed* together into a new dict to pass to your schema\n @parser.use_args({\"favorite_food\": fields.String()}, location=\"query_and_form\")\n def set_favorite_food(args):\n ... # do stuff\n return \"your favorite food is now set to {}\".format(args[\"favorite_food\"])\n\nmarshmallow Integration\n-----------------------\n\nWhen you need more flexibility in defining input schemas, you can pass a marshmallow `Schema ` instead of a dictionary to `Parser.parse `, `Parser.use_args `, and `Parser.use_kwargs `.\n\n\n.. code-block:: python\n\n from marshmallow import Schema, fields\n from webargs.flaskparser import use_args\n\n\n class UserSchema(Schema):\n id = fields.Int(dump_only=True) # read-only (won't be parsed by webargs)\n username = fields.Str(required=True)\n password = fields.Str(load_only=True) # write-only\n first_name = fields.Str(missing=\"\")\n last_name = fields.Str(missing=\"\")\n date_registered = fields.DateTime(dump_only=True)\n\n\n @use_args(UserSchema())\n def profile_view(args):\n username = args[\"username\"]\n # ...\n\n\n @use_kwargs(UserSchema())\n def profile_update(username, password, first_name, last_name):\n update_profile(username, password, first_name, last_name)\n # ...\n\n\n # You can add additional parameters\n @use_kwargs({\"posts_per_page\": fields.Int(missing=10)}, location=\"query\")\n @use_args(UserSchema())\n def profile_posts(args, posts_per_page):\n username = args[\"username\"]\n # ...\n\n.. _advanced_setting_unknown:\n\nSetting `unknown`\n-----------------\n\nwebargs supports several ways of setting and passing the `unknown` parameter\nfor `handling unknown fields `_.\n\nYou can pass `unknown=...` as a parameter to any of\n`Parser.parse `,\n`Parser.use_args `, and\n`Parser.use_kwargs `.\n\n\n.. note::\n\n The `unknown` value is passed to the schema's `load()` call. It therefore\n only applies to the top layer when nesting is used. To control `unknown` at\n multiple layers of a nested schema, you must use other mechanisms, like\n the `unknown` argument to `fields.Nested`.\n\nDefault `unknown`\n+++++++++++++++++\n\nBy default, webargs will pass `unknown=marshmallow.EXCLUDE` except when the\nlocation is `json`, `form`, `json_or_form`, or `path`. In those cases, it uses\n`unknown=marshmallow.RAISE` instead.\n\nYou can change these defaults by overriding `DEFAULT_UNKNOWN_BY_LOCATION`.\nThis is a mapping of locations to values to pass.\n\nFor example,\n\n.. code-block:: python\n\n from flask import Flask\n from marshmallow import EXCLUDE, fields\n from webargs.flaskparser import FlaskParser\n\n app = Flask(__name__)\n\n\n class Parser(FlaskParser):\n DEFAULT_UNKNOWN_BY_LOCATION = {\"query\": EXCLUDE}\n\n\n parser = Parser()\n\n\n # location is \"query\", which is listed in DEFAULT_UNKNOWN_BY_LOCATION,\n # so EXCLUDE will be used\n @app.route(\"/\", methods=[\"GET\"])\n @parser.use_args({\"foo\": fields.Int()}, location=\"query\")\n def get(args):\n return f\"foo x 2 = {args['foo'] * 2}\"\n\n\n # location is \"json\", which is not in DEFAULT_UNKNOWN_BY_LOCATION,\n # so no value will be passed for `unknown`\n @app.route(\"/\", methods=[\"POST\"])\n @parser.use_args({\"foo\": fields.Int(), \"bar\": fields.Int()}, location=\"json\")\n def post(args):\n return f\"foo x bar = {args['foo'] * args['bar']}\"\n\n\nYou can also define a default at parser instantiation, which will take\nprecedence over these defaults, as in\n\n.. code-block:: python\n\n from marshmallow import INCLUDE\n\n parser = Parser(unknown=INCLUDE)\n\n # because `unknown` is set on the parser, `DEFAULT_UNKNOWN_BY_LOCATION` has\n # effect and `INCLUDE` will always be used\n @app.route(\"/\", methods=[\"POST\"])\n @parser.use_args({\"foo\": fields.Int(), \"bar\": fields.Int()}, location=\"json\")\n def post(args):\n unexpected_args = [k for k in args.keys() if k not in (\"foo\", \"bar\")]\n return f\"foo x bar = {args['foo'] * args['bar']}; unexpected args={unexpected_args}\"\n\nUsing Schema-Specfied `unknown`\n+++++++++++++++++++++++++++++++\n\nIf you wish to use the value of `unknown` specified by a schema, simply pass\n``unknown=None``. This will disable webargs' automatic passing of values for\n``unknown``. For example,\n\n.. code-block:: python\n\n from flask import Flask\n from marshmallow import Schema, fields, EXCLUDE, missing\n from webargs.flaskparser import use_args\n\n\n class RectangleSchema(Schema):\n length = fields.Float()\n width = fields.Float()\n\n class Meta:\n unknown = EXCLUDE\n\n\n app = Flask(__name__)\n\n # because unknown=None was passed, no value is passed during schema loading\n # as a result, the schema's behavior (EXCLUDE) is used\n @app.route(\"/\", methods=[\"POST\"])\n @use_args(RectangleSchema(), location=\"json\", unknown=None)\n def get(args):\n return f\"area = {args['length'] * args['width']}\"\n\n\nYou can also set ``unknown=None`` when instantiating a parser to make this\nbehavior the default for a parser.\n\n\nWhen to avoid `use_kwargs`\n--------------------------\n\nAny `Schema ` passed to `use_kwargs ` MUST deserialize to a dictionary of data.\nIf your schema has a `post_load ` method \nthat returns a non-dictionary,\nyou should use `use_args ` instead.\n\n.. code-block:: python\n\n from marshmallow import Schema, fields, post_load\n from webargs.flaskparser import use_args\n\n\n class Rectangle:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n\n\n class RectangleSchema(Schema):\n length = fields.Float()\n width = fields.Float()\n\n @post_load\n def make_object(self, data, **kwargs):\n return Rectangle(**data)\n\n\n @use_args(RectangleSchema)\n def post(rect: Rectangle):\n return f\"Area: {rect.length * rect.width}\"\n\nPackages such as `marshmallow-sqlalchemy `_ and `marshmallow-dataclass `_ generate schemas that deserialize to non-dictionary objects.\nTherefore, `use_args ` should be used with those schemas.\n\n\nSchema Factories\n----------------\n\nIf you need to parametrize a schema based on a given request, you can use a \"Schema factory\": a callable that receives the current `request` and returns a `marshmallow.Schema` instance.\n\nConsider the following use cases:\n\n- Filtering via a query parameter by passing ``only`` to the Schema.\n- Handle partial updates for PATCH requests using marshmallow's `partial loading `_ API.\n\n.. code-block:: python\n\n from flask import Flask\n from marshmallow import Schema, fields\n from webargs.flaskparser import use_args\n\n app = Flask(__name__)\n\n\n class UserSchema(Schema):\n id = fields.Int(dump_only=True)\n username = fields.Str(required=True)\n password = fields.Str(load_only=True)\n first_name = fields.Str(missing=\"\")\n last_name = fields.Str(missing=\"\")\n date_registered = fields.DateTime(dump_only=True)\n\n\n def make_user_schema(request):\n # Filter based on 'fields' query parameter\n fields = request.args.get(\"fields\", None)\n only = fields.split(\",\") if fields else None\n # Respect partial updates for PATCH requests\n partial = request.method == \"PATCH\"\n # Add current request to the schema's context\n return UserSchema(only=only, partial=partial, context={\"request\": request})\n\n\n # Pass the factory to .parse, .use_args, or .use_kwargs\n @app.route(\"/profile/\", methods=[\"GET\", \"POST\", \"PATCH\"])\n @use_args(make_user_schema)\n def profile_view(args):\n username = args.get(\"username\")\n # ...\n\n\n\nReducing Boilerplate\n++++++++++++++++++++\n\nWe can reduce boilerplate and improve [re]usability with a simple helper function:\n\n.. code-block:: python\n\n from webargs.flaskparser import use_args\n\n\n def use_args_with(schema_cls, schema_kwargs=None, **kwargs):\n schema_kwargs = schema_kwargs or {}\n\n def factory(request):\n # Filter based on 'fields' query parameter\n only = request.args.get(\"fields\", None)\n # Respect partial updates for PATCH requests\n partial = request.method == \"PATCH\"\n return schema_cls(\n only=only, partial=partial, context={\"request\": request}, **schema_kwargs\n )\n\n return use_args(factory, **kwargs)\n\n\nNow we can attach input schemas to our view functions like so:\n\n.. code-block:: python\n\n @use_args_with(UserSchema)\n def profile_view(args):\n # ...\n get_profile(**args)\n\n\nCustom Fields\n-------------\n\nSee the \"Custom Fields\" section of the marshmallow docs for a detailed guide on defining custom fields which you can pass to webargs parsers: https://marshmallow.readthedocs.io/en/latest/custom_fields.html.\n\nUsing ``Method`` and ``Function`` Fields with webargs\n+++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nUsing the :class:`Method ` and :class:`Function ` fields requires that you pass the ``deserialize`` parameter.\n\n\n.. code-block:: python\n\n @use_args({\"cube\": fields.Function(deserialize=lambda x: int(x) ** 3)})\n def math_view(args):\n cube = args[\"cube\"]\n # ...\n\n.. _custom-loaders:\n\nCustom Parsers\n--------------\n\nTo add your own parser, extend :class:`Parser ` and implement the `load_*` method(s) you need to override. For example, here is a custom Flask parser that handles nested query string arguments.\n\n\n.. code-block:: python\n\n import re\n\n from webargs import core\n from webargs.flaskparser import FlaskParser\n\n\n class NestedQueryFlaskParser(FlaskParser):\n \"\"\"Parses nested query args\n\n This parser handles nested query args. It expects nested levels\n delimited by a period and then deserializes the query args into a\n nested dict.\n\n For example, the URL query params `?name.first=John&name.last=Boone`\n will yield the following dict:\n\n {\n 'name': {\n 'first': 'John',\n 'last': 'Boone',\n }\n }\n \"\"\"\n\n def load_querystring(self, req, schema):\n return _structure_dict(req.args)\n\n\n def _structure_dict(dict_):\n def structure_dict_pair(r, key, value):\n m = re.match(r\"(\\w+)\\.(.*)\", key)\n if m:\n if r.get(m.group(1)) is None:\n r[m.group(1)] = {}\n structure_dict_pair(r[m.group(1)], m.group(2), value)\n else:\n r[key] = value\n\n r = {}\n for k, v in dict_.items():\n structure_dict_pair(r, k, v)\n return r\n\nReturning HTTP 400 Responses\n----------------------------\n\nIf you'd prefer validation errors to return status code ``400`` instead\nof ``422``, you can override ``DEFAULT_VALIDATION_STATUS`` on a :class:`Parser `.\n\nSublcass the parser for your framework to do so. For example, using Falcon:\n\n.. code-block:: python\n\n from webargs.falconparser import FalconParser\n\n\n class Parser(FalconParser):\n DEFAULT_VALIDATION_STATUS = 400\n\n\n parser = Parser()\n use_args = parser.use_args\n use_kwargs = parser.use_kwargs\n\nBulk-type Arguments\n-------------------\n\nIn order to parse a JSON array of objects, pass ``many=True`` to your input ``Schema`` .\n\nFor example, you might implement JSON PATCH according to `RFC 6902 `_ like so:\n\n\n.. code-block:: python\n\n from webargs import fields\n from webargs.flaskparser import use_args\n from marshmallow import Schema, validate\n\n\n class PatchSchema(Schema):\n op = fields.Str(\n required=True,\n validate=validate.OneOf([\"add\", \"remove\", \"replace\", \"move\", \"copy\"]),\n )\n path = fields.Str(required=True)\n value = fields.Str(required=True)\n\n\n @app.route(\"/profile/\", methods=[\"patch\"])\n @use_args(PatchSchema(many=True))\n def patch_blog(args):\n \"\"\"Implements JSON Patch for the user profile\n\n Example JSON body:\n\n [\n {\"op\": \"replace\", \"path\": \"/email\", \"value\": \"mynewemail@test.org\"}\n ]\n \"\"\"\n # ...\n\nMulti-Field Detection\n---------------------\n\nIf a ``List`` field is used to parse data from a location like query parameters --\nwhere one or multiple values can be passed for a single parameter name -- then\nwebargs will automatically treat that field as a list and parse multiple values\nif present.\n\nTo implement this behavior, webargs will examine schemas for ``marshmallow.fields.List``\nfields. ``List`` fields get unpacked to list values when data is loaded, and\nother fields do not. This also applies to fields which inherit from ``List``.\n\n.. note::\n\n In webargs v8, ``Tuple`` will be treated this wa\n... [truncated 3609 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "marshmallow-code__webargs-353f49683261", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/marshmallow-code__webargs-353f49683261", "repo_key": "marshmallow-code__webargs", "repo": "marshmallow-code/webargs", "base_commit": "f953dff5c77b5eeb96046aef4a29fd9d097085c3", "source_files": ["CHANGELOG.rst", "docs/advanced.rst", "src/webargs/core.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Multi-dict unpacking incorrectly handles custom fields for multiple values\n\n## Description\nWhen unpacking data from a multi-dict, the system does not correctly determine if certain fields should be treated as multiple values. Custom field types that logically represent multiple values are not detected as such, leading to incorrect data handling. Additionally, subclasses of `List` fields cannot easily override the default behavior to be treated as a single value, even when their implementation dictates it (e.g., a delimited string that should be parsed as one item).\n\nExpected behavior: Users should be able to explicitly define whether a field is treated as multiple values during multi-dict unpacking.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `d4fbbb7e7064` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.rst\n```python\nChangelog\n---------\n\n7.0.1 (2020-12-14)\n******************\n\nBug fixes:\n\n* Fix `DelimitedList` and `DelimitedTuple` to pass additional keyword arguments\n through their `_serialize` methods to the child fields and fix type checking\n on these classes. (:issue:`569`)\n Thanks to :user:`decaz` for reporting.\n\n7.0.0 (2020-12-10)\n******************\n\nChanges:\n\n* *Backwards-incompatible*: Drop support for webapp2 (:pr:`565`).\n\n* Add type annotations to `Parser` class, `DelimitedList`, and\n `DelimitedTuple`. (:issue:`566`)\n\n7.0.0b2 (2020-12-01)\n********************\n\nFeatures:\n\n* `DjangoParser` now supports the `headers` location. (:issue:`540`)\n\n* `FalconParser` now supports a new `media` location, which uses\n Falcon's `media` decoding. (:issue:`253`)\n\n`media` behaves very similarly to the `json` location but also supports any\nregistered media handler. See the\n`Falcon documentation on media types\n`_ for more details.\n\nChanges:\n\n* `FalconParser` defaults to the `media` location instead of `json`. (:issue:`253`)\n* Test against Python 3.9 (:pr:`552`).\n* *Backwards-incompatible*: Drop support for Python 3.5 (:pr:`553`).\n\n7.0.0b1 (2020-09-11)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: Remove support for marshmallow2 (:issue:`539`)\n\n* *Backwards-incompatible*: Remove `dict2schema`\n\n Users desiring the `dict2schema` functionality may now rely upon\n `marshmallow.Schema.from_dict`. Rewrite any code using `dict2schema` like so:\n\n.. code-block:: python\n\n import marshmallow as ma\n\n # webargs 6.x and older\n from webargs import dict2schema\n\n myschema = dict2schema({\"q1\", ma.fields.Int()})\n\n # webargs 7.x\n myschema = ma.Schema.from_dict({\"q1\", ma.fields.Int()})\n\nFeatures:\n\n* Add ``unknown`` as a parameter to ``Parser.parse``, ``Parser.use_args``,\n ``Parser.use_kwargs``, and parser instantiation. When set, it will be passed\n to ``Schema.load``. When not set, the value passed will depend on the parser's\n settings. If set to ``None``, the schema's default behavior will be used (i.e.\n no value is passed to ``Schema.load``) and parser settings will be ignored.\n\nThis allows usages like\n\n.. code-block:: python\n\n import marshmallow as ma\n\n\n @parser.use_kwargs(\n {\"q1\": ma.fields.Int(), \"q2\": ma.fields.Int()}, location=\"query\", unknown=ma.EXCLUDE\n )\n def foo(q1, q2):\n ...\n\n* Defaults for ``unknown`` may be customized on parser classes via\n ``Parser.DEFAULT_UNKNOWN_BY_LOCATION``, which maps location names to values\n to use.\n\nUsages are varied, but include\n\n.. code-block:: python\n\n import marshmallow as ma\n from webargs.flaskparser import FlaskParser\n\n # as well as...\n class MyParser(FlaskParser):\n DEFAULT_UNKNOWN_BY_LOCATION = {\"query\": ma.INCLUDE}\n\n\n parser = MyParser()\n\nSetting the ``unknown`` value for a Parser instance has higher precedence. So\n\n.. code-block:: python\n\n parser = MyParser(unknown=ma.RAISE)\n\nwill always pass ``RAISE``, even when the location is ``query``.\n\n* By default, webargs will pass ``unknown=EXCLUDE`` for all locations except\n for request bodies (``json``, ``form``, and ``json_or_form``) and path\n parameters. Request bodies and path parameters will pass ``unknown=RAISE``.\n This behavior is defined by the default value for\n ``DEFAULT_UNKNOWN_BY_LOCATION``.\n\nChanges:\n\n* Registered `error_handler` callbacks are required to raise an exception.\n If a handler is invoked and no exception is raised, `webargs` will raise\n a `ValueError` (:issue:`527`)\n\n6.1.1 (2020-09-08)\n******************\n\nBug fixes:\n\n* Failure to validate flask headers would produce error data which contained\n tuples as keys, and was therefore not JSON-serializable. (:issue:`500`)\n These errors will now extract the headername as the key correctly.\n Thanks to :user:`shughes-uk` for reporting.\n\n6.1.0 (2020-04-05)\n******************\n\nFeatures:\n\n* Add ``fields.DelimitedTuple`` when using marshmallow 3. This behaves as a\n combination of ``fields.DelimitedList`` and ``marshmallow.fields.Tuple``. It\n takes an iterable of fields, plus a delimiter (defaults to ``,``), and parses\n delimiter-separated strings into tuples. (:pr:`509`)\n\n* Add ``__str__`` and ``__repr__`` to MultiDictProxy to make it easier to work\n with (:pr:`488`)\n\nSupport:\n\n* Various docs updates (:pr:`482`, :pr:`486`, :pr:`489`, :pr:`498`, :pr:`508`).\n Thanks :user:`lefterisjp`, :user:`timgates42`, and :user:`ugultopu` for the PRs.\n\n\n6.0.0 (2020-02-27)\n******************\n\nFeatures:\n\n* ``FalconParser``: Pass request content length to ``req.stream.read`` to\n provide compatibility with ``falcon.testing`` (:pr:`477`).\n Thanks :user:`suola` for the PR.\n\n* *Backwards-incompatible*: Factorize the ``use_args`` / ``use_kwargs`` branch\n in all parsers. When ``as_kwargs`` is ``False``, arguments are now\n consistently appended to the arguments list by the ``use_args`` decorator.\n Before this change, the ``PyramidParser`` would prepend the argument list on\n each call to ``use_args``. Pyramid view functions must reverse the order of\n their arguments. (:pr:`478`)\n\n6.0.0b8 (2020-02-16)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: Use keyword-only arguments (:pr:`472`).\n\n6.0.0b7 (2020-02-14)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: webargs will rewrite the error messages in\n ValidationErrors to be namespaced under the location which raised the error.\n The `messages` field on errors will therefore be one layer deeper with a\n single top-level key.\n\n6.0.0b6 (2020-01-31)\n********************\n\nRefactoring:\n\n* Remove the cache attached to webargs parsers. Due to changes between webargs\n v5 and v6, the cache is no longer considered useful.\n\nOther changes:\n\n* Import ``Mapping`` from ``collections.abc`` in pyramidparser.py (:pr:`471`).\n Thanks :user:`tirkarthi` for the PR.\n\n6.0.0b5 (2020-01-30)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: `DelimitedList` now requires that its input be a\n string and always serializes as a string. It can still serialize and deserialize\n using another field, e.g. `DelimitedList(Int())` is still valid and requires\n that the values in the list parse as ints.\n\n6.0.0b4 (2020-01-28)\n********************\n\nBug fixes:\n\n* :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched\n (bugfix from 5.5.3).\n\n6.0.0b3 (2020-01-21)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: Support Falcon 2.0. Drop support for Falcon 1.x\n (:pr:`459`). Thanks :user:`dodumosu` and :user:`Nateyo` for the PR.\n\n6.0.0b2 (2020-01-07)\n********************\n\nOther changes:\n\n* *Backwards-incompatible*: Drop support for Python 2 (:issue:`440`).\n Thanks :user:`hugovk` for the PR.\n\n6.0.0b1 (2020-01-06)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: Schemas will now load all data from a location, not\n only data specified by fields. As a result, schemas with validators which\n examine the full input data may change in behavior. The `unknown` parameter\n on schemas may be used to alter this. For example,\n `unknown=marshmallow.EXCLUDE` will produce a behavior similar to webargs v5.\n\nBug fixes:\n\n* *Backwards-incompatible*: All parsers now require the Content-Type to be set\n correctly when processing JSON request bodies. This impacts ``DjangoParser``,\n ``FalconParser``, ``FlaskParser``, and ``PyramidParser``\n\nRefactoring:\n\n* *Backwards-incompatible*: Schema fields may not specify a location any\n longer, and `Parser.use_args` and `Parser.use_kwargs` now accept `location`\n (singular) instead of `locations` (plural). Instead of using a single field or\n schema with multiple `locations`, users are recommended to make multiple\n calls to `use_args` or `use_kwargs` with a distinct schema per location. For\n example, code should be rewritten like this:\n\n.. code-block:: python\n\n # webargs 5.x and older\n @parser.use_args(\n {\n \"q1\": ma.fields.Int(location=\"query\"),\n \"q2\": ma.fields.Int(location=\"query\"),\n \"h1\": ma.fields.Int(location=\"headers\"),\n },\n locations=(\"query\", \"headers\"),\n )\n def foo(q1, q2, h1):\n ...\n\n\n # webargs 6.x\n @parser.use_args({\"q1\": ma.fields.Int(), \"q2\": ma.fields.Int()}, location=\"query\")\n @parser.use_args({\"h1\": ma.fields.Int()}, location=\"headers\")\n def foo(q1, q2, h1):\n ...\n\n* The `location_handler` decorator has been removed and replaced with\n `location_loader`. `location_loader` serves the same purpose (letting you\n write custom hooks for loading data) but its expected method signature is\n different. See the docs on `location_loader` for proper usage.\n\nThanks :user:`sirosen` for the PR!\n\n5.5.3 (2020-01-28)\n******************\n\nBug fixes:\n\n* :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched.\n\n5.5.2 (2019-10-06)\n******************\n\nBug fixes:\n\n* Handle ``UnicodeDecodeError`` when parsing JSON payloads (:issue:`427`).\n Thanks :user:`lindycoder` for the catch and patch.\n\n5.5.1 (2019-09-15)\n******************\n\nBug fixes:\n\n* Remove usage of deprecated ``Field.fail`` when using marshmallow 3.\n\n5.5.0 (2019-09-07)\n******************\n\nSupport:\n\n* Various docs updates (:pr:`414`, :pr:`421`).\n\nRefactoring:\n\n* Don't mutate ``globals()`` in ``webargs.fields`` (:pr:`411`).\n* Use marshmallow 3's ``Schema.from_dict`` if available (:pr:`415`).\n\n5.4.0 (2019-07-23)\n******************\n\nChanges:\n\n* Use explicit type check for `fields.DelimitedList` when deciding to\n parse value with `getlist()` (`#406 (comment) `_ ).\n\nSupport:\n\n* Add \"Parsing Lists in Query Strings\" section to docs (:issue:`406`).\n\n5.3.2 (2019-06-19)\n******************\n\nBug fixes:\n\n* marshmallow 3.0.0rc7 compatibility (:pr:`395`).\n\n5.3.1 (2019-05-05)\n******************\n\nBug fixes:\n\n* marshmallow 3.0.0rc6 compatibility (:pr:`384`).\n\n5.3.0 (2019-04-08)\n******************\n\nFeatures:\n\n* Add `\"path\"` location to ``AIOHTTPParser``, ``FlaskParser``, and\n ``PyramidParser`` (:pr:`379`). Thanks :user:`zhenhua32` for the PR.\n* Add ``webargs.__version_info__``.\n\n5.2.0 (2019-03-16)\n******************\n\nFeatures:\n\n* Make the schema class used when generating a schema from a\n dict overridable (:issue:`375`). Thanks :user:`ThiefMaster`.\n\n5.1.3 (2019-03-11)\n******************\n\nBug fixes:\n\n* :cve:`CVE-2019-9710`: Fix race condition between parallel requests when the cache is used\n (:issue:`371`). Thanks :user:`ThiefMaster` for reporting and fixing.\n\n5.1.2 (2019-02-03)\n******************\n\nBug fixes:\n\n* Remove lingering usages of ``ValidationError.status_code``\n (:issue:`365`). Thanks :user:`decaz` for reporting.\n* Avoid ``AttributeError`` on Python<3.5.4 (:issue:`366`).\n* Fix incorrect type annotations for ``error_headers``.\n* Fix outdated docs (:issue:`367`). Thanks :user:`alexandersoto` for reporting.\n\n5.1.1.post0 (2019-01-30)\n************************\n\n* Include LICENSE in sdist (:issue:`364`).\n\n5.1.1 (2019-01-28)\n******************\n\nBug fixes:\n\n* Fix installing ``simplejson`` on Python 2 by\n distributing a Python 2-only wheel (:issue:`363`).\n\n5.1.0 (2019-01-11)\n******************\n\nFeatures:\n\n* Error handlers for `AsyncParser` classes may be coroutine functions.\n* Add type annotations to `AsyncParser` and `AIOHTTPParser`.\n\nBug fixes:\n\n* Fix compatibility with Flask<1.0 (:issue:`355`).\n Thanks :user:`hoatle` for reporting.\n* Address warning on Python 3.7 about importing from ``collections.abc``.\n\n5.0.0 (2019-01-03)\n******************\n\nFeatures:\n\n* *Backwards-incompatible*: A 400 HTTPError is raised when an\n invalid JSON payload is passed. (:issue:`329`).\n Thanks :user:`zedrdave` for reporting.\n\nOther changes:\n\n* *Backwards-incompatible*: `webargs.argmap2schema` is removed. Use\n `webargs.dict2schema` instead.\n* *Backwards-incompatible*: `webargs.ValidationError` is removed.\n Use `marshmallow.ValidationError` instead.\n\n\n.. code-block:: python\n\n # <5.0.0\n from webargs import ValidationError\n\n\n def auth_validator(value):\n # ...\n raise ValidationError(\"Authentication failed\", status_code=401)\n\n\n @use_args({\"auth\": fields.Field(validate=auth_validator)})\n def auth_view(args):\n return jsonify(args)\n\n\n # >=5.0.0\n from marshmallow import ValidationError\n\n\n def auth_validator(value):\n # ...\n raise ValidationError(\"Authentication failed\")\n\n\n @use_args({\"auth\": fields.Field(validate=auth_validator)}, error_status_code=401)\n def auth_view(args):\n return jsonify(args)\n\n\n* *Backwards-incompatible*: Missing arguments will no longer be filled\n in when using ``@use_kwargs`` (:issue:`342,307,252`). Use ``**kwargs``\n to account for non-required fields.\n\n.. code-block:: python\n\n # <5.0.0\n @use_kwargs(\n {\"first_name\": fields.Str(required=True), \"last_name\": fields.Str(required=False)}\n )\n def myview(first_name, last_name):\n # last_name is webargs.missing if it's missing from the request\n return {\"first_name\": first_name}\n\n\n # >=5.0.0\n @use_kwargs(\n {\"first_name\": fields.Str(required=True), \"last_name\": fields.Str(required=False)}\n )\n def myview(first_name, **kwargs):\n # last_name will not be in kwargs if it's missing from the request\n return {\"first_name\": first_name}\n\n\n* `simplejson `_ is now a required\n dependency on Python 2 (:pr:`334`).\n This ensures consistency of behavior across Python 2 and 3.\n\n4.4.1 (2018-01-03)\n******************\n\nBug fixes:\n\n* Remove usages of ``argmap2schema`` from ``fields.Nested``,\n ``AsyncParser``, and ``PyramidParser``.\n\n4.4.0 (2019-01-03)\n******************\n\n* *Deprecation*: ``argmap2schema`` is deprecated in favor of\n ``dict2schema`` (:pr:`352`).\n\n4.3.1 (2018-12-31)\n******************\n\n* Add ``force_all`` param to ``PyramidParser.use_args``.\n* Add warning about missing arguments to ``AsyncParser``.\n\n4.3.0 (2018-12-30)\n******************\n\n* *Deprecation*: Add warning about missing arguments getting added\n to parsed arguments dictionary (:issue:`342`). This behavior will be\n removed in version 5.0.0.\n\n4.2.0 (2018-12-27)\n******************\n\nFeatures:\n\n* Add ``force_all`` argument to ``use_args`` and ``use_kwargs``\n (:issue:`252`, :issue:`307`). Thanks :user:`piroux` for reporting.\n* *Deprecation*: The ``status_code`` and ``headers`` arguments to ``ValidationError``\n are deprecated. Pass ``error_status_code`` and ``error_headers`` to\n `Parser.parse`, `Parser.use_args`, and `Parser.use_kwargs` instead.\n (:issue:`327`, :issue:`336`).\n* Custom error handlers receive ``error_status_code`` and ``error_headers`` arguments.\n (:issue:`327`).\n\n.. code-block:: python\n\n # <4.2.0\n @parser.error_handler\n def handle_error(error, req, schema):\n raise CustomError(error.messages)\n\n\n class MyParser(FlaskParser):\n def handle_error(self, error, req, schema):\n # ...\n raise CustomError(error.messages)\n\n\n # >=4.2.0\n @parser.error_handler\n def handle_error(error, req, schema, status_code, headers):\n raise CustomError(error.messages)\n\n\n # OR\n\n\n @parser.error_handler\n def handle_error(error, **kwargs):\n raise CustomError(error.messages)\n\n\n class MyParser(FlaskParser):\n def handle_error(self, error, req, schema, status_code, headers):\n # ...\n raise CustomError(error.messages)\n\n # OR\n\n def handle_error(self, error, req, **kwargs):\n # ...\n raise CustomError(error.messages)\n\nLegacy error handlers will be supported until version 5.0.0.\n\n4.1.3 (2018-12-02)\n******************\n\nBug fixes:\n\n* Fix bug in ``AIOHTTParser`` that prevented calling\n ``use_args`` on the same view function multiple times (:issue:`273`).\n Thanks to :user:`dnp1` for reporting and :user:`jangelo` for the fix.\n* Fix compatibility with marshmallow 3.0.0rc1 (:pr:`330`).\n\n4.1.2 (2018-\n... [truncated 21481 chars]\n\n```\n\n### src/webargs/core.py\n```python\nimport functools\nimport typing\nimport logging\nfrom collections.abc import Mapping\nimport json\n\nimport marshmallow as ma\nfrom marshmallow import ValidationError\nfrom marshmallow.utils import missing\n\nfrom webargs.fields import DelimitedList\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = [\n \"ValidationError\",\n \"is_multiple\",\n \"Parser\",\n \"missing\",\n \"parse_json\",\n]\n\n\nRequest = typing.TypeVar(\"Request\")\nArgMap = typing.Union[\n ma.Schema,\n typing.Mapping[str, ma.fields.Field],\n typing.Callable[[Request], ma.Schema],\n]\nValidateArg = typing.Union[None, typing.Callable, typing.Iterable[typing.Callable]]\nCallableList = typing.List[typing.Callable]\nErrorHandler = typing.Callable[..., typing.NoReturn]\n# generic type var with no particular meaning\nT = typing.TypeVar(\"T\")\n\n\n# a value used as the default for arguments, so that when `None` is passed, it\n# can be distinguished from the default value\n_UNKNOWN_DEFAULT_PARAM = \"_default\"\n\nDEFAULT_VALIDATION_STATUS: int = 422\n\n\ndef _iscallable(x) -> bool:\n # workaround for\n # https://github.com/python/mypy/issues/9778\n return callable(x)\n\n\ndef _callable_or_raise(obj: typing.Optional[T]) -> typing.Optional[T]:\n \"\"\"Makes sure an object is callable if it is not ``None``. If not\n callable, a ValueError is raised.\n \"\"\"\n if obj and not _iscallable(obj):\n raise ValueError(f\"{obj!r} is not callable.\")\n return obj\n\n\ndef is_multiple(field: ma.fields.Field) -> bool:\n \"\"\"Return whether or not `field` handles repeated/multi-value arguments.\"\"\"\n return isinstance(field, ma.fields.List) and not isinstance(field, DelimitedList)\n\n\ndef get_mimetype(content_type: str) -> str:\n return content_type.split(\";\")[0].strip()\n\n\n# Adapted from werkzeug:\n# https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/wrappers.py\ndef is_json(mimetype: typing.Optional[str]) -> bool:\n \"\"\"Indicates if this mimetype is JSON or not. By default a request\n is considered to include JSON data if the mimetype is\n ``application/json`` or ``application/*+json``.\n \"\"\"\n if not mimetype:\n return False\n if \";\" in mimetype: # Allow Content-Type header to be passed\n mimetype = get_mimetype(mimetype)\n if mimetype == \"application/json\":\n return True\n if mimetype.startswith(\"application/\") and mimetype.endswith(\"+json\"):\n return True\n return False\n\n\ndef parse_json(s: typing.AnyStr, *, encoding: str = \"utf-8\") -> typing.Any:\n if isinstance(s, str):\n decoded = s\n else:\n try:\n decoded = s.decode(encoding)\n except UnicodeDecodeError as exc:\n raise json.JSONDecodeError(\n f\"Bytes decoding error : {exc.reason}\",\n doc=str(exc.object),\n pos=exc.start,\n )\n return json.loads(decoded)\n\n\ndef _ensure_list_of_callables(obj: typing.Any) -> CallableList:\n if obj:\n if isinstance(obj, (list, tuple)):\n validators = typing.cast(CallableList, list(obj))\n elif callable(obj):\n validators = [obj]\n else:\n raise ValueError(f\"{obj!r} is not a callable or list of callables.\")\n else:\n validators = []\n return validators\n\n\nclass Parser:\n \"\"\"Base parser class that provides high-level implementation for parsing\n a request.\n\n Descendant classes must provide lower-level implementations for reading\n data from different locations, e.g. ``load_json``, ``load_querystring``,\n etc.\n\n :param str location: Default location to use for data\n :param str unknown: A default value to pass for ``unknown`` when calling the\n schema's ``load`` method. Defaults to EXCLUDE for non-body\n locations and RAISE for request bodies. Pass ``None`` to use the\n schema's setting instead.\n :param callable error_handler: Custom error handler function.\n \"\"\"\n\n #: Default location to check for data\n DEFAULT_LOCATION: str = \"json\"\n #: Default value to use for 'unknown' on schema load\n # on a per-location basis\n DEFAULT_UNKNOWN_BY_LOCATION: typing.Dict[str, str] = {\n \"json\": ma.RAISE,\n \"form\": ma.RAISE,\n \"json_or_form\": ma.RAISE,\n \"querystring\": ma.EXCLUDE,\n \"query\": ma.EXCLUDE,\n \"headers\": ma.EXCLUDE,\n \"cookies\": ma.EXCLUDE,\n \"files\": ma.EXCLUDE,\n }\n #: The marshmallow Schema class to use when creating new schemas\n DEFAULT_SCHEMA_CLASS: typing.Type = ma.Schema\n #: Default status code to return for validation errors\n DEFAULT_VALIDATION_STATUS: int = DEFAULT_VALIDATION_STATUS\n #: Default error message for validation errors\n DEFAULT_VALIDATION_MESSAGE: str = \"Invalid value.\"\n\n #: Maps location => method name\n __location_map__: typing.Dict[str, typing.Union[str, typing.Callable]] = {\n \"json\": \"load_json\",\n \"querystring\": \"load_querystring\",\n \"query\": \"load_querystring\",\n \"form\": \"load_form\",\n \"headers\": \"load_headers\",\n \"cookies\": \"load_cookies\",\n \"files\": \"load_files\",\n \"json_or_form\": \"load_json_or_form\",\n }\n\n def __init__(\n self,\n location: typing.Optional[str] = None,\n *,\n unknown: typing.Optional[str] = _UNKNOWN_DEFAULT_PARAM,\n error_handler: typing.Optional[ErrorHandler] = None,\n schema_class: typing.Optional[typing.Type] = None\n ):\n self.location = location or self.DEFAULT_LOCATION\n self.error_callback: typing.Optional[ErrorHandler] = _callable_or_raise(\n error_handler\n )\n self.schema_class = schema_class or self.DEFAULT_SCHEMA_CLASS\n self.unknown = unknown\n\n def _get_loader(self, location: str) -> typing.Callable:\n \"\"\"Get the loader function for the given location.\n\n :raises: ValueError if a given location is invalid.\n \"\"\"\n valid_locations = set(self.__location_map__.keys())\n if location not in valid_locations:\n raise ValueError(f\"Invalid location argument: {location}\")\n\n # Parsing function to call\n # May be a method name (str) or a function\n func = self.__location_map__[location]\n if isinstance(func, str):\n return getattr(self, func)\n return func\n\n def _load_location_data(\n self, *, schema: ma.Schema, req: Request, location: str\n ) -> typing.Mapping:\n \"\"\"Return a dictionary-like object for the location on the given request.\n\n Needs to have the schema in hand in order to correctly handle loading\n lists from multidict objects and `many=True` schemas.\n \"\"\"\n loader_func = self._get_loader(location)\n data = loader_func(req, schema)\n # when the desired location is empty (no data), provide an empty\n # dict as the default so that optional arguments in a location\n # (e.g. optional JSON body) work smoothly\n if data is missing:\n data = {}\n return data\n\n def _on_validation_error(\n self,\n error: ValidationError,\n req: Request,\n schema: ma.Schema,\n location: str,\n *,\n error_status_code: typing.Optional[int],\n error_headers: typing.Optional[typing.Mapping[str, str]]\n ) -> typing.NoReturn:\n # rewrite messages to be namespaced under the location which created\n # them\n # e.g. {\"json\":{\"foo\":[\"Not a valid integer.\"]}}\n # instead of\n # {\"foo\":[\"Not a valid integer.\"]}\n error.messages = {location: error.messages}\n error_handler: ErrorHandler = self.error_callback or self.handle_error\n error_handler(\n error,\n req,\n schema,\n error_status_code=error_status_code,\n error_headers=error_headers,\n )\n\n def _validate_arguments(self, data: typing.Any, validators: CallableList) -> None:\n # although `data` is typically a Mapping, nothing forbids a `schema.load`\n # from returning an arbitrary object subject to validators\n for validator in validators:\n if validator(data) is False:\n msg = self.DEFAULT_VALIDATION_MESSAGE\n raise ValidationError(msg, data=data)\n\n def _get_schema(self, argmap: ArgMap, req: Request) -> ma.Schema:\n \"\"\"Return a `marshmallow.Schema` for the given argmap and request.\n\n :param argmap: Either a `marshmallow.Schema`, `dict`\n of argname -> `marshmallow.fields.Field` pairs, or a callable that returns\n a `marshmallow.Schema` instance.\n :param req: The request object being parsed.\n :rtype: marshmallow.Schema\n \"\"\"\n if isinstance(argmap, ma.Schema):\n schema = argmap\n elif isinstance(argmap, type) and issubclass(argmap, ma.Schema):\n schema = argmap()\n elif callable(argmap):\n schema = argmap(req)\n else:\n schema = self.schema_class.from_dict(argmap)()\n return schema\n\n def parse(\n self,\n argmap: ArgMap,\n req: typing.Optional[Request] = None,\n *,\n location: typing.Optional[str] = None,\n unknown: typing.Optional[str] = _UNKNOWN_DEFAULT_PARAM,\n validate: ValidateArg = None,\n error_status_code: typing.Optional[int] = None,\n error_headers: typing.Optional[typing.Mapping[str, str]] = None\n ):\n \"\"\"Main request parsing method.\n\n :param argmap: Either a `marshmallow.Schema`, a `dict`\n of argname -> `marshmallow.fields.Field` pairs, or a callable\n which accepts a request and returns a `marshmallow.Schema`.\n :param req: The request object to parse.\n :param str location: Where on the request to load values.\n Can be any of the values in :py:attr:`~__location_map__`. By\n default, that means one of ``('json', 'query', 'querystring',\n 'form', 'headers', 'cookies', 'files', 'json_or_form')``.\n :param str unknown: A value to pass for ``unknown`` when calling the\n schema's ``load`` method. Defaults to EXCLUDE for non-body\n locations and RAISE for request bodies. Pass ``None`` to use the\n schema's setting instead.\n :param callable validate: Validation function or list of validation functions\n that receives the dictionary of parsed arguments. Validator either returns a\n boolean or raises a :exc:`ValidationError`.\n :param int error_status_code: Status code passed to error handler functions when\n a `ValidationError` is raised.\n :param dict error_headers: Headers passed to error handler functions when a\n a `ValidationError` is raised.\n\n :return: A dictionary of parsed arguments\n \"\"\"\n req = req if req is not None else self.get_default_request()\n location = location or self.location\n # precedence order: explicit, instance setting, default per location\n unknown = (\n unknown\n if unknown != _UNKNOWN_DEFAULT_PARAM\n else (\n self.unknown\n if self.unknown != _UNKNOWN_DEFAULT_PARAM\n else self.DEFAULT_UNKNOWN_BY_LOCATION.get(location)\n )\n )\n load_kwargs: typing.Dict[str, typing.Any] = (\n {\"unknown\": unknown} if unknown else {}\n )\n if req is None:\n raise ValueError(\"Must pass req object\")\n data = None\n validators = _ensure_list_of_callables(validate)\n schema = self._get_schema(argmap, req)\n try:\n location_data = self._load_location_data(\n schema=schema, req=req, location=location\n )\n data = schema.load(location_data, **load_kwargs)\n self._validate_arguments(data, validators)\n except ma.exceptions.ValidationError as error:\n self._on_validation_error(\n error,\n req,\n schema,\n location,\n error_status_code=error_status_code,\n error_headers=error_headers,\n )\n raise ValueError(\n \"_on_validation_error hook did not raise an exception\"\n ) from error\n return data\n\n def get_default_request(self) -> typing.Optional[Request]:\n \"\"\"Optional override. Provides a hook for frameworks that use thread-local\n request objects.\n \"\"\"\n return None\n\n def get_request_from_view_args(\n self,\n view: typing.Callable,\n args: typing.Tuple,\n kwargs: typing.Mapping[str, typing.Any],\n ) -> typing.Optional[Request]:\n \"\"\"Optional override. Returns the request object to be parsed, given a view\n function's args and kwargs.\n\n Used by the `use_args` and `use_kwargs` to get a request object from a\n view's arguments.\n\n :param callable view: The view function or method being decorated by\n `use_args` or `use_kwargs`\n :param tuple args: Positional arguments passed to ``view``.\n :param dict kwargs: Keyword arguments passed to ``view``.\n \"\"\"\n return None\n\n @staticmethod\n def _update_args_kwargs(\n args: typing.Tuple,\n kwargs: typing.Dict[str, typing.Any],\n parsed_args: typing.Tuple,\n as_kwargs: bool,\n ) -> typing.Tuple[typing.Tuple, typing.Mapping]:\n \"\"\"Update args or kwargs with parsed_args depending on as_kwargs\"\"\"\n if as_kwargs:\n kwargs.update(parsed_args)\n else:\n # Add parsed_args after other positional arguments\n args += (parsed_args,)\n return args, kwargs\n\n def use_args(\n self,\n argmap: ArgMap,\n req: typing.Optional[Request] = None,\n *,\n location: typing.Optional[str] = None,\n unknown: typing.Optional[str] = _UNKNOWN_DEFAULT_PARAM,\n as_kwargs: bool = False,\n validate: ValidateArg = None,\n error_status_code: typing.Optional[int] = None,\n error_headers: typing.Optional[typing.Mapping[str, str]] = None\n ) -> typing.Callable[..., typing.Callable]:\n \"\"\"Decorator that injects parsed arguments into a view function or method.\n\n Example usage with Flask: ::\n\n @app.route('/echo', methods=['get', 'post'])\n @parser.use_args({'name': fields.Str()}, location=\"querystring\")\n def greet(args):\n return 'Hello ' + args['name']\n\n :param argmap: Either a `marshmallow.Schema`, a `dict`\n of argname -> `marshmallow.fields.Field` pairs, or a callable\n which accepts a request and returns a `marshmallow.Schema`.\n :param str location: Where on the request to load values.\n :param str unknown: A value to pass for ``unknown`` when calling the\n schema's ``load`` method.\n :param bool as_kwargs: Whether to insert arguments as keyword arguments.\n :param callable validate: Validation function that receives the dictionary\n of parsed arguments. If the function returns ``False``, the parser\n will raise a :exc:`ValidationError`.\n :param int error_status_code: Status code passed to error handler functions when\n a `ValidationError` is raised.\n :param dict error_headers: Headers passed to error handler functions when a\n a `ValidationError` is raised.\n \"\"\"\n location = location or self.location\n request_obj = req\n # Optimization: If argmap is passed as a dictionary, we only need\n # to generate a Schema once\n if isinstance(argmap, Mapping):\n argmap = self.schema_class.from_dict(argmap)()\n\n def decorator(func):\n req_ = request_obj\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n req_obj = req_\n\n if not req_obj:\n req_obj = self.get_request_from_v\n... [truncated 7032 chars]\n\n```\n\n### src/webargs/fields.py\n```python\n\"\"\"Field classes.\n\nIncludes all fields from `marshmallow.fields` in addition to a custom\n`Nested` field and `DelimitedList`.\n\nAll fields can optionally take a special `location` keyword argument, which\ntells webargs where to parse the request argument from.\n\n.. code-block:: python\n\n args = {\n \"active\": fields.Bool(location=\"query\"),\n \"content_type\": fields.Str(data_key=\"Content-Type\", location=\"headers\"),\n }\n\"\"\"\nimport typing\n\nimport marshmallow as ma\n\n# Expose all fields from marshmallow.fields.\nfrom marshmallow.fields import * # noqa: F40\n\n__all__ = [\"DelimitedList\"] + ma.fields.__all__\n\n\nclass Nested(ma.fields.Nested): # type: ignore[no-redef]\n \"\"\"Same as `marshmallow.fields.Nested`, except can be passed a dictionary as\n the first argument, which will be converted to a `marshmallow.Schema`.\n\n .. note::\n\n The schema class here will always be `marshmallow.Schema`, regardless\n of whether a custom schema class is set on the parser. Pass an explicit schema\n class if necessary.\n \"\"\"\n\n def __init__(self, nested, *args, **kwargs):\n if isinstance(nested, dict):\n nested = ma.Schema.from_dict(nested)\n super().__init__(nested, *args, **kwargs)\n\n\nclass DelimitedFieldMixin:\n \"\"\"\n This is a mixin class for subclasses of ma.fields.List and ma.fields.Tuple\n which split on a pre-specified delimiter. By default, the delimiter will be \",\"\n\n Because we want the MRO to reach this class before the List or Tuple class,\n it must be listed first in the superclasses\n\n For example, a DelimitedList-like type can be defined like so:\n\n >>> class MyDelimitedList(DelimitedFieldMixin, ma.fields.List):\n >>> pass\n \"\"\"\n\n delimiter: str = \",\"\n\n def _serialize(self, value, attr, obj, **kwargs):\n # serializing will start with parent-class serialization, so that we correctly\n # output lists of non-primitive types, e.g. DelimitedList(DateTime)\n return self.delimiter.join(\n format(each) for each in super()._serialize(value, attr, obj, **kwargs)\n )\n\n def _deserialize(self, value, attr, data, **kwargs):\n # attempting to deserialize from a non-string source is an error\n if not isinstance(value, (str, bytes)):\n raise self.make_error(\"invalid\")\n return super()._deserialize(value.split(self.delimiter), attr, data, **kwargs)\n\n\nclass DelimitedList(DelimitedFieldMixin, ma.fields.List):\n \"\"\"A field which is similar to a List, but takes its input as a delimited\n string (e.g. \"foo,bar,baz\").\n\n Like List, it can be given a nested field type which it will use to\n de/serialize each element of the list.\n\n :param Field cls_or_instance: A field class or instance.\n :param str delimiter: Delimiter between values.\n \"\"\"\n\n default_error_messages = {\"invalid\": \"Not a valid delimited list.\"}\n\n def __init__(\n self,\n cls_or_instance: typing.Union[ma.fields.Field, type],\n *,\n delimiter: typing.Optional[str] = None,\n **kwargs\n ):\n self.delimiter = delimiter or self.delimiter\n super().__init__(cls_or_instance, **kwargs)\n\n\nclass DelimitedTuple(DelimitedFieldMixin, ma.fields.Tuple):\n \"\"\"A field which is similar to a Tuple, but takes its input as a delimited\n string (e.g. \"foo,bar,baz\").\n\n Like Tuple, it can be given a tuple of nested field types which it will use to\n de/serialize each element of the tuple.\n\n :param Iterable[Field] tuple_fields: An iterable of field classes or instances.\n :param str delimiter: Delimiter between values.\n \"\"\"\n\n default_error_messages = {\"invalid\": \"Not a valid delimited tuple.\"}\n\n def __init__(\n self, tuple_fields, *, delimiter: typing.Optional[str] = None, **kwargs\n ):\n self.delimiter = delimiter or self.delimiter\n super().__init__(tuple_fields, **kwargs)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "marshmallow-code__webargs-4cdf92c98c03", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/marshmallow-code__webargs-4cdf92c98c03", "repo_key": "marshmallow-code__webargs", "repo": "marshmallow-code/webargs", "base_commit": "d4fbbb7e70648af961ba0c5214812bc8cf3426f1", "source_files": ["CHANGELOG.rst", "src/webargs/core.py", "src/webargs/fields.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Pyramid parser raises exception when `use_kwargs` is enabled\n\n## Description\nWhen utilizing the Pyramid parser, an unhandled exception occurs if the `use_kwargs` option is enabled or actively used. The expected behavior is for the parser to function correctly without errors, allowing `use_kwargs` to be processed as intended.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `f57c9b730d9b` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### webargs/pyramidparser.py\n```python\n# -*- coding: utf-8 -*-\n\"\"\"Pyramid request argument parsing.\n\nExample usage: ::\n\n from wsgiref.simple_server import make_server\n from pyramid.config import Configurator\n from pyramid.response import Response\n from webargs import Arg\n from webargs.pyramidparser import use_args\n\n hello_args = {\n 'name': Arg(str, default='World')\n }\n\n @use_args(hello_args)\n def hello_world(request, args):\n return Response('Hello ' + args['name'])\n\n if __name__ == '__main__':\n config = Configurator()\n config.add_route('hello', '/')\n config.add_view(hello_world, route_name='hello')\n app = config.make_wsgi_app()\n server = make_server('0.0.0.0', 6543, app)\n server.serve_forever()\n\"\"\"\nimport functools\nimport logging\n\nfrom webob.multidict import MultiDict\nfrom pyramid.httpexceptions import exception_response\n\nfrom webargs import core\nfrom webargs.core import text_type\n\nlogger = logging.getLogger(__name__)\n\nclass PyramidParser(core.Parser):\n \"\"\"Pyramid request argument parser.\"\"\"\n\n def parse_querystring(self, req, name, arg):\n \"\"\"Pull a querystring value from the request.\"\"\"\n return core.get_value(req.GET, name, arg.multiple)\n\n def parse_form(self, req, name, arg):\n \"\"\"Pull a form value from the request.\"\"\"\n return core.get_value(req.POST, name, arg.multiple)\n\n def parse_json(self, req, name, arg):\n \"\"\"Pull a json value from the request.\"\"\"\n try:\n json_data = req.json_body\n except ValueError:\n return core.Missing\n\n return core.get_value(json_data, name, arg.multiple)\n\n def parse_cookies(self, req, name, arg):\n \"\"\"Pull the value from the cookiejar.\"\"\"\n return core.get_value(req.cookies, name, arg.multiple)\n\n def parse_headers(self, req, name, arg):\n \"\"\"Pull a value from the header data.\"\"\"\n return core.get_value(req.headers, name, arg.multiple)\n\n def parse_files(self, req, name, arg):\n \"\"\"Pull a file from the request.\"\"\"\n files = ((k, v) for k, v in req.POST.items() if hasattr(v, 'file'))\n return core.get_value(MultiDict(files), name, arg.multiple)\n\n def handle_error(self, error):\n \"\"\"Handles errors during parsing. Aborts the current HTTP request and\n responds with a 400 error.\n \"\"\"\n logger.error(error)\n status_code = getattr(error, 'status_code', 400)\n data = getattr(error, 'data', {})\n raise exception_response(status_code, detail=text_type(error), **data)\n\n def use_args(self, argmap, req=None, locations=core.Parser.DEFAULT_LOCATIONS,\n validate=None):\n \"\"\"Decorator that injects parsed arguments into a view callable.\n Supports the *Class-based View* pattern where `request` is saved as an instance\n attribute on a view class.\n\n :param dict argmap: Dictionary of argument_name:Arg object pairs.\n :param req: The request object to parse\n :param tuple locations: Where on the request to search for values.\n :param callable validate:\n Validation function that receives the dictionary of parsed arguments.\n If the function returns ``False``, the parser will raise a\n :exc:`ValidationError`.\n \"\"\"\n def decorator(func):\n @functools.wraps(func)\n def wrapper(obj, *args, **kwargs):\n # The first argument is either `self` or `request`\n try: # get self.request\n request = obj.request\n except AttributeError: # first arg is request\n request = obj\n parsed_args = self.parse(argmap, req=request, locations=locations,\n validate=None)\n return func(obj, parsed_args, *args, **kwargs)\n return wrapper\n return decorator\n\nparser = PyramidParser()\nuse_args = parser.use_args\nuse_kwargs = parser.use_kwargs\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "marshmallow-code__webargs-b13b4f23e7ec", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/marshmallow-code__webargs-b13b4f23e7ec", "repo_key": "marshmallow-code__webargs", "repo": "marshmallow-code/webargs", "base_commit": "f57c9b730d9b274edce85de38cdc39fdbdc2ecca", "source_files": ["webargs/pyramidparser.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `DelimitedFieldMixin` does not gracefully support non-string delimited data\n\n## Description\nWhen using `DelimitedFieldMixin` or its subclasses with non-string delimited data, such as lists of integers, there is no mechanism\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `44e2037a5607` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.rst\n```python\nChangelog\n---------\n\n8.3.1 (Unreleased)\n******************\n\nChanges:\n\n* Type annotations for ``FlaskParser`` have been improved\n\n8.3.0 (2023-07-10)\n******************\n\nFeatures:\n\n* ``webargs.Parser`` now inherits from ``typing.Generic`` and is parametrizable\n over the type of the request object. Various framework-specific parsers are\n parametrized over their relevant request object classes.\n\n* ``webargs.Parser`` and its subclasses now support passing arguments as a\n single keyword argument without expanding the parsed data into its\n components. For more details, see advanced docs on\n ``Argument Passing and arg_name``.\n\nOther changes:\n\n* Type annotations have been improved to allow ``Mapping`` for dict-like\n schemas where previously ``dict`` was used. This makes the type covariant\n rather than invariant (:issue:`836`).\n\n* Test against Python 3.11 (:pr:`787`).\n\n8.2.0 (2022-07-11)\n******************\n\nFeatures:\n\n* A new method, ``webargs.Parser.async_parse``, can be used for async-aware\n parsing from the base parser class. This can handle async location loader\n functions and async error handlers.\n\n* ``webargs.Parser.use_args`` and ``use_kwargs`` can now be used to decorate\n async functions, and will use ``async_parse`` if the decorated function is\n also async. They will call the non-async ``parse`` method when used to\n decorate non-async functions.\n\n* As a result of the changes to ``webargs.Parser``, ``FlaskParser``,\n ``DjangoParser``, and ``FalconParser`` now all support async views.\n Thanks :user:`Isira-Seneviratne` for the initial PR.\n\nChanges:\n\n* The implementation of ``AsyncParser`` has changed. Now that\n ``webargs.Parser`` has built-in support for async usage, the primary\n purpose of ``AsyncParser`` is to redefine ``parse`` as an alias for\n ``async_parse``\n\n* Set ``python_requires>=3.7.2`` in package metadata (:pr:`692`).\n Thanks :user:`kasium` for the PR.\n\n8.1.0 (2022-01-12)\n******************\n\nBug fixes:\n\n* Fix publishing type hints per `PEP-561 `_.\n (:pr:`650`).\n* Add DelimitedTuple to fields.__all__ (:pr:`678`).\n* Narrow type of ``argmap`` from ``Mapping`` to ``Dict`` (:pr:`682`).\n\nOther changes:\n\n* Test against Python 3.10 (:pr:`647`).\n* Drop support for Python 3.6 (:pr:`673`).\n* Address distutils deprecation warning in Python 3.10 (:pr:`652`).\n Thanks :user:`kkirsche` for the PR.\n* Use postponed evaluation of annotations (:pr:`663`).\n Thanks :user:`Isira-Seneviratne` for the PR.\n* Pin mypy version in tox (:pr:`674`).\n* Improve type annotations for ``__version_info__`` (:pr:`680`).\n\n8.0.1 (2021-08-12)\n******************\n\nBug fixes:\n\n* Fix \"``DelimitedList`` deserializes empty string as ``['']``\" (:issue:`623`).\n Thanks :user:`TTWSchell` for reporting and for the PR.\n\nOther changes:\n\n* New documentation theme with `furo`. Thanks to :user:`pradyunsg` for writing\n furo!\n* Webargs has a new logo. Thanks to :user:`michaelizergit`! (:issue:`312`)\n* Don't build universal wheels. We don't support Python 2 anymore.\n (:pr:`632`)\n* Make the build reproducible (:pr:`631`).\n\n\n8.0.0 (2021-04-08)\n******************\n\nFeatures:\n\n* Add `Parser.pre_load` as a method for allowing users to modify data before\n schema loading, but without redefining location loaders. See advanced docs on\n `Parser pre_load` for usage information. (:pr:`583`)\n\n* *Backwards-incompatible*: ``unknown`` defaults to `None` for body locations\n (`json`, `form` and `json_or_form`) (:issue:`580`).\n\n* Detection of fields as \"multi-value\" for unpacking lists from multi-dict\n types is now extensible with the ``is_multiple`` attribute. If a field sets\n ``is_multiple = True`` it will be detected as a multi-value field. If\n ``is_multiple`` is not set or is set to ``None``, webargs will check if the\n field is an instance of ``List`` or ``Tuple``. (:issue:`563`)\n\n* A new attribute on ``Parser`` objects, ``Parser.KNOWN_MULTI_FIELDS`` can be\n used to set fields which should be detected as ``is_multiple=True`` even when\n the attribute is not set (:pr:`592`).\n\nSee docs on \"Multi-Field Detection\" for more details.\n\nBug fixes:\n\n* ``Tuple`` field now behaves as a \"multiple\" field (:pr:`585`).\n\n7.0.1 (2020-12-14)\n******************\n\nBug fixes:\n\n* Fix `DelimitedList` and `DelimitedTuple` to pass additional keyword arguments\n through their `_serialize` methods to the child fields and fix type checking\n on these classes. (:issue:`569`)\n Thanks to :user:`decaz` for reporting.\n\n7.0.0 (2020-12-10)\n******************\n\nChanges:\n\n* *Backwards-incompatible*: Drop support for webapp2 (:pr:`565`).\n\n* Add type annotations to `Parser` class, `DelimitedList`, and\n `DelimitedTuple`. (:issue:`566`)\n\n7.0.0b2 (2020-12-01)\n********************\n\nFeatures:\n\n* `DjangoParser` now supports the `headers` location. (:issue:`540`)\n\n* `FalconParser` now supports a new `media` location, which uses\n Falcon's `media` decoding. (:issue:`253`)\n\n`media` behaves very similarly to the `json` location but also supports any\nregistered media handler. See the\n`Falcon documentation on media types\n`_ for more details.\n\nChanges:\n\n* `FalconParser` defaults to the `media` location instead of `json`. (:issue:`253`)\n* Test against Python 3.9 (:pr:`552`).\n* *Backwards-incompatible*: Drop support for Python 3.5 (:pr:`553`).\n\n7.0.0b1 (2020-09-11)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: Remove support for marshmallow2 (:issue:`539`)\n\n* *Backwards-incompatible*: Remove `dict2schema`\n\n Users desiring the `dict2schema` functionality may now rely upon\n `marshmallow.Schema.from_dict`. Rewrite any code using `dict2schema` like so:\n\n.. code-block:: python\n\n import marshmallow as ma\n\n # webargs 6.x and older\n from webargs import dict2schema\n\n myschema = dict2schema({\"q1\", ma.fields.Int()})\n\n # webargs 7.x\n myschema = ma.Schema.from_dict({\"q1\", ma.fields.Int()})\n\nFeatures:\n\n* Add ``unknown`` as a parameter to ``Parser.parse``, ``Parser.use_args``,\n ``Parser.use_kwargs``, and parser instantiation. When set, it will be passed\n to ``Schema.load``. When not set, the value passed will depend on the parser's\n settings. If set to ``None``, the schema's default behavior will be used (i.e.\n no value is passed to ``Schema.load``) and parser settings will be ignored.\n\nThis allows usages like\n\n.. code-block:: python\n\n import marshmallow as ma\n\n\n @parser.use_kwargs(\n {\"q1\": ma.fields.Int(), \"q2\": ma.fields.Int()}, location=\"query\", unknown=ma.EXCLUDE\n )\n def foo(q1, q2):\n ...\n\n* Defaults for ``unknown`` may be customized on parser classes via\n ``Parser.DEFAULT_UNKNOWN_BY_LOCATION``, which maps location names to values\n to use.\n\nUsages are varied, but include\n\n.. code-block:: python\n\n import marshmallow as ma\n from webargs.flaskparser import FlaskParser\n\n # as well as...\n class MyParser(FlaskParser):\n DEFAULT_UNKNOWN_BY_LOCATION = {\"query\": ma.INCLUDE}\n\n\n parser = MyParser()\n\nSetting the ``unknown`` value for a Parser instance has higher precedence. So\n\n.. code-block:: python\n\n parser = MyParser(unknown=ma.RAISE)\n\nwill always pass ``RAISE``, even when the location is ``query``.\n\n* By default, webargs will pass ``unknown=EXCLUDE`` for all locations except\n for request bodies (``json``, ``form``, and ``json_or_form``) and path\n parameters. Request bodies and path parameters will pass ``unknown=RAISE``.\n This behavior is defined by the default value for\n ``DEFAULT_UNKNOWN_BY_LOCATION``.\n\nChanges:\n\n* Registered `error_handler` callbacks are required to raise an exception.\n If a handler is invoked and no exception is raised, `webargs` will raise\n a `ValueError` (:issue:`527`)\n\n6.1.1 (2020-09-08)\n******************\n\nBug fixes:\n\n* Failure to validate flask headers would produce error data which contained\n tuples as keys, and was therefore not JSON-serializable. (:issue:`500`)\n These errors will now extract the headername as the key correctly.\n Thanks to :user:`shughes-uk` for reporting.\n\n6.1.0 (2020-04-05)\n******************\n\nFeatures:\n\n* Add ``fields.DelimitedTuple`` when using marshmallow 3. This behaves as a\n combination of ``fields.DelimitedList`` and ``marshmallow.fields.Tuple``. It\n takes an iterable of fields, plus a delimiter (defaults to ``,``), and parses\n delimiter-separated strings into tuples. (:pr:`509`)\n\n* Add ``__str__`` and ``__repr__`` to MultiDictProxy to make it easier to work\n with (:pr:`488`)\n\nSupport:\n\n* Various docs updates (:pr:`482`, :pr:`486`, :pr:`489`, :pr:`498`, :pr:`508`).\n Thanks :user:`lefterisjp`, :user:`timgates42`, and :user:`ugultopu` for the PRs.\n\n\n6.0.0 (2020-02-27)\n******************\n\nFeatures:\n\n* ``FalconParser``: Pass request content length to ``req.stream.read`` to\n provide compatibility with ``falcon.testing`` (:pr:`477`).\n Thanks :user:`suola` for the PR.\n\n* *Backwards-incompatible*: Factorize the ``use_args`` / ``use_kwargs`` branch\n in all parsers. When ``as_kwargs`` is ``False``, arguments are now\n consistently appended to the arguments list by the ``use_args`` decorator.\n Before this change, the ``PyramidParser`` would prepend the argument list on\n each call to ``use_args``. Pyramid view functions must reverse the order of\n their arguments. (:pr:`478`)\n\n6.0.0b8 (2020-02-16)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: Use keyword-only arguments (:pr:`472`).\n\n6.0.0b7 (2020-02-14)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: webargs will rewrite the error messages in\n ValidationErrors to be namespaced under the location which raised the error.\n The `messages` field on errors will therefore be one layer deeper with a\n single top-level key.\n\n6.0.0b6 (2020-01-31)\n********************\n\nRefactoring:\n\n* Remove the cache attached to webargs parsers. Due to changes between webargs\n v5 and v6, the cache is no longer considered useful.\n\nOther changes:\n\n* Import ``Mapping`` from ``collections.abc`` in pyramidparser.py (:pr:`471`).\n Thanks :user:`tirkarthi` for the PR.\n\n6.0.0b5 (2020-01-30)\n********************\n\nRefactoring:\n\n* *Backwards-incompatible*: `DelimitedList` now requires that its input be a\n string and always serializes as a string. It can still serialize and deserialize\n using another field, e.g. `DelimitedList(Int())` is still valid and requires\n that the values in the list parse as ints.\n\n6.0.0b4 (2020-01-28)\n********************\n\nBug fixes:\n\n* :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched\n (bugfix from 5.5.3).\n\n6.0.0b3 (2020-01-21)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: Support Falcon 2.0. Drop support for Falcon 1.x\n (:pr:`459`). Thanks :user:`dodumosu` and :user:`Nateyo` for the PR.\n\n6.0.0b2 (2020-01-07)\n********************\n\nOther changes:\n\n* *Backwards-incompatible*: Drop support for Python 2 (:issue:`440`).\n Thanks :user:`hugovk` for the PR.\n\n6.0.0b1 (2020-01-06)\n********************\n\nFeatures:\n\n* *Backwards-incompatible*: Schemas will now load all data from a location, not\n only data specified by fields. As a result, schemas with validators which\n examine the full input data may change in behavior. The `unknown` parameter\n on schemas may be used to alter this. For example,\n `unknown=marshmallow.EXCLUDE` will produce a behavior similar to webargs v5.\n\nBug fixes:\n\n* *Backwards-incompatible*: All parsers now require the Content-Type to be set\n correctly when processing JSON request bodies. This impacts ``DjangoParser``,\n ``FalconParser``, ``FlaskParser``, and ``PyramidParser``\n\nRefactoring:\n\n* *Backwards-incompatible*: Schema fields may not specify a location any\n longer, and `Parser.use_args` and `Parser.use_kwargs` now accept `location`\n (singular) instead of `locations` (plural). Instead of using a single field or\n schema with multiple `locations`, users are recommended to make multiple\n calls to `use_args` or `use_kwargs` with a distinct schema per location. For\n example, code should be rewritten like this:\n\n.. code-block:: python\n\n # webargs 5.x and older\n @parser.use_args(\n {\n \"q1\": ma.fields.Int(location=\"query\"),\n \"q2\": ma.fields.Int(location=\"query\"),\n \"h1\": ma.fields.Int(location=\"headers\"),\n },\n locations=(\"query\", \"headers\"),\n )\n def foo(q1, q2, h1):\n ...\n\n\n # webargs 6.x\n @parser.use_args({\"q1\": ma.fields.Int(), \"q2\": ma.fields.Int()}, location=\"query\")\n @parser.use_args({\"h1\": ma.fields.Int()}, location=\"headers\")\n def foo(q1, q2, h1):\n ...\n\n* The `location_handler` decorator has been removed and replaced with\n `location_loader`. `location_loader` serves the same purpose (letting you\n write custom hooks for loading data) but its expected method signature is\n different. See the docs on `location_loader` for proper usage.\n\nThanks :user:`sirosen` for the PR!\n\n5.5.3 (2020-01-28)\n******************\n\nBug fixes:\n\n* :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched.\n\n5.5.2 (2019-10-06)\n******************\n\nBug fixes:\n\n* Handle ``UnicodeDecodeError`` when parsing JSON payloads (:issue:`427`).\n Thanks :user:`lindycoder` for the catch and patch.\n\n5.5.1 (2019-09-15)\n******************\n\nBug fixes:\n\n* Remove usage of deprecated ``Field.fail`` when using marshmallow 3.\n\n5.5.0 (2019-09-07)\n******************\n\nSupport:\n\n* Various docs updates (:pr:`414`, :pr:`421`).\n\nRefactoring:\n\n* Don't mutate ``globals()`` in ``webargs.fields`` (:pr:`411`).\n* Use marshmallow 3's ``Schema.from_dict`` if available (:pr:`415`).\n\n5.4.0 (2019-07-23)\n******************\n\nChanges:\n\n* Use explicit type check for `fields.DelimitedList` when deciding to\n parse value with `getlist()` (`#406 (comment) `_ ).\n\nSupport:\n\n* Add \"Parsing Lists in Query Strings\" section to docs (:issue:`406`).\n\n5.3.2 (2019-06-19)\n******************\n\nBug fixes:\n\n* marshmallow 3.0.0rc7 compatibility (:pr:`395`).\n\n5.3.1 (2019-05-05)\n******************\n\nBug fixes:\n\n* marshmallow 3.0.0rc6 compatibility (:pr:`384`).\n\n5.3.0 (2019-04-08)\n******************\n\nFeatures:\n\n* Add `\"path\"` location to ``AIOHTTPParser``, ``FlaskParser``, and\n ``PyramidParser`` (:pr:`379`). Thanks :user:`zhenhua32` for the PR.\n* Add ``webargs.__version_info__``.\n\n5.2.0 (2019-03-16)\n******************\n\nFeatures:\n\n* Make the schema class used when generating a schema from a\n dict overridable (:issue:`375`). Thanks :user:`ThiefMaster`.\n\n5.1.3 (2019-03-11)\n******************\n\nBug fixes:\n\n* :cve:`CVE-2019-9710`: Fix race condition between parallel requests when the cache is used\n (:issue:`371`). Thanks :user:`ThiefMaster` for reporting and fixing.\n\n5.1.2 (2019-02-03)\n******************\n\nBug fixes:\n\n* Remove lingering usages of ``ValidationError.status_code``\n (:issue:`365`). Thanks :user:`decaz` for reporting.\n* Avoid ``AttributeError`` on Python<3.5.4 (:issue:`366`).\n* Fix incorrect type annotations for ``error_headers``.\n* Fix outdated docs (:issue:`367`). Thanks :user:`alexandersoto` for reporting.\n\n5.1.1.post0 (2019-01-30)\n************************\n\n* Include LICENSE in sdist (:issue:`364`).\n\n5.1.1 (2019-01-28)\n******************\n\nBug fixes:\n\n* Fix installing ``simplejson`` on Python 2 by\n distributing a Python 2-only wheel (:issue:`363`).\n\n5.1.0 (2019-01-11)\n******************\n\nFeatures:\n\n* Error handlers for `AsyncParser` classes may be coroutine functions.\n* Add type annotations to `AsyncParser` and `AIOHTTPParser`.\n\nBug fixes:\n\n* Fix compatibility with Flask<1.0 (:issue:`355`).\n Thanks :user:`hoatle` for reporting.\n* Address warning on Python 3.7 about importing from ``collections.abc``.\n\n5.0.0 (2019-01-03)\n******************\n\nFeatures:\n\n* *Backwards-incompatible*: A 400 HTTPError is raised when an\n invalid JSON payload is passed. (:issue:`329`).\n Thanks :user:`zedrdave` for reporting.\n\nOther changes:\n\n* *Backwards-incompatible*: `webargs.argmap2schema` is removed. U\n... [truncated 25654 chars]\n\n```\n\n### src/webargs/fields.py\n```python\n\"\"\"Field classes.\n\nIncludes all fields from `marshmallow.fields` in addition to a custom\n`Nested` field and `DelimitedList`.\n\nAll fields can optionally take a special `location` keyword argument, which\ntells webargs where to parse the request argument from.\n\n.. code-block:: python\n\n args = {\n \"active\": fields.Bool(location=\"query\"),\n \"content_type\": fields.Str(data_key=\"Content-Type\", location=\"headers\"),\n }\n\"\"\"\nfrom __future__ import annotations\n\nimport marshmallow as ma\n\n# Expose all fields from marshmallow.fields.\nfrom marshmallow.fields import * # noqa: F40\n\n__all__ = [\"DelimitedList\", \"DelimitedTuple\"] + ma.fields.__all__\n\n\n# TODO: remove custom `Nested` in the next major release\n#\n# the `Nested` class is only needed on versions of marshmallow prior to v3.15.0\n# in that version, `ma.fields.Nested` gained the ability to consume dict inputs\n# prior to that, this subclass adds this capability\n#\n# if we drop support for ma.__version_info__ < (3, 15) we can do this\nclass Nested(ma.fields.Nested): # type: ignore[no-redef]\n \"\"\"Same as `marshmallow.fields.Nested`, except can be passed a dictionary as\n the first argument, which will be converted to a `marshmallow.Schema`.\n\n .. note::\n\n The schema class here will always be `marshmallow.Schema`, regardless\n of whether a custom schema class is set on the parser. Pass an explicit schema\n class if necessary.\n \"\"\"\n\n def __init__(self, nested, *args, **kwargs):\n if isinstance(nested, dict):\n nested = ma.Schema.from_dict(nested)\n super().__init__(nested, *args, **kwargs)\n\n\nclass DelimitedFieldMixin:\n \"\"\"\n This is a mixin class for subclasses of ma.fields.List and ma.fields.Tuple\n which split on a pre-specified delimiter. By default, the delimiter will be \",\"\n\n Because we want the MRO to reach this class before the List or Tuple class,\n it must be listed first in the superclasses\n\n For example, a DelimitedList-like type can be defined like so:\n\n >>> class MyDelimitedList(DelimitedFieldMixin, ma.fields.List):\n >>> pass\n \"\"\"\n\n delimiter: str = \",\"\n # delimited fields set is_multiple=False for webargs.core.is_multiple\n is_multiple: bool = False\n\n def _serialize(self, value, attr, obj, **kwargs):\n # serializing will start with parent-class serialization, so that we correctly\n # output lists of non-primitive types, e.g. DelimitedList(DateTime)\n return self.delimiter.join(\n format(each) for each in super()._serialize(value, attr, obj, **kwargs)\n )\n\n def _deserialize(self, value, attr, data, **kwargs):\n # attempting to deserialize from a non-string source is an error\n if not isinstance(value, (str, bytes)):\n raise self.make_error(\"invalid\")\n values = value.split(self.delimiter) if value else []\n return super()._deserialize(values, attr, data, **kwargs)\n\n\nclass DelimitedList(DelimitedFieldMixin, ma.fields.List):\n \"\"\"A field which is similar to a List, but takes its input as a delimited\n string (e.g. \"foo,bar,baz\").\n\n Like List, it can be given a nested field type which it will use to\n de/serialize each element of the list.\n\n :param Field cls_or_instance: A field class or instance.\n :param str delimiter: Delimiter between values.\n \"\"\"\n\n default_error_messages = {\"invalid\": \"Not a valid delimited list.\"}\n\n def __init__(\n self,\n cls_or_instance: ma.fields.Field | type,\n *,\n delimiter: str | None = None,\n **kwargs,\n ):\n self.delimiter = delimiter or self.delimiter\n super().__init__(cls_or_instance, **kwargs)\n\n\nclass DelimitedTuple(DelimitedFieldMixin, ma.fields.Tuple):\n \"\"\"A field which is similar to a Tuple, but takes its input as a delimited\n string (e.g. \"foo,bar,baz\").\n\n Like Tuple, it can be given a tuple of nested field types which it will use to\n de/serialize each element of the tuple.\n\n :param Iterable[Field] tuple_fields: An iterable of field classes or instances.\n :param str delimiter: Delimiter between values.\n \"\"\"\n\n default_error_messages = {\"invalid\": \"Not a valid delimited tuple.\"}\n\n def __init__(self, tuple_fields, *, delimiter: str | None = None, **kwargs):\n self.delimiter = delimiter or self.delimiter\n super().__init__(tuple_fields, **kwargs)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "marshmallow-code__webargs-be8461c20e8c", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/marshmallow-code__webargs-be8461c20e8c", "repo_key": "marshmallow-code__webargs", "repo": "marshmallow-code/webargs", "base_commit": "44e2037a5607f3655f47d475272eab01d49aaaa0", "source_files": ["CHANGELOG.rst", "src/webargs/fields.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** DelimitedList returns `['']` when field value is an empty string\n\n## Description\nWhen a `DelimitedList` field processes an empty string (`\"\"`) as its input value, it currently returns a list containing a single empty string (`['']`). The expected behavior is for the `DelimitedList` to return an empty list (`[]`) when the input value is an empty string, indicating that no items were present to be delimited.\n\n**Reproduction:**\n```python\n# Assuming 'field' is an instance of DelimitedList\nresult = field.load(\"\") # or field.parse_value(\"\")\n# Actual: result is ['']\n# Expected: result should be []\n```\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `ed8840c4bb06` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### src/webargs/fields.py\n```python\n\"\"\"Field classes.\n\nIncludes all fields from `marshmallow.fields` in addition to a custom\n`Nested` field and `DelimitedList`.\n\nAll fields can optionally take a special `location` keyword argument, which\ntells webargs where to parse the request argument from.\n\n.. code-block:: python\n\n args = {\n \"active\": fields.Bool(location=\"query\"),\n \"content_type\": fields.Str(data_key=\"Content-Type\", location=\"headers\"),\n }\n\"\"\"\nimport typing\n\nimport marshmallow as ma\n\n# Expose all fields from marshmallow.fields.\nfrom marshmallow.fields import * # noqa: F40\n\n__all__ = [\"DelimitedList\"] + ma.fields.__all__\n\n\nclass Nested(ma.fields.Nested): # type: ignore[no-redef]\n \"\"\"Same as `marshmallow.fields.Nested`, except can be passed a dictionary as\n the first argument, which will be converted to a `marshmallow.Schema`.\n\n .. note::\n\n The schema class here will always be `marshmallow.Schema`, regardless\n of whether a custom schema class is set on the parser. Pass an explicit schema\n class if necessary.\n \"\"\"\n\n def __init__(self, nested, *args, **kwargs):\n if isinstance(nested, dict):\n nested = ma.Schema.from_dict(nested)\n super().__init__(nested, *args, **kwargs)\n\n\nclass DelimitedFieldMixin:\n \"\"\"\n This is a mixin class for subclasses of ma.fields.List and ma.fields.Tuple\n which split on a pre-specified delimiter. By default, the delimiter will be \",\"\n\n Because we want the MRO to reach this class before the List or Tuple class,\n it must be listed first in the superclasses\n\n For example, a DelimitedList-like type can be defined like so:\n\n >>> class MyDelimitedList(DelimitedFieldMixin, ma.fields.List):\n >>> pass\n \"\"\"\n\n delimiter: str = \",\"\n # delimited fields set is_multiple=False for webargs.core.is_multiple\n is_multiple: bool = False\n\n def _serialize(self, value, attr, obj, **kwargs):\n # serializing will start with parent-class serialization, so that we correctly\n # output lists of non-primitive types, e.g. DelimitedList(DateTime)\n return self.delimiter.join(\n format(each) for each in super()._serialize(value, attr, obj, **kwargs)\n )\n\n def _deserialize(self, value, attr, data, **kwargs):\n # attempting to deserialize from a non-string source is an error\n if not isinstance(value, (str, bytes)):\n raise self.make_error(\"invalid\")\n return super()._deserialize(value.split(self.delimiter), attr, data, **kwargs)\n\n\nclass DelimitedList(DelimitedFieldMixin, ma.fields.List):\n \"\"\"A field which is similar to a List, but takes its input as a delimited\n string (e.g. \"foo,bar,baz\").\n\n Like List, it can be given a nested field type which it will use to\n de/serialize each element of the list.\n\n :param Field cls_or_instance: A field class or instance.\n :param str delimiter: Delimiter between values.\n \"\"\"\n\n default_error_messages = {\"invalid\": \"Not a valid delimited list.\"}\n\n def __init__(\n self,\n cls_or_instance: typing.Union[ma.fields.Field, type],\n *,\n delimiter: typing.Optional[str] = None,\n **kwargs\n ):\n self.delimiter = delimiter or self.delimiter\n super().__init__(cls_or_instance, **kwargs)\n\n\nclass DelimitedTuple(DelimitedFieldMixin, ma.fields.Tuple):\n \"\"\"A field which is similar to a Tuple, but takes its input as a delimited\n string (e.g. \"foo,bar,baz\").\n\n Like Tuple, it can be given a tuple of nested field types which it will use to\n de/serialize each element of the tuple.\n\n :param Iterable[Field] tuple_fields: An iterable of field classes or instances.\n :param str delimiter: Delimiter between values.\n \"\"\"\n\n default_error_messages = {\"invalid\": \"Not a valid delimited tuple.\"}\n\n def __init__(\n self, tuple_fields, *, delimiter: typing.Optional[str] = None, **kwargs\n ):\n self.delimiter = delimiter or self.delimiter\n super().__init__(tuple_fields, **kwargs)\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "marshmallow-code__webargs-f2cc3fec3622", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/marshmallow-code__webargs-f2cc3fec3622", "repo_key": "marshmallow-code__webargs", "repo": "marshmallow-code/webargs", "base_commit": "ed8840c4bb06f1b3bcaf664e025183423349d9d2", "source_files": ["src/webargs/fields.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** City area data is not normalized and validation rules are insufficient\n\n## Description\nWhen processing city area data, the system fails to normalize the input correctly, leading to inconsistent or incorrect data representations. Additionally, the existing validation rules are not robust enough, allowing invalid data to pass through or incorrectly flagging valid data. The expected behavior is for city area data to be consistently normalized and for all input to be thoroughly validated against correct rules.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `21693704723a` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### i18naddress/__init__.py\n```python\nfrom __future__ import unicode_literals\n\nfrom collections import namedtuple\nimport json\n\nimport io\nimport os\nimport re\n\nVALID_COUNTRY_CODE = re.compile(r'^\\w{2,3}$')\nVALIDATION_DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') \nVALIDATION_DATA_PATH = os.path.join(VALIDATION_DATA_DIR, '%s.json')\n\nFIELD_MAPPING = {\n 'A': 'street_address',\n 'C': 'city',\n 'D': 'city_area',\n 'N': 'name',\n 'O': 'company_name',\n 'S': 'country_area',\n 'X': 'sorting_code',\n 'Z': 'postal_code'}\n\nKNOWN_FIELDS = set(FIELD_MAPPING.values()) | {'country_code'}\n\n\ndef load_validation_data(country_code='all'):\n if not VALID_COUNTRY_CODE.match(country_code):\n raise ValueError(\n '%r is not a valid country code' % (country_code,))\n country_code = country_code.lower()\n path = VALIDATION_DATA_PATH % (country_code,)\n if not os.path.exists(path):\n raise ValueError(\n '%r is not a valid country code' % (country_code,))\n with io.open(path, encoding='utf-8') as data:\n return json.load(data)\n\n\nValidationRules = namedtuple(\n 'ValidationRules', [\n 'country_name',\n 'address_format', 'address_latin_format',\n 'allowed_fields', 'required_fields', 'upper_fields',\n 'country_area_type', 'country_area_choices',\n 'city_type', 'city_choices',\n 'city_area_type', 'city_area_choices',\n 'postal_code_type', 'postal_code_matchers', 'postal_code_examples',\n 'postal_code_prefix'])\n\n\ndef _make_choices(rules, translated=False):\n sub_keys = rules.get('sub_keys')\n if not sub_keys:\n return []\n choices = []\n sub_keys = sub_keys.split('~')\n sub_names = rules.get('sub_names')\n if sub_names:\n choices += [\n (key, value)\n for key, value in zip(sub_keys, sub_names.split('~'))\n if value]\n else:\n if not translated:\n choices += [(key, key) for key in sub_keys]\n if not translated:\n sub_lnames = rules.get('sub_lnames')\n if sub_lnames:\n choices += [\n (key, value)\n for key, value in zip(sub_keys, sub_lnames.split('~'))\n if value]\n sub_lfnames = rules.get('sub_lfnames')\n if sub_lfnames:\n choices += [\n (key, value)\n for key, value in zip(sub_keys, sub_lfnames.split('~'))\n if value]\n return choices\n\n\ndef _match_choices(value, choices):\n if value:\n value = value.strip().lower()\n for name, label in choices:\n if name.lower() == value:\n return name\n if label.lower() == value:\n return name\n\n\ndef _load_country_data(country_code):\n database = load_validation_data('zz')\n country_data = database['ZZ']\n if country_code:\n country_code = country_code.upper()\n if country_code.lower() == 'zz':\n raise ValueError(\n '%r is not a valid country code' % (country_code,))\n database = load_validation_data(country_code.lower())\n country_data.update(database[country_code])\n return country_data, database\n\n\ndef get_validation_rules(address):\n country_code = address.get('country_code', '').upper()\n country_data, database = _load_country_data(country_code)\n country_name = country_data.get('name', '')\n address_format = country_data['fmt']\n address_latin_format = country_data.get('lfmt', address_format)\n format_fields = re.finditer(r'%([ACDNOSXZ])', address_format)\n allowed_fields = {FIELD_MAPPING[m.group(1)] for m in format_fields}\n required_fields = {FIELD_MAPPING[f] for f in country_data['require']}\n upper_fields = {FIELD_MAPPING[f] for f in country_data['upper']}\n languages = []\n if 'languages' in country_data:\n languages = country_data['languages'].split('~')\n languages.remove(country_data['lang'])\n\n postal_code_matchers = []\n if 'postal_code' in required_fields:\n if 'zip' in country_data:\n postal_code_matchers.append(\n re.compile('^' + country_data['zip'] + '$'))\n postal_code_examples = country_data.get('zipex')\n\n city_choices = []\n city_area_choices = []\n country_area_type = country_data['state_name_type']\n city_type = country_data['locality_name_type']\n city_area_type = country_data['sublocality_name_type']\n postal_code_type = country_data['zip_name_type']\n postal_code_prefix = country_data.get('postprefix', '')\n # second level of data is for administrative areas\n country_area_choices = _make_choices(country_data)\n for language in languages:\n localized_country_data = database['%s--%s' % (\n country_code, language)]\n country_area_choices += _make_choices(\n localized_country_data, translated=True)\n country_area = _match_choices(\n address.get('country_area'), country_area_choices)\n if country_area:\n # third level of data is for cities\n country_area_data = database['%s/%s' % (\n country_code, country_area)]\n if 'zip' in country_area_data:\n postal_code_matchers.append(\n re.compile('^' + country_area_data['zip']))\n if 'zipex' in country_area_data:\n postal_code_examples = country_area_data['zipex']\n city_choices = _make_choices(country_area_data)\n for language in languages:\n localized_country_area_data = database['%s/%s--%s' % (\n country_code, country_area, language)]\n city_choices += _make_choices(\n localized_country_area_data, translated=True)\n city = _match_choices(\n address.get('city'), city_choices)\n if city:\n # fourth level of data is for dependent sublocalities\n city_data = database['%s/%s/%s' % (\n country_code, country_area, city)]\n if 'zip' in city_data:\n postal_code_matchers.append(\n re.compile('^' + city_data['zip']))\n if 'zipex' in city_data:\n postal_code_examples = city_data['zipex']\n city_area_choices = _make_choices(city_data)\n for language in languages:\n localized_city_data = database['%s/%s/%s--%s' % (\n country_code, country_area, city, language)]\n city_area_choices += _make_choices(\n localized_city_data, translated=True)\n return ValidationRules(\n country_name,\n address_format, address_latin_format,\n allowed_fields, required_fields, upper_fields,\n country_area_type, country_area_choices,\n city_type, city_choices,\n city_area_type, city_area_choices,\n postal_code_type, postal_code_matchers, postal_code_examples,\n postal_code_prefix)\n\n\nclass InvalidAddress(ValueError):\n def __init__(self, message, errors):\n super(InvalidAddress, self).__init__(message)\n self.errors = errors\n\n\ndef _normalize_field(name, rules, data, choices, errors):\n value = data.get(name)\n if name in rules.upper_fields and value is not None:\n value = value.upper()\n data[name] = value\n if name not in rules.allowed_fields:\n data[name] = ''\n elif not value and name in rules.required_fields:\n errors[name] = 'required'\n elif choices:\n value = _match_choices(value, choices)\n if value is not None:\n data[name] = value\n else:\n errors[name] = 'invalid'\n if not value:\n data[name] = ''\n\n\ndef normalize_address(address):\n errors = {}\n try:\n rules = get_validation_rules(address)\n except ValueError:\n errors['country_code'] = 'invalid'\n else:\n cleaned_data = address.copy()\n country_code = cleaned_data.get('country_code')\n if not country_code:\n errors['country_code'] = 'required'\n else:\n cleaned_data['country_code'] = country_code.upper()\n _normalize_field(\n 'country_area', rules, cleaned_data, rules.country_area_choices,\n errors)\n _normalize_field(\n 'city', rules, cleaned_data, rules.city_choices, errors)\n _normalize_field(\n 'city_area', rules, cleaned_data, rules.city_area_choices, errors)\n _normalize_field(\n 'postal_code', rules, cleaned_data, [], errors)\n postal_code = cleaned_data.get('postal_code', '')\n if rules.postal_code_matchers and postal_code:\n for matcher in rules.postal_code_matchers:\n if not matcher.match(postal_code):\n errors['postal_code'] = 'invalid'\n break\n _normalize_field(\n 'street_address', rules, cleaned_data, [], errors)\n _normalize_field(\n 'sorting_code', rules, cleaned_data, [], errors)\n if errors:\n raise InvalidAddress('Invalid address', errors)\n return cleaned_data\n\n\ndef _format_address_line(line_format, address, rules):\n\n def _get_field(name):\n value = address.get(name, '')\n if name in rules.upper_fields:\n value = value.upper()\n return value\n replacements = {'%%%s' % code: _get_field(field_name)\n for code, field_name in FIELD_MAPPING.items()}\n\n fields = re.split('(%.)', line_format)\n fields = [replacements.get(f, f) for f in fields]\n return ''.join(fields).strip()\n\n\ndef get_field_order(address, latin=False):\n \"\"\"\n Returns expected order of address form fields as a list of lists.\n Example for PL:\n >>> get_field_order({'country_code': 'PL'})\n [[u'name'], [u'company_name'], [u'street_address'], [u'postal_code', u'city']]\n \"\"\"\n rules = get_validation_rules(address)\n address_format = (\n rules.address_latin_format if latin else rules.address_format)\n address_lines = address_format.split('%n')\n replacements = {'%%%s' % code: field_name\n for code, field_name in FIELD_MAPPING.items()}\n all_lines = []\n for line in address_lines:\n fields = re.split('(%.)', line)\n single_line = [replacements.get(field) for field in fields]\n single_line = list(filter(None, single_line))\n all_lines.append(single_line)\n return all_lines\n\n\ndef format_address(address, latin=False):\n rules = get_validation_rules(address)\n address_format = (\n rules.address_latin_format if latin else rules.address_format)\n address_line_formats = address_format.split('%n')\n address_lines = [\n _format_address_line(lf, address, rules)\n for lf in address_line_formats]\n address_lines.append(rules.country_name)\n address_lines = filter(None, address_lines)\n return '\\n'.join(address_lines)\n\n\ndef latinize_address(address, normalized=False):\n if not normalized:\n address = normalize_address(address)\n cleaned_data = address.copy()\n country_code = address.get('country_code', '').upper()\n dummy_country_data, database = _load_country_data(country_code)\n if country_code:\n country_area = address['country_area']\n if country_area:\n key = '%s/%s' % (country_code, country_area)\n country_area_data = database.get(key)\n if country_area_data:\n cleaned_data['country_area'] = country_area_data.get(\n 'lname',\n country_area_data.get('name', country_area))\n city = address['city']\n key = '%s/%s/%s' % (country_code, country_area, city)\n city_data = database.get(key)\n if city_data:\n cleaned_data['city'] = city_data.get(\n 'lname',\n city_data.get('name', city))\n city_area = address['city_area']\n key = '%s/%s/%s/%s' % (\n country_code, country_area, city, city_area)\n city_area_data = database.get(key)\n if city_area_data:\n cleaned_data['city_area'] = city_data.get(\n 'lname',\n city_area_data.get('name', city_area))\n return cleaned_data\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "mirumee__google-i18n-address-311eb0f1a0fa", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/mirumee__google-i18n-address-311eb0f1a0fa", "repo_key": "mirumee__google-i18n-address", "repo": "mirumee/google-i18n-address", "base_commit": "21693704723afbe9a9fadffa206caaa41bf217e2", "source_files": ["i18naddress/__init__.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `config.eval` fails due to incorrect type casting\n\n## Description\nWhen attempting to use `config.eval`, the operation fails because of an incorrect type cast. This prevents the configuration from being evaluated successfully and blocks further progress. The expected behavior is for `config.eval` to correctly handle all necessary type conversions and complete its evaluation without errors.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `4572e2897fd8` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGES.txt\n```python\n1.2.2\n=====\n\n - Remove testfixtures requirements (it's broken with pypy)\n\n1.2.1\n=====\n\n - New cast type: config.eval (uses ``ast.literal_eval`` to cast python settings)\n - 3rd-party suggestion: dj-email-url parser in documentation\n\n1.2.0\n=====\n\n - New cast type: config.tuple (converts a comma-separated string in tuple)\n\n1.1.2\n=====\n\n - Ignore errors in ``make clean``\n\n1.1.1\n=====\n\n - Fix a brown paper bug in the last release\n - Force test running in ``make release`` target\n - Add \"pragma: no cover\" in abstract methods\n\n1.1.0\n=====\n\n - Skip discovering files inside not-directory paths (eg. ``.egg``, ``.zip``\n or wheel packages)\n\n1.0.1\n=====\n\n - Fix a issue that breaks .ini/.cfg loader with \"broken\" files\n\n1.0.0\n=====\n\n - First stable release! hooray!\n - Make configuration load lazy to make possible change root_path and\n starting_path in prettyconf.config\n - Default root_path is \"/\" instead of $HOME (backward incompatible change)\n - Add missing requirements in requirements.txt and make tox use it.\n - Small PEP-8 and code formatting fixes\n\n0.4.1\n=====\n\n - Add MacOSX travis builds.\n\n0.4.0\n=====\n\n - Add ``root_path`` to stop looking indefinitely for configuration files until the OS root path\n - Add advanced usage docs\n - Include a simple (but working) tox configuration for py27 + py34 to the project\n\n\n0.3.3\n=====\n\n - Start a structure to make a better documentation with sphinx and publish it at Read the Docs\n\n0.3.2\n=====\n\n - Stop directories from being traversed up when valid configurations were found.\n - Validates invalid unicode data on INI files (and skip them)\n - Better Python3 support with use of ConfigParser.read_file\n - Code cleanup\n - More test cases for ConfigurationDiscovery added\n\n0.3.1\n=====\n\n - Fix a bad behaviour that make impossible to define a None default\n\n0.3.0\n=====\n\n - Make config.{cast} shortcuts easier to use. This change breaks backward compatibility.\n\n0.2.2\n=====\n\n - Fix an issue with .env parser that breaks with unquoted URL values\n - Fix an issue with magic _get_path used by config discovery (thanks @bertonha)\n\n0.2.0\n=====\n\n - Add basic documentation\n\n0.1.1\n=====\n\n - Fix a small issue in README.txt formatting\n\n0.1\n===\n\n - First version\n\n\n```\n\n### prettyconf/configuration.py\n```python\n# coding: utf-8\n\n\nimport os\nimport sys\nimport ast\n\nfrom .loaders import EnvFileConfigurationLoader, IniFileConfigurationLoader, EnvVarConfigurationLoader\nfrom .exceptions import InvalidConfigurationFile, InvalidPath, InvalidConfigurationCast, UnknownConfiguration\nfrom .casts import Boolean, Option, List, Tuple\n\n\nMAGIC_FRAME_DEPTH = 3\n\n\nclass ConfigurationDiscovery(object):\n default_filetypes = (EnvFileConfigurationLoader, IniFileConfigurationLoader)\n\n def __init__(self, starting_path, filetypes=None, root_path=\"/\"):\n \"\"\"\n Setup the configuration file discovery.\n\n :param starting_path: The path to begin looking for configuration files\n :param filetypes: tuple with configuration loaders. Defaults to\n ``(EnvFileConfigurationLoader, IniFileConfigurationLoader)``\n :param root_path: Configuration lookup will stop at the given path. Defaults to\n the current user directory\n \"\"\"\n self.starting_path = os.path.realpath(os.path.abspath(starting_path))\n self.root_path = os.path.realpath(root_path)\n\n if not self.starting_path.startswith(self.root_path):\n raise InvalidPath('Invalid root path given')\n\n if filetypes is None:\n filetypes = self.default_filetypes\n\n self.filetypes = filetypes\n self._config_files = None\n\n def _scan_path(self, path):\n config_files = []\n\n for file_type in self.filetypes:\n for filename in file_type.get_filenames(path):\n try:\n config_files.append(file_type(filename))\n except InvalidConfigurationFile:\n continue\n\n return config_files\n\n def _discover(self):\n self._config_files = []\n\n path = self.starting_path\n while not self._config_files:\n if os.path.isdir(path):\n self._config_files += self._scan_path(path)\n\n if path == self.root_path:\n break\n\n path = os.path.dirname(path)\n\n @property\n def config_files(self):\n if self._config_files is None:\n self._discover()\n\n return self._config_files\n\n\nclass Configuration(object):\n # Shortcut for standard casts\n boolean = Boolean()\n list = List()\n tuple = Tuple()\n option = Option\n eval = ast.literal_eval\n\n def __init__(self, configs=None, starting_path=None, root_path=\"/\"):\n if configs is None:\n configs = [EnvVarConfigurationLoader()]\n self.configurations = configs\n self.starting_path = starting_path\n self.root_path = root_path\n self._initialized = False\n\n @staticmethod\n def _caller_path():\n # MAGIC! Get the caller's module path.\n # noinspection PyProtectedMember\n frame = sys._getframe(MAGIC_FRAME_DEPTH)\n path = os.path.dirname(frame.f_code.co_filename)\n return path\n\n def _init_configs(self):\n if self._initialized:\n return\n\n if self.starting_path is None:\n self.starting_path = self._caller_path()\n\n discovery = ConfigurationDiscovery(self.starting_path, root_path=self.root_path)\n self.configurations.extend(discovery.config_files)\n\n self._initialized = True\n\n def __call__(self, item, cast=lambda v: v, **kwargs):\n if not callable(cast):\n raise InvalidConfigurationCast(\"Cast must be callable\")\n\n self._init_configs()\n\n for configuration in self.configurations:\n try:\n return cast(configuration[item])\n except KeyError:\n continue\n\n if 'default' not in kwargs:\n raise UnknownConfiguration(\"Configuration '{}' not found\".format(item))\n\n return cast(kwargs[\"default\"])\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "osantana__prettyconf-16570d889998", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/osantana__prettyconf-16570d889998", "repo_key": "osantana__prettyconf", "repo": "osantana/prettyconf", "base_commit": "4572e2897fd8172cb47a26ac159734eef1ba669e", "source_files": ["CHANGES.txt", "prettyconf/configuration.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Variable expansion incorrectly discards trailing string content\n\n## Description\nWhen processing a string with variable expansion enabled (e.g., `expand_vars=True`), if the string begins with a variable reference like `${VAR}` but includes additional characters or content afterwards, the entire trailing portion of the string is unexpectedly discarded.\n\n**Reproduction:**\nGiven a variable `A=\"foo\"`, processing the string `\"${A};Val_B;\"` with variable expansion enabled.\n\n**Actual Result:** The output is `\"foo\"`.\n**Expected Result:** The output should be `\"foo;Val_B;\"`.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `f678dabd2ebb` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## next\n\nOther changes:\n\n- Update lowest supported marshmallow version to 3.26.2 ([#448](https://github.com/sloria/environs/pull/448)).\n Thanks [whyscream](https://github.com/whyscream) for the PR.\n\n## 14.5.0 (2025-11-02)\n\nFeatures:\n\n- Add `strip_whitespace` param to `FileAwareEnv` ([#431](https://github.com/sloria/environs/issues/431)).\n Thanks [eandersons](https://github.com/eandersons) for the suggestion and PR.\n\nOther changes:\n\n- Drop support for Python 3.9, which is EOL.\n\n## 14.4.0 (2025-10-29)\n\nFeatures:\n\n- Add support for ISO 8601 durations to `env.timedelta`. ([#434](https://github.com/sloria/environs/pull/434)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for the suggestion and PR.\n\n## 14.3.0 (2025-08-01)\n\nFeatures:\n\n- Add `environs.FileAwareEnv` for reading secret files ([#410](https://github.com/sloria/environs/pull/410)).\n Thanks [holtgrewe](https://github.com/holtgrewe) for the suggestion.\n Thanks [whyscream](https://github.com/whyscream) and [avilaton](https://github.com/avilaton) for the PRs.\n\n## 14.2.0 (2025-05-22)\n\nFeatures:\n\n- Add `key_value_delimiter` argument to `env.dict` ([#419](https://github.com/sloria/environs/issues/419)).\n Thanks [jerr0328](https://github.com/jerr0328) for the suggestion and PR.\n\n## 14.1.1 (2025-02-10)\n\nBug fixes:\n\n- Typing: Fix typing for `env.list` and `env.dict` to properly handle\n `default` and `subcast` arguments ([#406](https://github.com/sloria/environs/issues/406)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for the PR.\n- Add `env` to `__all__` ([#396](https://github.com/sloria/environs/issues/396)).\n Thanks [daveflr](https://github.com/daveflr) for reporting.\n\nChanges:\n\n- _Backwards-incompatible_: `recurse`, `verbose`, `override`,\n and `return_path` parameters to `Env.read_env` are now keyword-only.\n- _Backwards-incompatible_: The `required` argument to parser methods\n is removed. Call a parser method without a default value to make it required.\n\n## 14.1.0 (2025-01-10)\n\nFeatures:\n\n- Add `prefix` parameter to `Env` constructor ([#384](https://github.com/sloria/environs/issues/384)).\n Thanks [arthurc0102](https://github.com/sloria/environs/issues/384)\n for the suggestion.\n- Re-export `validate` module from marshmallow ([#385](https://github.com/sloria/environs/issues/385)).\n\nBug fixes:\n\n- Typing: Fix typing for `Env.enum` to allow `by_value` to be passed ([#386](https://github.com/sloria/environs/issues/386)).\n\n## 14.0.0 (2025-01-07)\n\nFeatures:\n\n- Add `env` singleton ([#194]).\n Thanks [AndBondStyle](https://github.com/AndBondStyle) for the suggestion.\n\n```python\nfrom environs import env\n```\n\nChanges:\n\n- `default` values are expected to be their in their deserialized form.\n _Backwards-incompatible_: Passing serialized values to `default`\n is no longer supported.\n\n```python\nfrom datetime import date, timedelta\nimport environs\n\n# DO\nenable_login = env.bool(\"ENABLE_LOGIN\", True)\nttl = env.timedelta(\"TTL\", default=timedelta(seconds=600))\nrelease_date = env.date(\"RELEASE\", date(2025, 1, 7))\nnumbers = env.list(\"FOO\", [1.0, 2.0, 3.0], subcast=float)\n\n# DON'T\nenable_login = env.bool(\"ENABLE_LOGIN\", \"true\")\nttl = env.timedelta(\"TTL\", default=600)\nrelease_date = env.date(\"RELEASE\", \"2025-01-07\")\nnumbers = env.list(\"NUMBERS\", \"1,2,42\", subcast=float)\n```\n\nThe exceptions to this rule are the Django-related functions, which\naccept string defaults.\n\n```python\nDATABASE_URL = env.dj_db_url(\"DATABASE_URL\", default=\"postgresql://localhost:5432/mydb\")\n```\n\nThis fixes [#297](https://github.com/sloria/environs/issues/297)\nand [#270](https://github.com/sloria/environs/issues/270).\n\n## 13.0.0 (2025-01-07)\n\nFeatures:\n\n- Typing: Add type hints for parser methods ([#367](https://github.com/sloria/environs/issues/367)).\n Thanks [OkeyDev](https://github/OkeyDev) for the PR.\n- Add `by_value` param to `Env.enum`. Pass `by_value=True` to parse Enum by values instead of names.\n\nOther changes:\n\n- Drop support for marshmallow<3.18.0.\n- _Backwards-incompatible_: Remove `load_default` param from parser methods. Use `default` instead.\n- _Backwards-incompatible_: Rename `Env.enum`'s `type` param to `enum`.\n- _Backwards-incompatible_: Remove `ignore_case` param from `Env.enum`.\n- _Backwards-incompatible_: Remove\n `allow_none`, `error_messages`, and `metadata` params from parser methods.\n\n## 12.0.0 (2025-01-06)\n\nFeatures:\n\n- `Env.enum` allows passing an `Enum` as `default`.\n\nOther changes:\n\n- Support marshmallow 4.\n- Support Python 3.9-3.13.\n- _Backwards-incompatible_: Make `Field` classes private. Users should\n not need to access these.\n\n## 11.2.1 (2024-11-20)\n\nBug fixes:\n\n- Fix passing non-string default values to `Env.timedelta` ([#369](https://github.com/sloria/environs/pull/369)).\n Thanks [tcleonard](https://github.com/tcleonard) for reporting and\n thanks [ddelange](https://github.com/ddelange) for the PR.\n- Fix `Env.read_env(recurse=True)` so that it returns as soon as a `.env`\n file is found ([#370](https://github.com/sloria/environs/pull/370)).\n Thanks [senese](https://github.com/senese) for the PR.\n\n## 11.2.0 (2024-11-14)\n\nFeatures:\n\n- `Env.timedelta` can parse [GEP-2257](https://gateway-api.sigs.k8s.io/geps/gep-2257/)\n duration strings ([#366](https://github.com/sloria/environs/pull/366)).\n Thanks [ddelange](https://github.com/ddelange) for the PR.\n\n## 11.1.0 (2024-11-11)\n\nFeatures:\n\n- Add `return_path` argument to `Env.read_env` to return the path of the\n parsed file ([#362](https://github.com/sloria/environs/issues/362)).\n Thanks [senese](https://github.com/senese) for the suggestion and PR.\n NOTE: This is added as a backwards-compatible change that is scheduled to be\n removed in 12.0.0. The path will stored as an attribute of `Env`.\n\n## 11.0.0 (2024-03-04)\n\nFixes:\n\n- Prevent `DeprecationWarning` getting raised by marshmallow 3.21.0 (:issue:`333`).\n\nOther changes:\n\n- Remove `subcast_key` argument of `env.dict`. Use `subcast_keys` instead.\n- Bump minimum required marshmallow version to 3.13.0.\n- Remove `missing` argument from `Env` methods. Use `default` instead.\n- Remove `subcast` argument from `Env` methods that don't use it.\n- _Backwards-incompatible_: Remove `environs.__version__` variable.\n Use `importlib.metadata.version(\"environs\")` instead.\n\n## 10.3.0 (2024-01-11)\n\nFeatures:\n\n- `Env.__repr__` and `Env.__str__` no longer display environment variables, to prevent accidental exfiltration of sensitive data ([#292](https://github.com/sloria/environs/issues/292)).\n Thanks [mro-rhansen2](https://github.com/mro-rhansen2) for the suggestion.\n\nBug fixes:\n\n- Fix passing `None` as default to `env.list` ([#298](https://github.com/sloria/environs/issues/298)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for reporting.\n\n## 10.2.0 (2024-01-09)\n\nFeatures:\n\n- `env.read_env` returns `False` if file not found ([#294](https://github.com/sloria/environs/issues/294)).\n Thanks [rptaylor](https://github.com/rptaylor) for the suggestion.\n\n## 10.1.0 (2024-01-08)\n\nFeatures:\n\n- Allow `default` for `env.json` to be a `dict` or `list` ([#240](https://github.com/sloria/environs/pull/240)).\n Thanks [tomgrin10](https://github.com/tomgrin10) and [bvanelli](https://github.com/bvanelli) for the PRs.\n\nOther changes:\n\n- Test against Python 3.12.\n\n## 10.0.0 (2023-12-15)\n\nFeatures:\n\n- Add `delimiter` argument to `env.dict` ([#277](https://github.com/sloria/environs/pull/277)). Thanks [gregoiredx](https://github.com/gregoiredx) for the PR.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for EOL Python 3.6 and 3.7.\n- Test against Python 3.11.\n- Migrate to setup.cfg. Thanks [deronnax](https://github.com/deronnax) for the PR.\n\n## 9.5.0 (2022-01-30)\n\nFeatures:\n\n- Allow callables or custom marshmallow fields to be passed to `subcast`, `subcast_keys`, and `subcast_values`. ([#241](https://github.com/sloria/environs/pull/241)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.4.0 (2022-01-04)\n\nBug fixes:\n\n- Address warning about passing metadata in newer versions of marshmallow.\n\nOther changes:\n\n- Test against Python 3.10.\n\n## 9.3.5 (2021-11-14)\n\nBug fixes:\n\n- Fix `env.url` and other parsers that take field keyword arguments ([#227](https://github.com/sloria/environs/issues/227)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.4 (2021-10-03)\n\nBug fixes:\n\n- Allow default for `env.path` to be a `pathlib.Path` ([#228](https://github.com/sloria/environs/issues/228)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.3 (2021-08-08)\n\nBug fixes:\n\n- Fix compatibility with marshmallow>=3.13.0\n so that no DeprecationWarnings are raised ([#224](https://github.com/sloria/environs/issues/224)).\n\n## 9.3.2 (2021-03-28)\n\nBug fixes:\n\n- Handle JSON decoding errors when using `env.json` ([#212](https://github.com/sloria/environs/pull/212)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.3.1 (2021-02-07)\n\nBug fixes:\n\n- Apply variable expansion to default values ([#204](https://github.com/sloria/environs/pull/204)).\n Thanks [rjcohn](https://github.com/rjcohn) for the PR.\n\n## 9.3.0 (2020-12-26)\n\nDeprecations:\n\n- Rename `subcast_key` argument of `env.dict` to `subcast_keys`\n for consistency with `subcast_values`. `subcast_key` is deprecated.\n\n## 9.2.0 (2020-11-07)\n\nFeatures:\n\n- Add time parser ([#191](https://github.com/sloria/environs/issues/191)).\n\n## 9.1.0 (2020-11-06)\n\nFeatures:\n\n- Add `enum` parser ([#185](https://github.com/sloria/environs/pull/185)).\n- Add `delimiter` param to `env.list`\n ([#184](https://github.com/sloria/environs/pull/184)).\n\nThanks [tomgrin10](https://github.com/tomgrin10) for the PRs.\n\nBug fixes:\n\n- Loosen `ParserMethod` typing ([#186 (comment)](https://github.com/sloria/environs/issues/186#issuecomment-723163520)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for the PR.\n\nOther changes:\n\n- When using deferred validation (`eager=False`), parser methods return `None`\n for missing or invalid values.\n _Note_: This may break code that depended on parser methods returning `marshmallow.missing`,\n but this behavior was not documented nor tested and therefore is not considered public API.\n\n## 9.0.0 (2020-10-31)\n\n- _Backwards-incompatible_: Rename `subcast` param of `env.dict` to `subcast_values` for consistency with `subcast_keys`.\n- _Backwards-incompatible_: Remove variable proxying. Use variable expansion instead (see 8.1.0 release notes below)\n ([#175](https://github.com/sloria/environs/issues/175)).\n- _Backwards-incompatible_: Drop support for marshmallow 2 and Python 3.5,\n which are both EOL ([#174](https://github.com/sloria/environs/issues/174)).\n\n## 8.1.0 (2020-10-31)\n\nFeatures:\n\n- Add support for variable expansion, e.g. `MY_VAR=${MY_OTHER_VAR:-mydefault}` ([#164](https://github.com/sloria/environs/issues/164)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\nDeprecations:\n\n- Variable proxying using the `{{VAR}}` syntax is deprecated\n and will be removed in environs 9.0.0.\n Use variable expansion using `${VAR}` instead.\n\n```bash\n# Before\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN={{MAILGUN_LOGIN}}\n\n# After\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN=${MAILGUN_LOGIN}\n```\n\n```python\nfrom environs import Env\n\nenv = Env(expand_vars=True)\n\nSMTP_LOGIN = env.str(\"SMTP_LOGIN\") # => 'sloria'\n```\n\nBug fixes:\n\n- Fix deferred validation behavior for `dj_db_url`, `dj_email_url`, `dj_cache_url`,\n and custom parsers ([#121](https://github.com/sloria/environs/issues/121)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for reporting.\n\nOther changes:\n\n- Test against Python 3.9.\n- Remove usage of implicit `typing.Optional` ([171](https://github.com/sloria/environs/issues/171)).\n\n## 8.0.0 (2020-05-27)\n\nBug fixes:\n\n- Fix behavior of recurse=True when custom filepath is passed to `env.read_env`\n ([#100](https://github.com/sloria/environs/issues/100)). Thanks [ribeaud](https://github.com/ribeaud) and [timoklimmer](https://github.com/sloria/environs/pull/157) for the help.\n\nOther changes:\n\n- _Backwards-incompatible_: As a result of the above fix, passing a directory to `env.read_env` is no longer allowed and will raise a `ValueError`.\n Only file paths or file names should be passed.\n\n## 7.4.0 (2020-04-18)\n\n- Add `subcast_key` argument to `env.dict` ([#151](https://github.com/sloria/environs/issues/151)).\n Thanks [AugPro](https://github.com/AugPro) for the suggestion and PR.\n\n## 7.3.1 (2020-03-22)\n\n- Fix error when parsing empty list with subcast\n [#137](https://github.com/sloria/environs/issues/137).\n Thanks [sabdouni] for the catch and patch.\n\n## 7.3.0 (2020-03-01)\n\n- `log_level` accepts lower-cased log level names and rejects invalid\n names ([#138](https://github.com/sloria/environs/pull/138)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\n## 7.2.0 (2020-02-09)\n\n- Add `dj_cache_url` for caching Django cache URLs (requires installing with `[django]`)\n ([#126](https://github.com/sloria/environs/issues/126)).\n Thanks [epicserve](https://github.com/epicserve) for the suggestion and PR.\n\n## 7.1.0 (2019-12-07)\n\n- Improve typings and run mypy with dependencies type annotations ([#115](https://github.com/sloria/environs/pull/115)).\n- Distribute types per PEP 561 ([#116](https://github.com/sloria/environs/pull/116)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 7.0.0 (2019-12-02)\n\n- _Backwards-incompatible_: Remove `stream` argument from `read_env`,\n since it had no effect ([#114](https://github.com/sloria/environs/pull/114)).\n- _Backwards-incompatible_: `Env.read_env` consistently returns `None`\n ([#111](https://github.com/sloria/environs/pull/111)).\n- Remove unnecessary `__str__` definition ([#112](https://github.com/sloria/environs/pull/112)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 6.1.0 (2019-11-03)\n\nFeatures:\n\n- Add deferred validation via the `eager` parameter and `env.seal()` ([#56](https://github.com/sloria/environs/issues/56)).\n Thanks [robertlagrant](https://github.com/robertlagrant) for the suggestion.\n\nOther changes:\n\n- Test against Python 3.8 ([#108](https://github.com/sloria/environs/pull/108)).\n\n## 6.0.0 (2019-09-22)\n\nFeatures:\n\n- Default parser methods are now defined as bound methods.\n This enables static analysis features, e.g. autocomplete ([#103](https://github.com/sloria/environs/issues/103)).\n Thanks [rugleb](https://github.com/rugleb) for the suggestion.\n _Backwards-incompatible_: As a result of this change, adding a parser name that is the same as an existing method\n will result in an error being raised.\n\n```python\nimport environs\n\nenv = environs.Env()\n\n\n# Below conflicts with built-in `url` method.\n# In <6.0.0, this would override the built-in method.\n# In >=6.0.0, this raises an error:\n# environs.ParserConflictError: Env already has a method with name 'url'. Use a different name.\n@env.parser_for(\"url\")\ndef https_url(value):\n return \"https://\" + value\n```\n\nBug fixes:\n\n- Fix error message for prefixed variables ([#102](https://github.com/sloria/environs/issues/102)).\n Thanks [AGeekInside](https://github.com/AGeekInside) for reporting.\n\nOther changes:\n\n- _Backwards-incompatible_: Rename `Env.__parser_map__` to `Env.__custom_parsers__`.\n\n## 5.2.1 (2019-08-08)\n\nBug fixes:\n\n- Fix behavior when recursively searching for a specified file\n ([#96](https://github.com/sloria/environs/issues/96)).\n Thanks [ribeaud](https://github.com/ribeaud) for the catch and patch.\n\n## 5.2.0 (2019-07-19)\n\nChanges:\n\n- Improve typings.\n\n## 5.1.0 (2019-07-13)\n\nFeatures:\n\n- Add `env.log_level` ([#7](https://github.com/sloria/environs/issues/7)).\n- Use `raise from` to improve tracebacks.\n\nOther changes:\n\n- Improve typings.\n\n## 5.0.0 (2019-07-06)\n\nFeatures:\n\n- Add `env.path` ([#81](https://github.com/sloria/environs/issues/81)).\n Thanks [umrashrf](https://github.com/umrashrf) for the suggestion.\n- Add type annotations.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for Python 2. If you use Python 2,\n you will need to use ve\n... [truncated 3425 chars]\n\n```\n\n### src/environs/__init__.py\n```python\nfrom __future__ import annotations\n\nimport collections\nimport contextlib\nimport functools\nimport inspect\nimport json as pyjson\nimport os\nimport re\nimport typing\nfrom collections.abc import Mapping\nfrom pathlib import Path\n\nimport marshmallow as ma\nfrom dotenv.main import _walk_to_root, load_dotenv\n\nfrom . import fields\nfrom .exceptions import (\n EnvError,\n EnvSealedError,\n EnvValidationError,\n ParserConflictError,\n)\n\nif typing.TYPE_CHECKING:\n import datetime as dt\n import decimal\n import uuid\n from urllib.parse import ParseResult\n\n from .types import (\n DictFieldMethod,\n EnumFieldMethod,\n ErrorMapping,\n FieldFactory,\n FieldMethod,\n ListFieldMethod,\n ParserMethod,\n Subcast,\n TimeDeltaFieldMethod,\n )\n\n try:\n from dj_database_url import DBConfig\n except ImportError:\n pass\n\n__all__ = [\"Env\", \"EnvError\", \"FileAwareEnv\", \"ValidationError\", \"env\"]\n\n_T = typing.TypeVar(\"_T\")\n_StrType = str\n_BoolType = bool\n_IntType = int\n_ListType = list\n_DictType = dict\n\n_EXPANDED_VAR_PATTERN = re.compile(r\"(? typing.Any:\n def method(\n self: Env,\n name: str,\n default: typing.Any = ...,\n subcast: Subcast[_T] | None = None,\n *,\n # Subset of relevant marshmallow.Field kwargs\n validate: (\n typing.Callable[[typing.Any], typing.Any]\n | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]\n | None\n ) = None,\n # Additional kwargs are passed to Field constructor\n **kwargs,\n ) -> _T | None:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\",\n )\n load_default = default if default is not Ellipsis else ma.missing\n preprocess_kwargs = {\n name: kwargs.pop(name) for name in preprocess_kwarg_names if name in kwargs\n }\n if isinstance(field_or_factory, type) and issubclass(\n field_or_factory,\n ma.fields.Field,\n ):\n field = field_or_factory(\n validate=validate,\n load_default=load_default,\n **kwargs,\n )\n else:\n parsed_subcast = _make_subcast_field(subcast) if subcast else ma.fields.Raw\n field = typing.cast(\"FieldFactory\", field_or_factory)(\n subcast=parsed_subcast,\n validate=validate,\n load_default=load_default,\n )\n parsed_key, value, proxied_key = self._get_from_environ(name, default=Ellipsis)\n self._fields[parsed_key] = field\n source_key = proxied_key or parsed_key\n if value is Ellipsis:\n if default is not Ellipsis:\n self._values[parsed_key] = default\n return default\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set',\n )\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n try:\n if preprocess:\n value = preprocess(value, **preprocess_kwargs)\n value = field.deserialize(value)\n except ma.ValidationError as error:\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n error.messages,\n ) from error\n self._errors[parsed_key].extend(error.messages)\n else:\n self._values[parsed_key] = value\n return typing.cast(\"_T | None\", value)\n\n method.__name__ = method_name\n return method\n\n\ndef _func2method(func: typing.Callable[..., _T], method_name: str) -> typing.Any:\n def method(\n self: Env,\n name: str,\n default: typing.Any = ...,\n **kwargs,\n ) -> _T | None:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\",\n )\n parsed_key, raw_value, proxied_key = self._get_from_environ(name, default)\n self._fields[parsed_key] = ma.fields.Raw()\n source_key = proxied_key or parsed_key\n if raw_value is Ellipsis:\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set',\n )\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n if raw_value or raw_value == \"\": # noqa: SIM108\n value = raw_value\n else:\n value = None\n try:\n value = func(raw_value, **kwargs)\n except (EnvError, ma.ValidationError) as error:\n messages = (\n error.messages\n if isinstance(error, ma.ValidationError)\n else [error.args[0]]\n )\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n messages,\n ) from error\n self._errors[parsed_key].extend(messages)\n else:\n self._values[parsed_key] = value\n return typing.cast(\"_T | None\", value)\n\n method.__name__ = method_name\n return method\n\n\ndef _make_subcast_field(\n subcast: Subcast,\n) -> type[ma.fields.Field]:\n if isinstance(subcast, type) and subcast in ma.Schema.TYPE_MAPPING:\n inner_field = ma.Schema.TYPE_MAPPING[subcast]\n elif isinstance(subcast, type) and issubclass(subcast, ma.fields.Field):\n inner_field = subcast\n elif callable(subcast):\n\n class SubcastField(ma.fields.Field):\n def _deserialize(self, value, *args, **kwargs):\n return subcast(value)\n\n inner_field = SubcastField\n else:\n inner_field = ma.fields.Raw\n return inner_field\n\n\ndef _make_list_field(*, subcast: Subcast | None, **kwargs) -> ma.fields.List:\n inner_field = _make_subcast_field(subcast) if subcast else ma.fields.Raw\n return ma.fields.List(inner_field, **kwargs)\n\n\ndef _preprocess_list(\n value: str | typing.Iterable,\n *,\n delimiter: str = \",\",\n **kwargs,\n) -> typing.Iterable:\n if ma.utils.is_iterable_but_not_string(value) or value is None:\n return value\n return typing.cast(\"str\", value).split(delimiter) if value != \"\" else []\n\n\ndef _preprocess_dict(\n value: str | typing.Mapping,\n *,\n subcast_keys: Subcast | None = None,\n subcast_values: Subcast | None = None,\n delimiter: str = \",\",\n key_value_delimiter: str = \"=\",\n **kwargs,\n) -> typing.Mapping:\n if isinstance(value, Mapping):\n return value\n subcast_keys_instance: ma.fields.Field\n if subcast_keys:\n subcast_keys_instance = _make_subcast_field(subcast_keys)(**kwargs)\n else:\n subcast_keys_instance = ma.fields.Raw()\n subcast_values_instance: ma.fields.Field\n if subcast_values:\n subcast_values_instance = _make_subcast_field(subcast_values)(**kwargs)\n else:\n subcast_values_instance = ma.fields.Raw()\n\n return {\n subcast_keys_instance.deserialize(\n key.strip(),\n ): subcast_values_instance.deserialize(val.strip())\n for key, val in (\n item.split(key_value_delimiter, 1) for item in value.split(delimiter) if value\n )\n }\n\n\ndef _preprocess_json(value: str | typing.Mapping | list, **kwargs):\n try:\n if isinstance(value, str):\n return pyjson.loads(value)\n if isinstance(value, (dict, list)) or value is None:\n return value\n raise ma.ValidationError(\"Not valid JSON.\")\n except pyjson.JSONDecodeError as error:\n raise ma.ValidationError(\"Not valid JSON.\") from error\n\n\ndef _dj_db_url_parser(value: str, **kwargs) -> DBConfig:\n try:\n import dj_database_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_db_url parser requires the dj-database-url package. \"\n \"You can install it with: pip install dj-database-url\",\n ) from error\n try:\n return dj_database_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid database URL.\") from error\n\n\ndef _dj_email_url_parser(value: str, **kwargs) -> dict:\n try:\n import dj_email_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_email_url parser requires the dj-email-url package. \"\n \"You can install it with: pip install dj-email-url\",\n ) from error\n try:\n return dj_email_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid email URL.\") from error\n\n\ndef _dj_cache_url_parser(value: str, **kwargs) -> dict:\n try:\n import django_cache_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_cache_url parser requires the django-cache-url package. \"\n \"You can install it with: pip install django-cache-url\",\n ) from error\n try:\n return django_cache_url.parse(value, **kwargs)\n except Exception as error:\n # django_cache_url may raise Exception(\"Unknown backend...\")\n # so use that error message in the validation error\n raise ma.ValidationError(error.args[0]) from error\n\n\nclass Env:\n \"\"\"An environment variable reader.\"\"\"\n\n __call__: FieldMethod[typing.Any] = _field2method(ma.fields.Raw, \"__call__\")\n\n int: FieldMethod[int] = _field2method(ma.fields.Int, \"int\")\n bool: FieldMethod[bool] = _field2method(ma.fields.Bool, \"bool\")\n str: FieldMethod[str] = _field2method(ma.fields.Str, \"str\")\n float: FieldMethod[float] = _field2method(ma.fields.Float, \"float\")\n decimal: FieldMethod[decimal.Decimal] = _field2method(ma.fields.Decimal, \"decimal\")\n list: ListFieldMethod = _field2method(\n _make_list_field,\n \"list\",\n preprocess=_preprocess_list,\n preprocess_kwarg_names=(\"subcast\", \"delimiter\"),\n )\n dict: DictFieldMethod = _field2method(\n ma.fields.Dict,\n \"dict\",\n preprocess=_preprocess_dict,\n preprocess_kwarg_names=(\n \"subcast_keys\",\n \"subcast_key\",\n \"subcast_values\",\n \"delimiter\",\n \"key_value_delimiter\",\n ),\n )\n json: FieldMethod[_ListType | _DictType] = _field2method(\n ma.fields.Raw,\n \"json\",\n preprocess=_preprocess_json,\n )\n datetime: FieldMethod[dt.datetime] = _field2method(ma.fields.DateTime, \"datetime\")\n date: FieldMethod[dt.date] = _field2method(ma.fields.Date, \"date\")\n time: FieldMethod[dt.time] = _field2method(ma.fields.Time, \"time\")\n timedelta: TimeDeltaFieldMethod = _field2method(fields.TimeDelta, \"timedelta\")\n path: FieldMethod[Path] = _field2method(fields.Path, \"path\")\n log_level: FieldMethod[_IntType] = _field2method(fields.LogLevel, \"log_level\")\n\n uuid: FieldMethod[uuid.UUID] = _field2method(ma.fields.UUID, \"uuid\")\n url: FieldMethod[ParseResult] = _field2method(fields.Url, \"url\")\n\n enum: EnumFieldMethod = _field2method(ma.fields.Enum, \"enum\")\n dj_db_url = _func2method(_dj_db_url_parser, \"dj_db_url\")\n dj_email_url = _func2method(_dj_email_url_parser, \"dj_email_url\")\n dj_cache_url = _func2method(_dj_cache_url_parser, \"dj_cache_url\")\n\n def __init__(\n self,\n *,\n eager: _BoolType = True,\n expand_vars: _BoolType = False,\n prefix: _StrType | None = None,\n ):\n self.eager = eager\n self._sealed: bool = False\n self.expand_vars = expand_vars\n self._fields: dict[_StrType, ma.fields.Field] = {}\n self._values: dict[_StrType, typing.Any] = {}\n self._errors: ErrorMapping = collections.defaultdict(list)\n self._prefix: _StrType | None = prefix\n self.__custom_parsers__: dict[_StrType, ParserMethod] = {}\n\n def __repr__(self) -> _StrType:\n return f\"<{self.__class__.__name__}(eager={self.eager}, expand_vars={self.expand_vars})>\"\n\n @staticmethod\n def read_env(\n path: _StrType | Path | None = None,\n *,\n recurse: _BoolType = True,\n verbose: _BoolType = False,\n override: _BoolType = False,\n return_path: _BoolType = False,\n ) -> _BoolType | _StrType | None:\n \"\"\"Read a .env file into os.environ.\n\n If .env is not found in the directory from which this method is called,\n the default behavior is to recurse up the directory tree until a .env\n file is found. If you do not wish to recurse up the tree, you may pass\n False as a second positional argument.\n \"\"\"\n env_path = None\n is_env_loaded = False\n if path is None:\n # By default, start search from the same directory this function is called\n current_frame = inspect.currentframe()\n if current_frame is None:\n raise RuntimeError(\"Could not get current call frame.\")\n frame = current_frame.f_back\n assert frame is not None # noqa: S101\n caller_dir = Path(frame.f_code.co_filename).parent.resolve()\n start = caller_dir / \".env\"\n else:\n if Path(path).is_dir():\n raise ValueError(\"path must be a filename, not a directory.\")\n start = Path(path)\n if recurse:\n start_dir, env_name = os.path.split(start)\n if not start_dir: # Only a filename was given\n start_dir = os.getcwd()\n for dirname in _walk_to_root(start_dir):\n check_path = Path(dirname) / env_name\n if check_path.exists():\n is_env_loaded = load_dotenv(\n check_path,\n verbose=verbose,\n override=override,\n )\n env_path = str(check_path)\n break\n\n else:\n is_env_loaded = load_dotenv(str(start), verbose=verbose, override=override)\n env_path = str(start)\n\n if return_path:\n return env_path\n return is_env_loaded\n\n @contextlib.contextmanager\n def prefixed(self, prefix: _StrType) -> typing.Iterator[Env]:\n \"\"\"Context manager for parsing envvars with a common prefix.\"\"\"\n try:\n old_prefix = self._prefix\n if old_prefix is None:\n self._prefix = prefix\n else:\n self._prefix = f\"{old_prefix}{prefix}\"\n yield self\n finally:\n # explicitly reset the stored prefix on completion and exceptions\n self._prefix = None\n self._prefix = old_prefix\n\n def seal(self):\n \"\"\"Validate parsed values and prevent new values from being added.\n\n :raises: environs.EnvValidationError\n \"\"\"\n self._sealed = True\n if self._errors:\n error_messages = dict(self._errors)\n self._errors = {}\n raise EnvValidationError(\n f\"Environment variables invalid: {error_messages}\",\n error_messages,\n )\n\n def __getattr__(self, name: _StrType):\n try:\n return functools.partial(self.__custom_parsers__[name], self)\n except KeyError as error:\n raise AttributeError(f\"{self} has no attribute\n... [truncated 5867 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "sloria__environs-1a47a3658bf7", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/sloria__environs-1a47a3658bf7", "repo_key": "sloria__environs", "repo": "sloria/environs", "base_commit": "f678dabd2ebb32a22a90f439d8518f8c2ddcb60c", "source_files": ["CHANGELOG.md", "src/environs/__init__.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Environment variables from `os.environ` are overridden by `.env` files\n\n## Description\nWhen an environment variable is already set in the system's `os.environ` (e.g., from the shell or system-wide configuration), and the same variable is also defined within a `.env` file, the value from the `.env` file incorrectly takes precedence.\n\n**Reproduction:**\n1. Set an environment variable in your shell: `export MY_VAR=from_shell`\n2. Create a `.env` file with the same variable: `echo \"MY_VAR=from_dot_env\" > .env`\n3. Load environment variables (e.g., using a library that processes `.env` files).\n4. Check the value of `MY_VAR`.\n\n**Actual Behavior:** The application reads `MY_VAR` as `from_dot_env`.\n**Expected Behavior:** The application should read `MY_VAR` as `from_shell`, respecting the precedence of `os.environ` over `.env` files.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `4654e60b62aa` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 15.0.0 (2026-03-31)\n\nFeatures:\n\n- `Env.read_env` no longer mutates `os.environ` ([#393](https://github.com/sloria/environs/issues/393)). Values from `.env` files are loaded into the `Env` instance only. This comes with **two breaking changes**:\n - `Env.read_env` is now an instance method rather than a `@staticmethod`.\n `Env.read_env()` -> `env.read_env()`\n - The `verbose` parameter of `read_env` is been removed.\n\nOther changes:\n\n- Drop support for marshmallow 3, which is EOL. marshmallow>=4.0.0 is supported.\n- Minor typing improvements ([#463](https://github.com/sloria/environs/pull/463)).\n\n## 14.6.0 (2026-02-19)\n\nBug fixes:\n\n- Fix variable expansion with other characters ([#359](https://github.com/sloria/environs/issues/359)).\n Thanks [flymanzhao](https://github.com/flymanzhao) for reporting and [veeceey](https://github.com/veeceey) for the PR.\n\nOther changes:\n\n- Update lowest supported marshmallow version to 3.26.2 ([#448](https://github.com/sloria/environs/pull/448)).\n Thanks [whyscream](https://github.com/whyscream) for the PR.\n\n## 14.5.0 (2025-11-02)\n\nFeatures:\n\n- Add `strip_whitespace` param to `FileAwareEnv` ([#431](https://github.com/sloria/environs/issues/431)).\n Thanks [eandersons](https://github.com/eandersons) for the suggestion and PR.\n\nOther changes:\n\n- Drop support for Python 3.9, which is EOL.\n\n## 14.4.0 (2025-10-29)\n\nFeatures:\n\n- Add support for ISO 8601 durations to `env.timedelta`. ([#434](https://github.com/sloria/environs/pull/434)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for the suggestion and PR.\n\n## 14.3.0 (2025-08-01)\n\nFeatures:\n\n- Add `environs.FileAwareEnv` for reading secret files ([#410](https://github.com/sloria/environs/pull/410)).\n Thanks [holtgrewe](https://github.com/holtgrewe) for the suggestion.\n Thanks [whyscream](https://github.com/whyscream) and [avilaton](https://github.com/avilaton) for the PRs.\n\n## 14.2.0 (2025-05-22)\n\nFeatures:\n\n- Add `key_value_delimiter` argument to `env.dict` ([#419](https://github.com/sloria/environs/issues/419)).\n Thanks [jerr0328](https://github.com/jerr0328) for the suggestion and PR.\n\n## 14.1.1 (2025-02-10)\n\nBug fixes:\n\n- Typing: Fix typing for `env.list` and `env.dict` to properly handle\n `default` and `subcast` arguments ([#406](https://github.com/sloria/environs/issues/406)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for the PR.\n- Add `env` to `__all__` ([#396](https://github.com/sloria/environs/issues/396)).\n Thanks [daveflr](https://github.com/daveflr) for reporting.\n\nChanges:\n\n- _Backwards-incompatible_: `recurse`, `verbose`, `override`,\n and `return_path` parameters to `Env.read_env` are now keyword-only.\n- _Backwards-incompatible_: The `required` argument to parser methods\n is removed. Call a parser method without a default value to make it required.\n\n## 14.1.0 (2025-01-10)\n\nFeatures:\n\n- Add `prefix` parameter to `Env` constructor ([#384](https://github.com/sloria/environs/issues/384)).\n Thanks [arthurc0102](https://github.com/sloria/environs/issues/384)\n for the suggestion.\n- Re-export `validate` module from marshmallow ([#385](https://github.com/sloria/environs/issues/385)).\n\nBug fixes:\n\n- Typing: Fix typing for `Env.enum` to allow `by_value` to be passed ([#386](https://github.com/sloria/environs/issues/386)).\n\n## 14.0.0 (2025-01-07)\n\nFeatures:\n\n- Add `env` singleton ([#194]).\n Thanks [AndBondStyle](https://github.com/AndBondStyle) for the suggestion.\n\n```python\nfrom environs import env\n```\n\nChanges:\n\n- `default` values are expected to be their in their deserialized form.\n _Backwards-incompatible_: Passing serialized values to `default`\n is no longer supported.\n\n```python\nfrom datetime import date, timedelta\nimport environs\n\n# DO\nenable_login = env.bool(\"ENABLE_LOGIN\", True)\nttl = env.timedelta(\"TTL\", default=timedelta(seconds=600))\nrelease_date = env.date(\"RELEASE\", date(2025, 1, 7))\nnumbers = env.list(\"FOO\", [1.0, 2.0, 3.0], subcast=float)\n\n# DON'T\nenable_login = env.bool(\"ENABLE_LOGIN\", \"true\")\nttl = env.timedelta(\"TTL\", default=600)\nrelease_date = env.date(\"RELEASE\", \"2025-01-07\")\nnumbers = env.list(\"NUMBERS\", \"1,2,42\", subcast=float)\n```\n\nThe exceptions to this rule are the Django-related functions, which\naccept string defaults.\n\n```python\nDATABASE_URL = env.dj_db_url(\"DATABASE_URL\", default=\"postgresql://localhost:5432/mydb\")\n```\n\nThis fixes [#297](https://github.com/sloria/environs/issues/297)\nand [#270](https://github.com/sloria/environs/issues/270).\n\n## 13.0.0 (2025-01-07)\n\nFeatures:\n\n- Typing: Add type hints for parser methods ([#367](https://github.com/sloria/environs/issues/367)).\n Thanks [OkeyDev](https://github/OkeyDev) for the PR.\n- Add `by_value` param to `Env.enum`. Pass `by_value=True` to parse Enum by values instead of names.\n\nOther changes:\n\n- Drop support for marshmallow<3.18.0.\n- _Backwards-incompatible_: Remove `load_default` param from parser methods. Use `default` instead.\n- _Backwards-incompatible_: Rename `Env.enum`'s `type` param to `enum`.\n- _Backwards-incompatible_: Remove `ignore_case` param from `Env.enum`.\n- _Backwards-incompatible_: Remove\n `allow_none`, `error_messages`, and `metadata` params from parser methods.\n\n## 12.0.0 (2025-01-06)\n\nFeatures:\n\n- `Env.enum` allows passing an `Enum` as `default`.\n\nOther changes:\n\n- Support marshmallow 4.\n- Support Python 3.9-3.13.\n- _Backwards-incompatible_: Make `Field` classes private. Users should\n not need to access these.\n\n## 11.2.1 (2024-11-20)\n\nBug fixes:\n\n- Fix passing non-string default values to `Env.timedelta` ([#369](https://github.com/sloria/environs/pull/369)).\n Thanks [tcleonard](https://github.com/tcleonard) for reporting and\n thanks [ddelange](https://github.com/ddelange) for the PR.\n- Fix `Env.read_env(recurse=True)` so that it returns as soon as a `.env`\n file is found ([#370](https://github.com/sloria/environs/pull/370)).\n Thanks [senese](https://github.com/senese) for the PR.\n\n## 11.2.0 (2024-11-14)\n\nFeatures:\n\n- `Env.timedelta` can parse [GEP-2257](https://gateway-api.sigs.k8s.io/geps/gep-2257/)\n duration strings ([#366](https://github.com/sloria/environs/pull/366)).\n Thanks [ddelange](https://github.com/ddelange) for the PR.\n\n## 11.1.0 (2024-11-11)\n\nFeatures:\n\n- Add `return_path` argument to `Env.read_env` to return the path of the\n parsed file ([#362](https://github.com/sloria/environs/issues/362)).\n Thanks [senese](https://github.com/senese) for the suggestion and PR.\n NOTE: This is added as a backwards-compatible change that is scheduled to be\n removed in 12.0.0. The path will stored as an attribute of `Env`.\n\n## 11.0.0 (2024-03-04)\n\nFixes:\n\n- Prevent `DeprecationWarning` getting raised by marshmallow 3.21.0 (:issue:`333`).\n\nOther changes:\n\n- Remove `subcast_key` argument of `env.dict`. Use `subcast_keys` instead.\n- Bump minimum required marshmallow version to 3.13.0.\n- Remove `missing` argument from `Env` methods. Use `default` instead.\n- Remove `subcast` argument from `Env` methods that don't use it.\n- _Backwards-incompatible_: Remove `environs.__version__` variable.\n Use `importlib.metadata.version(\"environs\")` instead.\n\n## 10.3.0 (2024-01-11)\n\nFeatures:\n\n- `Env.__repr__` and `Env.__str__` no longer display environment variables, to prevent accidental exfiltration of sensitive data ([#292](https://github.com/sloria/environs/issues/292)).\n Thanks [mro-rhansen2](https://github.com/mro-rhansen2) for the suggestion.\n\nBug fixes:\n\n- Fix passing `None` as default to `env.list` ([#298](https://github.com/sloria/environs/issues/298)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for reporting.\n\n## 10.2.0 (2024-01-09)\n\nFeatures:\n\n- `env.read_env` returns `False` if file not found ([#294](https://github.com/sloria/environs/issues/294)).\n Thanks [rptaylor](https://github.com/rptaylor) for the suggestion.\n\n## 10.1.0 (2024-01-08)\n\nFeatures:\n\n- Allow `default` for `env.json` to be a `dict` or `list` ([#240](https://github.com/sloria/environs/pull/240)).\n Thanks [tomgrin10](https://github.com/tomgrin10) and [bvanelli](https://github.com/bvanelli) for the PRs.\n\nOther changes:\n\n- Test against Python 3.12.\n\n## 10.0.0 (2023-12-15)\n\nFeatures:\n\n- Add `delimiter` argument to `env.dict` ([#277](https://github.com/sloria/environs/pull/277)). Thanks [gregoiredx](https://github.com/gregoiredx) for the PR.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for EOL Python 3.6 and 3.7.\n- Test against Python 3.11.\n- Migrate to setup.cfg. Thanks [deronnax](https://github.com/deronnax) for the PR.\n\n## 9.5.0 (2022-01-30)\n\nFeatures:\n\n- Allow callables or custom marshmallow fields to be passed to `subcast`, `subcast_keys`, and `subcast_values`. ([#241](https://github.com/sloria/environs/pull/241)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.4.0 (2022-01-04)\n\nBug fixes:\n\n- Address warning about passing metadata in newer versions of marshmallow.\n\nOther changes:\n\n- Test against Python 3.10.\n\n## 9.3.5 (2021-11-14)\n\nBug fixes:\n\n- Fix `env.url` and other parsers that take field keyword arguments ([#227](https://github.com/sloria/environs/issues/227)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.4 (2021-10-03)\n\nBug fixes:\n\n- Allow default for `env.path` to be a `pathlib.Path` ([#228](https://github.com/sloria/environs/issues/228)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.3 (2021-08-08)\n\nBug fixes:\n\n- Fix compatibility with marshmallow>=3.13.0\n so that no DeprecationWarnings are raised ([#224](https://github.com/sloria/environs/issues/224)).\n\n## 9.3.2 (2021-03-28)\n\nBug fixes:\n\n- Handle JSON decoding errors when using `env.json` ([#212](https://github.com/sloria/environs/pull/212)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.3.1 (2021-02-07)\n\nBug fixes:\n\n- Apply variable expansion to default values ([#204](https://github.com/sloria/environs/pull/204)).\n Thanks [rjcohn](https://github.com/rjcohn) for the PR.\n\n## 9.3.0 (2020-12-26)\n\nDeprecations:\n\n- Rename `subcast_key` argument of `env.dict` to `subcast_keys`\n for consistency with `subcast_values`. `subcast_key` is deprecated.\n\n## 9.2.0 (2020-11-07)\n\nFeatures:\n\n- Add time parser ([#191](https://github.com/sloria/environs/issues/191)).\n\n## 9.1.0 (2020-11-06)\n\nFeatures:\n\n- Add `enum` parser ([#185](https://github.com/sloria/environs/pull/185)).\n- Add `delimiter` param to `env.list`\n ([#184](https://github.com/sloria/environs/pull/184)).\n\nThanks [tomgrin10](https://github.com/tomgrin10) for the PRs.\n\nBug fixes:\n\n- Loosen `ParserMethod` typing ([#186 (comment)](https://github.com/sloria/environs/issues/186#issuecomment-723163520)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for the PR.\n\nOther changes:\n\n- When using deferred validation (`eager=False`), parser methods return `None`\n for missing or invalid values.\n _Note_: This may break code that depended on parser methods returning `marshmallow.missing`,\n but this behavior was not documented nor tested and therefore is not considered public API.\n\n## 9.0.0 (2020-10-31)\n\n- _Backwards-incompatible_: Rename `subcast` param of `env.dict` to `subcast_values` for consistency with `subcast_keys`.\n- _Backwards-incompatible_: Remove variable proxying. Use variable expansion instead (see 8.1.0 release notes below)\n ([#175](https://github.com/sloria/environs/issues/175)).\n- _Backwards-incompatible_: Drop support for marshmallow 2 and Python 3.5,\n which are both EOL ([#174](https://github.com/sloria/environs/issues/174)).\n\n## 8.1.0 (2020-10-31)\n\nFeatures:\n\n- Add support for variable expansion, e.g. `MY_VAR=${MY_OTHER_VAR:-mydefault}` ([#164](https://github.com/sloria/environs/issues/164)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\nDeprecations:\n\n- Variable proxying using the `{{VAR}}` syntax is deprecated\n and will be removed in environs 9.0.0.\n Use variable expansion using `${VAR}` instead.\n\n```bash\n# Before\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN={{MAILGUN_LOGIN}}\n\n# After\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN=${MAILGUN_LOGIN}\n```\n\n```python\nfrom environs import Env\n\nenv = Env(expand_vars=True)\n\nSMTP_LOGIN = env.str(\"SMTP_LOGIN\") # => 'sloria'\n```\n\nBug fixes:\n\n- Fix deferred validation behavior for `dj_db_url`, `dj_email_url`, `dj_cache_url`,\n and custom parsers ([#121](https://github.com/sloria/environs/issues/121)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for reporting.\n\nOther changes:\n\n- Test against Python 3.9.\n- Remove usage of implicit `typing.Optional` ([171](https://github.com/sloria/environs/issues/171)).\n\n## 8.0.0 (2020-05-27)\n\nBug fixes:\n\n- Fix behavior of recurse=True when custom filepath is passed to `env.read_env`\n ([#100](https://github.com/sloria/environs/issues/100)). Thanks [ribeaud](https://github.com/ribeaud) and [timoklimmer](https://github.com/sloria/environs/pull/157) for the help.\n\nOther changes:\n\n- _Backwards-incompatible_: As a result of the above fix, passing a directory to `env.read_env` is no longer allowed and will raise a `ValueError`.\n Only file paths or file names should be passed.\n\n## 7.4.0 (2020-04-18)\n\n- Add `subcast_key` argument to `env.dict` ([#151](https://github.com/sloria/environs/issues/151)).\n Thanks [AugPro](https://github.com/AugPro) for the suggestion and PR.\n\n## 7.3.1 (2020-03-22)\n\n- Fix error when parsing empty list with subcast\n [#137](https://github.com/sloria/environs/issues/137).\n Thanks [sabdouni] for the catch and patch.\n\n## 7.3.0 (2020-03-01)\n\n- `log_level` accepts lower-cased log level names and rejects invalid\n names ([#138](https://github.com/sloria/environs/pull/138)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\n## 7.2.0 (2020-02-09)\n\n- Add `dj_cache_url` for caching Django cache URLs (requires installing with `[django]`)\n ([#126](https://github.com/sloria/environs/issues/126)).\n Thanks [epicserve](https://github.com/epicserve) for the suggestion and PR.\n\n## 7.1.0 (2019-12-07)\n\n- Improve typings and run mypy with dependencies type annotations ([#115](https://github.com/sloria/environs/pull/115)).\n- Distribute types per PEP 561 ([#116](https://github.com/sloria/environs/pull/116)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 7.0.0 (2019-12-02)\n\n- _Backwards-incompatible_: Remove `stream` argument from `read_env`,\n since it had no effect ([#114](https://github.com/sloria/environs/pull/114)).\n- _Backwards-incompatible_: `Env.read_env` consistently returns `None`\n ([#111](https://github.com/sloria/environs/pull/111)).\n- Remove unnecessary `__str__` definition ([#112](https://github.com/sloria/environs/pull/112)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 6.1.0 (2019-11-03)\n\nFeatures:\n\n- Add deferred validation via the `eager` parameter and `env.seal()` ([#56](https://github.com/sloria/environs/issues/56)).\n Thanks [robertlagrant](https://github.com/robertlagrant) for the suggestion.\n\nOther changes:\n\n- Test against Python 3.8 ([#108](https://github.com/sloria/environs/pull/108)).\n\n## 6.0.0 (2019-09-22)\n\nFeatures:\n\n- Default parser methods are now defined as bound methods.\n This enables static analysis features, e.g. autocomplete ([#103](https://github.com/sloria/environs/issues/103)).\n Thanks [rugleb](https://github.com/rugleb) for the suggestion.\n _Backwards-incompatible_: As a result of this change, adding a parser name that is the same as an existing method\n will result in an error being raised.\n\n```python\nimport environs\n\nenv = environs.Env()\n\n\n# Below conflicts with built-in `url` method.\n# In <6.0.0, this would override the built-in method.\n# In >=6.0.0, this raises an error:\n# environs.ParserConflictError: Env already has a method with name 'url'. Use a different name.\n@env.parser_for(\"url\")\ndef https_url(value):\n return \"https://\" + value\n```\n\nBug fixes:\n\n- Fix error message for prefixed variables ([#102](https://github.com/sloria/environs/issues/102)).\n Thanks [AGeekInside](https://github.com/AGeekInside) for reporting.\n\nOther changes:\n\n- _Backwards-\n... [truncated 4284 chars]\n\n```\n\n### src/environs/__init__.py\n```python\nfrom __future__ import annotations\n\nimport collections\nimport contextlib\nimport functools\nimport inspect\nimport json as pyjson\nimport os\nimport re\nimport typing\nfrom collections.abc import Mapping\nfrom pathlib import Path\n\nimport marshmallow as ma\nfrom dotenv.main import _walk_to_root, dotenv_values\n\nfrom . import fields\nfrom .exceptions import (\n EnvError,\n EnvSealedError,\n EnvValidationError,\n ParserConflictError,\n)\n\nif typing.TYPE_CHECKING:\n import datetime as dt\n import decimal\n import uuid\n from urllib.parse import ParseResult\n\n from .types import (\n DictFieldMethod,\n EnumFieldMethod,\n ErrorMapping,\n FieldFactory,\n FieldMethod,\n ListFieldMethod,\n ParserMethod,\n Subcast,\n TimeDeltaFieldMethod,\n )\n\n try:\n from dj_database_url import DBConfig\n except ImportError:\n pass\n\n__all__ = [\"Env\", \"EnvError\", \"FileAwareEnv\", \"ValidationError\", \"env\"]\n\n_T = typing.TypeVar(\"_T\")\n# Aliases for built-in types that are shadowed by Env class attributes\n_StrType: typing.TypeAlias = str\n_BoolType: typing.TypeAlias = bool\n_IntType: typing.TypeAlias = int\n_ListType: typing.TypeAlias = list\n_DictType: typing.TypeAlias = dict\n\n_EXPANDED_VAR_PATTERN = re.compile(r\"(? typing.Any:\n def method(\n self: Env,\n name: str,\n default: typing.Any = ...,\n subcast: Subcast[_T] | None = None,\n *,\n # Subset of relevant marshmallow.Field kwargs\n validate: (\n typing.Callable[[typing.Any], typing.Any]\n | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]\n | None\n ) = None,\n # Additional kwargs are passed to Field constructor\n **kwargs,\n ) -> _T | None:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\",\n )\n load_default = default if default is not Ellipsis else ma.missing\n preprocess_kwargs = {\n name: kwargs.pop(name) for name in preprocess_kwarg_names if name in kwargs\n }\n if isinstance(field_or_factory, type) and issubclass(\n field_or_factory,\n ma.fields.Field,\n ):\n field = field_or_factory(\n validate=validate,\n load_default=load_default,\n **kwargs,\n )\n else:\n parsed_subcast = _make_subcast_field(subcast) if subcast else ma.fields.Raw\n field = typing.cast(\"FieldFactory\", field_or_factory)(\n subcast=parsed_subcast,\n validate=validate,\n load_default=load_default,\n )\n parsed_key, value, proxied_key = self._get_from_environ(name, default=Ellipsis)\n self._fields[parsed_key] = field\n source_key = proxied_key or parsed_key\n if value is Ellipsis:\n if default is not Ellipsis:\n self._values[parsed_key] = default\n return default\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set',\n )\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n try:\n if preprocess:\n value = preprocess(value, **preprocess_kwargs)\n value = field.deserialize(value)\n except ma.ValidationError as error:\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n error.messages,\n ) from error\n self._errors[parsed_key].extend(error.messages)\n else:\n self._values[parsed_key] = value\n return typing.cast(\"_T | None\", value)\n\n method.__name__ = method_name\n return method\n\n\ndef _func2method(func: typing.Callable[..., _T], method_name: str) -> typing.Any:\n def method(\n self: Env,\n name: str,\n default: typing.Any = ...,\n **kwargs,\n ) -> _T | None:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\",\n )\n parsed_key, raw_value, proxied_key = self._get_from_environ(name, default)\n self._fields[parsed_key] = ma.fields.Raw()\n source_key = proxied_key or parsed_key\n if raw_value is Ellipsis:\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set',\n )\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n if raw_value or raw_value == \"\": # noqa: SIM108\n value = raw_value\n else:\n value = None\n try:\n value = func(raw_value, **kwargs)\n except (EnvError, ma.ValidationError) as error:\n messages = (\n error.messages\n if isinstance(error, ma.ValidationError)\n else [error.args[0]]\n )\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n messages,\n ) from error\n self._errors[parsed_key].extend(messages)\n else:\n self._values[parsed_key] = value\n return typing.cast(\"_T | None\", value)\n\n method.__name__ = method_name\n return method\n\n\ndef _make_subcast_field(\n subcast: Subcast,\n) -> type[ma.fields.Field]:\n if isinstance(subcast, type) and subcast in ma.Schema.TYPE_MAPPING:\n inner_field = ma.Schema.TYPE_MAPPING[subcast]\n elif isinstance(subcast, type) and issubclass(subcast, ma.fields.Field):\n inner_field = subcast\n elif callable(subcast):\n\n class SubcastField(ma.fields.Field):\n def _deserialize(self, value, *args, **kwargs):\n if not isinstance(value, str):\n return value\n return subcast(value) # type: ignore[operator]\n\n inner_field = SubcastField\n else:\n inner_field = ma.fields.Raw\n return inner_field\n\n\ndef _make_list_field(*, subcast: Subcast | None, **kwargs) -> ma.fields.List:\n inner_field = _make_subcast_field(subcast) if subcast else ma.fields.Raw\n return ma.fields.List(inner_field, **kwargs)\n\n\ndef _preprocess_list(\n value: str | typing.Iterable,\n *,\n delimiter: str = \",\",\n **kwargs,\n) -> typing.Iterable:\n if ma.utils.is_iterable_but_not_string(value) or value is None:\n return value\n return typing.cast(\"str\", value).split(delimiter) if value != \"\" else []\n\n\ndef _preprocess_dict(\n value: str | typing.Mapping,\n *,\n subcast_keys: Subcast | None = None,\n subcast_values: Subcast | None = None,\n delimiter: str = \",\",\n key_value_delimiter: str = \"=\",\n **kwargs,\n) -> typing.Mapping:\n if isinstance(value, Mapping):\n return value\n subcast_keys_instance: ma.fields.Field\n if subcast_keys:\n subcast_keys_instance = _make_subcast_field(subcast_keys)(**kwargs)\n else:\n subcast_keys_instance = ma.fields.Raw()\n subcast_values_instance: ma.fields.Field\n if subcast_values:\n subcast_values_instance = _make_subcast_field(subcast_values)(**kwargs)\n else:\n subcast_values_instance = ma.fields.Raw()\n\n return {\n subcast_keys_instance.deserialize(\n key.strip(),\n ): subcast_values_instance.deserialize(val.strip())\n for key, val in (\n item.split(key_value_delimiter, 1) for item in value.split(delimiter) if value\n )\n }\n\n\ndef _preprocess_json(value: str | typing.Mapping | list, **kwargs) -> typing.Any:\n try:\n if isinstance(value, str):\n return pyjson.loads(value)\n if isinstance(value, (dict, list)) or value is None:\n return value\n raise ma.ValidationError(\"Not valid JSON.\")\n except pyjson.JSONDecodeError as error:\n raise ma.ValidationError(\"Not valid JSON.\") from error\n\n\ndef _dj_db_url_parser(value: str, **kwargs) -> DBConfig:\n try:\n import dj_database_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_db_url parser requires the dj-database-url package. \"\n \"You can install it with: pip install dj-database-url\",\n ) from error\n try:\n return dj_database_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid database URL.\") from error\n\n\ndef _dj_email_url_parser(value: str, **kwargs) -> dict:\n try:\n import dj_email_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_email_url parser requires the dj-email-url package. \"\n \"You can install it with: pip install dj-email-url\",\n ) from error\n try:\n return dj_email_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid email URL.\") from error\n\n\ndef _dj_cache_url_parser(value: str, **kwargs) -> dict:\n try:\n import django_cache_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_cache_url parser requires the django-cache-url package. \"\n \"You can install it with: pip install django-cache-url\",\n ) from error\n try:\n return django_cache_url.parse(value, **kwargs)\n except Exception as error:\n # django_cache_url may raise Exception(\"Unknown backend...\")\n # so use that error message in the validation error\n raise ma.ValidationError(error.args[0]) from error\n\n\nclass Env:\n \"\"\"An environment variable reader.\"\"\"\n\n __call__: FieldMethod[typing.Any] = _field2method(ma.fields.Raw, \"__call__\")\n\n int: FieldMethod[int] = _field2method(ma.fields.Int, \"int\")\n bool: FieldMethod[bool] = _field2method(ma.fields.Bool, \"bool\")\n str: FieldMethod[str] = _field2method(ma.fields.Str, \"str\")\n float: FieldMethod[float] = _field2method(ma.fields.Float, \"float\")\n decimal: FieldMethod[decimal.Decimal] = _field2method(ma.fields.Decimal, \"decimal\")\n list: ListFieldMethod = _field2method(\n _make_list_field,\n \"list\",\n preprocess=_preprocess_list,\n preprocess_kwarg_names=(\"subcast\", \"delimiter\"),\n )\n dict: DictFieldMethod = _field2method(\n ma.fields.Dict,\n \"dict\",\n preprocess=_preprocess_dict,\n preprocess_kwarg_names=(\n \"subcast_keys\",\n \"subcast_key\",\n \"subcast_values\",\n \"delimiter\",\n \"key_value_delimiter\",\n ),\n )\n json: FieldMethod[_ListType | _DictType] = _field2method(\n ma.fields.Raw,\n \"json\",\n preprocess=_preprocess_json,\n )\n datetime: FieldMethod[dt.datetime] = _field2method(ma.fields.DateTime, \"datetime\")\n date: FieldMethod[dt.date] = _field2method(ma.fields.Date, \"date\")\n time: FieldMethod[dt.time] = _field2method(ma.fields.Time, \"time\")\n timedelta: TimeDeltaFieldMethod = _field2method(fields.TimeDelta, \"timedelta\")\n path: FieldMethod[Path] = _field2method(fields.Path, \"path\")\n log_level: FieldMethod[_IntType] = _field2method(fields.LogLevel, \"log_level\")\n\n uuid: FieldMethod[uuid.UUID] = _field2method(ma.fields.UUID, \"uuid\")\n url: FieldMethod[ParseResult] = _field2method(fields.Url, \"url\")\n\n enum: EnumFieldMethod = _field2method(ma.fields.Enum, \"enum\")\n dj_db_url = _func2method(_dj_db_url_parser, \"dj_db_url\")\n dj_email_url = _func2method(_dj_email_url_parser, \"dj_email_url\")\n dj_cache_url = _func2method(_dj_cache_url_parser, \"dj_cache_url\")\n\n def __init__(\n self,\n *,\n eager: _BoolType = True,\n expand_vars: _BoolType = False,\n prefix: _StrType | None = None,\n ):\n self.eager = eager\n self._sealed: bool = False\n self.expand_vars = expand_vars\n self._fields: dict[_StrType, ma.fields.Field] = {}\n self._values: dict[_StrType, typing.Any] = {}\n self._errors: ErrorMapping = collections.defaultdict(list)\n self._prefix: _StrType | None = prefix\n self.__custom_parsers__: dict[_StrType, ParserMethod] = {}\n self._environ: dict[_StrType, _StrType] = {}\n\n def __repr__(self) -> _StrType:\n return f\"<{self.__class__.__name__}(eager={self.eager}, expand_vars={self.expand_vars})>\"\n\n def read_env(\n self,\n path: _StrType | Path | None = None,\n *,\n recurse: _BoolType = True,\n override: _BoolType = False,\n return_path: _BoolType = False,\n ) -> _BoolType | _StrType | None:\n \"\"\"Read a .env file into this Env instance.\n\n If .env is not found in the directory from which this method is called,\n the default behavior is to recurse up the directory tree until a .env\n file is found. To disable this behavior, pass ``recurse=False``.\n\n Pass ``override=True`` to overwrite previously loaded values when\n loading multiple .env files.\n\n If ``return_path`` is ``True``, return the path to the loaded .env\n file (or ``None`` if no file was found) instead of a boolean.\n \"\"\"\n env_path = None\n is_env_loaded = False\n if path is None:\n # By default, start search from the same directory this function is called\n current_frame = inspect.currentframe()\n if current_frame is None:\n raise RuntimeError(\"Could not get current call frame.\")\n frame = current_frame.f_back\n assert frame is not None # noqa: S101\n caller_dir = Path(frame.f_code.co_filename).parent.resolve()\n start = caller_dir / \".env\"\n else:\n if Path(path).is_dir():\n raise ValueError(\"path must be a filename, not a directory.\")\n start = Path(path)\n if recurse:\n start_dir, env_name = os.path.split(start)\n if not start_dir: # Only a filename was given\n start_dir = os.getcwd()\n for dirname in _walk_to_root(start_dir):\n check_path = Path(dirname) / env_name\n if check_path.exists():\n self._load_dotenv(check_path, override=override)\n is_env_loaded = True\n env_path = str(check_path)\n break\n elif start.exists():\n self._load_dotenv(start, override=override)\n is_env_loaded = True\n env_path = str(start)\n\n if return_path:\n return env_path\n return is_env_loaded\n\n def _load_dotenv(\n self,\n path: _StrType | Path,\n *,\n override: _BoolType = False,\n ) -> None:\n \"\"\"Load a .env file into self._environ.\"\"\"\n values = dotenv_values(path)\n for key, value in values.items():\n if value is None:\n continue\n if override or key not in self._environ:\n self._environ[key] = value\n\n @contextlib.contextmanager\n def prefixed(self, prefix: _StrType) -> typing.Iterator[Env]:\n \"\"\"Context manager for parsing envvars with a common prefix.\"\"\"\n try:\n old_prefix = self._prefix\n if old_prefix is None:\n self._prefix = prefix\n else:\n self._prefix = f\"{old_prefix}\n... [truncated 6960 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "sloria__environs-9c51c66940a1", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/sloria__environs-9c51c66940a1", "repo_key": "sloria__environs", "repo": "sloria/environs", "base_commit": "4654e60b62aae63638533c6aa8d4605680d2e3f1", "source_files": ["CHANGELOG.md", "src/environs/__init__.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** `read_env` always searches recursively and can raise `UnboundLocalError`\n\n## Description\nThe `read_env` function exhibits an \"always recursive\" behavior, meaning it searches parent directories for `.env` files even when not explicitly intended, potentially leading to unexpected file loading. Furthermore, under specific conditions, calling `read_env` can result in an `UnboundLocalError`. When `return_path=True` and no `.env` file is located, the function should return `None` but currently does not.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `a873df346093` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 11.2.0 (2024-11-14)\n\nFeatures:\n\n- `Env.timedelta` can parse [GEP-2257](https://gateway-api.sigs.k8s.io/geps/gep-2257/)\n duration strings ([#366](https://github.com/sloria/environs/pull/366)).\n Thanks [ddelange](https://github.com/ddelange) for the PR.\n\n## 11.1.0 (2024-11-11)\n\nFeatures:\n\n- Add `return_path` argument to `Env.read_env` to return the path of the\n parsed file ([#362](https://github.com/sloria/environs/issues/362)).\n Thanks [senese](https://github.com/senese) for the suggestion and PR.\n NOTE: This is added as a backwards-compatible change that is scheduled to be\n removed in 12.0.0. The path will stored as an attribute of `Env`.\n\n## 11.0.0 (2024-03-04)\n\nFixes:\n\n- Prevent `DeprecationWarning` getting raised by marshmallow 3.21.0 (:issue:`333`).\n\nOther changes:\n\n- Remove `subcast_key` argument of `env.dict`. Use `subcast_keys` instead.\n- Bump minimum required marshmallow version to 3.13.0.\n- Remove `missing` argument from `Env` methods. Use `default` instead.\n- Remove `subcast` argument from `Env` methods that don't use it.\n- _Backwards-incompatible_: Remove `environs.__version__` variable.\n Use `importlib.metadata.version(\"environs\")` instead.\n\n## 10.3.0 (2024-01-11)\n\nFeatures:\n\n- `Env.__repr__` and `Env.__str__` no longer display environment variables, to prevent accidental exfiltration of sensitive data ([#292](https://github.com/sloria/environs/issues/292)).\n Thanks [mro-rhansen2](https://github.com/mro-rhansen2) for the suggestion.\n\nBug fixes:\n\n- Fix passing `None` as default to `env.list` ([#298](https://github.com/sloria/environs/issues/298)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for reporting.\n\n## 10.2.0 (2024-01-09)\n\nFeatures:\n\n- `env.read_env` returns `False` if file not found ([#294](https://github.com/sloria/environs/issues/294)).\n Thanks [rptaylor](https://github.com/rptaylor) for the suggestion.\n\n## 10.1.0 (2024-01-08)\n\nFeatures:\n\n- Allow `default` for `env.json` to be a `dict` or `list` ([#240](https://github.com/sloria/environs/pull/240)).\n Thanks [tomgrin10](https://github.com/tomgrin10) and [bvanelli](https://github.com/bvanelli) for the PRs.\n\nOther changes:\n\n- Test against Python 3.12.\n\n## 10.0.0 (2023-12-15)\n\nFeatures:\n\n- Add `delimiter` argument to `env.dict` ([#277](https://github.com/sloria/environs/pull/277)). Thanks [gregoiredx](https://github.com/gregoiredx) for the PR.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for EOL Python 3.6 and 3.7.\n- Test against Python 3.11.\n- Migrate to setup.cfg. Thanks [deronnax](https://github.com/deronnax) for the PR.\n\n## 9.5.0 (2022-01-30)\n\nFeatures:\n\n- Allow callables or custom marshmallow fields to be passed to `subcast`, `subcast_keys`, and `subcast_values`. ([#241](https://github.com/sloria/environs/pull/241)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.4.0 (2022-01-04)\n\nBug fixes:\n\n- Address warning about passing metadata in newer versions of marshmallow.\n\nOther changes:\n\n- Test against Python 3.10.\n\n## 9.3.5 (2021-11-14)\n\nBug fixes:\n\n- Fix `env.url` and other parsers that take field keyword arguments ([#227](https://github.com/sloria/environs/issues/227)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.4 (2021-10-03)\n\nBug fixes:\n\n- Allow default for `env.path` to be a `pathlib.Path` ([#228](https://github.com/sloria/environs/issues/228)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.3 (2021-08-08)\n\nBug fixes:\n\n- Fix compatibility with marshmallow>=3.13.0\n so that no DeprecationWarnings are raised ([#224](https://github.com/sloria/environs/issues/224)).\n\n## 9.3.2 (2021-03-28)\n\nBug fixes:\n\n- Handle JSON decoding errors when using `env.json` ([#212](https://github.com/sloria/environs/pull/212)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.3.1 (2021-02-07)\n\nBug fixes:\n\n- Apply variable expansion to default values ([#204](https://github.com/sloria/environs/pull/204)).\n Thanks [rjcohn](https://github.com/rjcohn) for the PR.\n\n## 9.3.0 (2020-12-26)\n\nDeprecations:\n\n- Rename `subcast_key` argument of `env.dict` to `subcast_keys`\n for consistency with `subcast_values`. `subcast_key` is deprecated.\n\n## 9.2.0 (2020-11-07)\n\nFeatures:\n\n- Add time parser ([#191](https://github.com/sloria/environs/issues/191)).\n\n## 9.1.0 (2020-11-06)\n\nFeatures:\n\n- Add `enum` parser ([#185](https://github.com/sloria/environs/pull/185)).\n- Add `delimiter` param to `env.list`\n ([#184](https://github.com/sloria/environs/pull/184)).\n\nThanks [tomgrin10](https://github.com/tomgrin10) for the PRs.\n\nBug fixes:\n\n- Loosen `ParserMethod` typing ([#186 (comment)](https://github.com/sloria/environs/issues/186#issuecomment-723163520)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for the PR.\n\nOther changes:\n\n- When using deferred validation (`eager=False`), parser methods return `None`\n for missing or invalid values.\n _Note_: This may break code that depended on parser methods returning `marshmallow.missing`,\n but this behavior was not documented nor tested and therefore is not considered public API.\n\n## 9.0.0 (2020-10-31)\n\n- _Backwards-incompatible_: Rename `subcast` param of `env.dict` to `subcast_values` for consistency with `subcast_keys`.\n- _Backwards-incompatible_: Remove variable proxying. Use variable expansion instead (see 8.1.0 release notes below)\n ([#175](https://github.com/sloria/environs/issues/175)).\n- _Backwards-incompatible_: Drop support for marshmallow 2 and Python 3.5,\n which are both EOL ([#174](https://github.com/sloria/environs/issues/174)).\n\n## 8.1.0 (2020-10-31)\n\nFeatures:\n\n- Add support for variable expansion, e.g. `MY_VAR=${MY_OTHER_VAR:-mydefault}` ([#164](https://github.com/sloria/environs/issues/164)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\nDeprecations:\n\n- Variable proxying using the `{{VAR}}` syntax is deprecated\n and will be removed in environs 9.0.0.\n Use variable expansion using `${VAR}` instead.\n\n```bash\n# Before\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN={{MAILGUN_LOGIN}}\n\n# After\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN=${MAILGUN_LOGIN}\n```\n\n```python\nfrom environs import Env\n\nenv = Env(expand_vars=True)\n\nSMTP_LOGIN = env.str(\"SMTP_LOGIN\") # => 'sloria'\n```\n\nBug fixes:\n\n- Fix deferred validation behavior for `dj_db_url`, `dj_email_url`, `dj_cache_url`,\n and custom parsers ([#121](https://github.com/sloria/environs/issues/121)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for reporting.\n\nOther changes:\n\n- Test against Python 3.9.\n- Remove usage of implicit `typing.Optional` ([171](https://github.com/sloria/environs/issues/171)).\n\n## 8.0.0 (2020-05-27)\n\nBug fixes:\n\n- Fix behavior of recurse=True when custom filepath is passed to `env.read_env`\n ([#100](https://github.com/sloria/environs/issues/100)). Thanks [ribeaud](https://github.com/ribeaud) and [timoklimmer](https://github.com/sloria/environs/pull/157) for the help.\n\nOther changes:\n\n- _Backwards-incompatible_: As a result of the above fix, passing a directory to `env.read_env` is no longer allowed and will raise a `ValueError`.\n Only file paths or file names should be passed.\n\n## 7.4.0 (2020-04-18)\n\n- Add `subcast_key` argument to `env.dict` ([#151](https://github.com/sloria/environs/issues/151)).\n Thanks [AugPro](https://github.com/AugPro) for the suggestion and PR.\n\n## 7.3.1 (2020-03-22)\n\n- Fix error when parsing empty list with subcast\n [#137](https://github.com/sloria/environs/issues/137).\n Thanks [sabdouni] for the catch and patch.\n\n## 7.3.0 (2020-03-01)\n\n- `log_level` accepts lower-cased log level names and rejects invalid\n names ([#138](https://github.com/sloria/environs/pull/138)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\n## 7.2.0 (2020-02-09)\n\n- Add `dj_cache_url` for caching Django cache URLs (requires installing with `[django]`)\n ([#126](https://github.com/sloria/environs/issues/126)).\n Thanks [epicserve](https://github.com/epicserve) for the suggestion and PR.\n\n## 7.1.0 (2019-12-07)\n\n- Improve typings and run mypy with dependencies type annotations ([#115](https://github.com/sloria/environs/pull/115)).\n- Distribute types per PEP 561 ([#116](https://github.com/sloria/environs/pull/116)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 7.0.0 (2019-12-02)\n\n- _Backwards-incompatible_: Remove `stream` argument from `read_env`,\n since it had no effect ([#114](https://github.com/sloria/environs/pull/114)).\n- _Backwards-incompatible_: `Env.read_env` consistently returns `None`\n ([#111](https://github.com/sloria/environs/pull/111)).\n- Remove unnecessary `__str__` definition ([#112](https://github.com/sloria/environs/pull/112)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 6.1.0 (2019-11-03)\n\nFeatures:\n\n- Add deferred validation via the `eager` parameter and `env.seal()` ([#56](https://github.com/sloria/environs/issues/56)).\n Thanks [robertlagrant](https://github.com/robertlagrant) for the suggestion.\n\nOther changes:\n\n- Test against Python 3.8 ([#108](https://github.com/sloria/environs/pull/108)).\n\n## 6.0.0 (2019-09-22)\n\nFeatures:\n\n- Default parser methods are now defined as bound methods.\n This enables static analysis features, e.g. autocomplete ([#103](https://github.com/sloria/environs/issues/103)).\n Thanks [rugleb](https://github.com/rugleb) for the suggestion.\n _Backwards-incompatible_: As a result of this change, adding a parser name that is the same as an existing method\n will result in an error being raised.\n\n```python\nimport environs\n\nenv = environs.Env()\n\n\n# Below conflicts with built-in `url` method.\n# In <6.0.0, this would override the built-in method.\n# In >=6.0.0, this raises an error:\n# environs.ParserConflictError: Env already has a method with name 'url'. Use a different name.\n@env.parser_for(\"url\")\ndef https_url(value):\n return \"https://\" + value\n```\n\nBug fixes:\n\n- Fix error message for prefixed variables ([#102](https://github.com/sloria/environs/issues/102)).\n Thanks [AGeekInside](https://github.com/AGeekInside) for reporting.\n\nOther changes:\n\n- _Backwards-incompatible_: Rename `Env.__parser_map__` to `Env.__custom_parsers__`.\n\n## 5.2.1 (2019-08-08)\n\nBug fixes:\n\n- Fix behavior when recursively searching for a specified file\n ([#96](https://github.com/sloria/environs/issues/96)).\n Thanks [ribeaud](https://github.com/ribeaud) for the catch and patch.\n\n## 5.2.0 (2019-07-19)\n\nChanges:\n\n- Improve typings.\n\n## 5.1.0 (2019-07-13)\n\nFeatures:\n\n- Add `env.log_level` ([#7](https://github.com/sloria/environs/issues/7)).\n- Use `raise from` to improve tracebacks.\n\nOther changes:\n\n- Improve typings.\n\n## 5.0.0 (2019-07-06)\n\nFeatures:\n\n- Add `env.path` ([#81](https://github.com/sloria/environs/issues/81)).\n Thanks [umrashrf](https://github.com/umrashrf) for the suggestion.\n- Add type annotations.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for Python 2. If you use Python 2,\n you will need to use version 4.2.0 or older.\n\n## 4.2.0 (2019-06-01)\n\n- Minor optimization.\n\nBug fixes:\n\n- Reset prefix when an exception is raised within an `env.prefixed()`\n context ([#78](https://github.com/sloria/environs/issues/78)).\n Thanks [rcuza](https://github.com/rcuza) for the catch and patch.\n\n## 4.1.3 (2019-05-15)\n\nBug fixes:\n\n- Fix behavior when passing a `dict` value as the default\n to `env.dict` ([#76](https://github.com/sloria/environs/pull/76)).\n Thanks [c-w](https://github.com/c-w) for the PR.\n\nSupport:\n\n- Document how to read a specific file with `env.read_env`\n ([#66](https://github.com/sloria/environs/issues/66)).\n Thanks [nvtkaszpir](https://github.com/nvtkaszpir) and\n [c-w](https://github.com/c-w).\n\n## 4.1.2 (2019-05-05)\n\nBug fixes:\n\n- Fix compatibility with marshmallow 3.0.0>=rc6.\n\n## 4.1.1 (2019-05-04)\n\nBug fixes:\n\n- Fix accessing proxied envvars when using `env.prefixed`\n ([#72](https://github.com/sloria/environs/issues/72)).\n Thanks [Kamforka](https://github.com/Kamforka) for the catch and patch.\n- Fix behavior when an envvar is explicitly set to an empty string\n ([#71](https://github.com/sloria/environs/issues/71)).\n Thanks [twosigmajab](https://github.com/twosigmajab) for reporting\n and thanks [hvtuananh](https://github.com/hvtuananh) for the PR.\n\n## 4.1.0 (2018-12-10)\n\n- `EnvError` subclasses `ValueError` ([#50](https://github.com/sloria/environs/pull/50)).\n Thanks [alexpirine](https://github.com/alexpirine).\n- Test against Python 3.7.\n\n## 4.0.0 (2018-08-06)\n\n- Use python-dotenv for parsing .env files. `Env.read_env` behaves\n mostly the same except that a warning isn't raised by default if a\n .env file isn\\'t found. Pass `verbose=True` to raise a warning.\n\n## 3.0.0 (2018-08-05)\n\nFeatures:\n\n- _Backwards-incompatible_: `Env.read_env` raises a warning instead of\n an error when `.env` isn\\'t found\n ([#10](https://github.com/sloria/environs/issues/10)). Thanks\n [lachlancooper](https://github.com/lachlancooper) for the\n suggestion.\n- Add optional Django support. Install using\n `pip install environs[django]`, which enables `env.dj_db_url` and\n `env.dj_email_url`.\n\n## 2.1.1 (2018-05-21)\n\nFeatures:\n\n- Fix compatibility with marshmallow 3 beta.\n\n## 2.1.0 (2018-01-25)\n\nFeatures:\n\n- Add recurse parameter to Env.read_env\n ([#9](https://github.com/sloria/environs/pull/9)). Thanks\n [gthank](https://github.com/gthank) for the PR.\n\n## 2.0.0 (2018-01-02)\n\nFeatures:\n\n- Add support for nested prefixes\n ([#8](https://github.com/sloria/environs/pull/8)). Thanks\n [gvialetto](https://github.com/gvialetto) for the PR.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for Python 3.3 and 3.4.\n\n## 1.2.0 (2017-01-12)\n\nFeatures:\n\n- Add `url` parser that returns a `urllib.parse.ParseResult`\n ([#6](https://github.com/sloria/environs/issues/6)). Thanks\n [IlyaSemenov](https://github.com/IlyaSemenov) for the suggestion.\n\nBug fixes:\n\n- Every instance of `Env` gets its own parser map, so calling\n `env.parser_for` for one instance doesn\\'t affect other instances.\n\n## 1.1.0 (2016-05-01)\n\n- Add `Env.read_env` method for reading `.env` files.\n\n## 1.0.0 (2016-04-30)\n\n- Support for proxied variables\n ([#2](https://github.com/sloria/environs/issues/2)).\n- _Backwards-incompatible_: Remove `env.get` method. Use `env()`\n instead.\n- Document how to read `.env` files\n ([#1](https://github.com/sloria/environs/issues/1)).\n\n## 0.1.0 (2016-04-25)\n\n- First PyPI release.\n\n```\n\n### src/environs/__init__.py\n```python\nimport collections\nimport contextlib\nimport functools\nimport inspect\nimport json as pyjson\nimport logging\nimport os\nimport re\nimport typing\nfrom collections.abc import Mapping\nfrom datetime import timedelta\nfrom enum import Enum\nfrom pathlib import Path\nfrom urllib.parse import ParseResult, urlparse\n\nimport marshmallow as ma\nfrom dotenv.main import _walk_to_root, load_dotenv\n\n__all__ = [\"EnvError\", \"Env\"]\n\n_T = typing.TypeVar(\"_T\")\n_StrType = str\n_BoolType = bool\n\nErrorMapping = typing.Mapping[str, typing.List[str]]\nErrorList = typing.List[str]\nFieldFactory = typing.Callable[..., ma.fields.Field]\nSubcast = typing.Union[typing.Type, typing.Callable[..., _T], ma.fields.Field]\nFieldType = typing.Type[ma.fields.Field]\nFieldOrFactory = typing.Union[FieldType, FieldFactory]\nParserMethod = typing.Callable\n\n\n_EXPANDED_VAR_PATTERN = re.compile(r\"(? ParserMethod:\n def method(\n self: \"Env\",\n name: str,\n default: typing.Any = ma.missing,\n subcast: typing.Optional[Subcast] = None,\n *,\n # Subset of relevant marshmallow.Field kwargs\n load_default: typing.Any = ma.missing,\n validate: typing.Optional[\n typing.Union[\n typing.Callable[[typing.Any], typing.Any],\n typing.Iterable[typing.Callable[[typing.Any], typing.Any]],\n ]\n ] = None,\n required: bool = False,\n allow_none: typing.Optional[bool] = None,\n error_messages: typing.Optional[typing.Dict[str, str]] = None,\n metadata: typing.Optional[typing.Mapping[str, typing.Any]] = None,\n **kwargs,\n ) -> typing.Optional[_T]:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\"\n )\n field_kwargs = dict(\n validate=validate,\n required=required,\n allow_none=allow_none,\n load_default=load_default or default,\n error_messages=error_messages,\n metadata=metadata,\n )\n preprocess_kwargs = {\n name: kwargs.pop(name) for name in preprocess_kwarg_names if name in kwargs\n }\n if isinstance(field_or_factory, type) and issubclass(\n field_or_factory, ma.fields.Field\n ):\n field = field_or_factory(**field_kwargs, **kwargs)\n else:\n parsed_subcast = _make_subcast_field(subcast)\n field = typing.cast(FieldFactory, field_or_factory)(\n subcast=parsed_subcast, **field_kwargs\n )\n parsed_key, value, proxied_key = self._get_from_environ(\n name, field.load_default\n )\n self._fields[parsed_key] = field\n source_key = proxied_key or parsed_key\n if value is ma.missing:\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set'\n )\n else:\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n try:\n if preprocess:\n value = preprocess(value, **preprocess_kwargs)\n value = field.deserialize(value)\n except ma.ValidationError as error:\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n error.messages,\n ) from error\n self._errors[parsed_key].extend(error.messages)\n else:\n self._values[parsed_key] = value\n return value\n\n method.__name__ = method_name\n return method\n\n\ndef _func2method(func: typing.Callable, method_name: str) -> ParserMethod:\n def method(\n self: \"Env\",\n name: str,\n default: typing.Any = ma.missing,\n **kwargs,\n ) -> typing.Optional[_T]:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\"\n )\n parsed_key, raw_value, proxied_key = self._get_from_environ(name, default)\n self._fields[parsed_key] = ma.fields.Field()\n source_key = proxied_key or parsed_key\n if raw_value is ma.missing:\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set'\n )\n else:\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n if raw_value or raw_value == \"\":\n value = raw_value\n else:\n value = None\n try:\n value = func(raw_value, **kwargs)\n except (EnvError, ma.ValidationError) as error:\n messages = (\n error.messages\n if isinstance(error, ma.ValidationError)\n else [error.args[0]]\n )\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n messages,\n ) from error\n self._errors[parsed_key].extend(messages)\n else:\n self._values[parsed_key] = value\n return value\n\n method.__name__ = method_name\n return method\n\n\ndef _make_subcast_field(\n subcast: typing.Optional[Subcast],\n) -> typing.Type[ma.fields.Field]:\n if isinstance(subcast, type) and subcast in ma.Schema.TYPE_MAPPING:\n inner_field = ma.Schema.TYPE_MAPPING[subcast]\n elif isinstance(subcast, type) and issubclass(subcast, ma.fields.Field):\n inner_field = subcast\n elif callable(subcast):\n\n class SubcastField(ma.fields.Field):\n def _deserialize(self, value, *args, **kwargs):\n func = typing.cast(typing.Callable[..., _T], subcast)\n return func(value)\n\n inner_field = SubcastField\n else:\n inner_field = ma.fields.Field\n return inner_field\n\n\ndef _make_list_field(*, subcast: typing.Optional[type], **kwargs) -> ma.fields.List:\n inner_field = _make_subcast_field(subcast)\n return ma.fields.List(inner_field, **kwargs)\n\n\ndef _preprocess_list(\n value: typing.Union[str, typing.Iterable], *, delimiter: str = \",\", **kwargs\n) -> typing.Iterable:\n if ma.utils.is_iterable_but_not_string(value) or value is None:\n return value\n return typing.cast(str, value).split(delimiter) if value != \"\" else []\n\n\ndef _preprocess_dict(\n value: typing.Union[str, typing.Mapping],\n *,\n subcast_keys: typing.Optional[Subcast] = None,\n subcast_values: typing.Optional[Subcast] = None,\n delimiter: str = \",\",\n **kwargs,\n) -> typing.Mapping:\n if isinstance(value, Mapping):\n return value\n subcast_keys_instance: ma.fields.Field = _make_subcast_field(subcast_keys)(**kwargs)\n subcast_values_instance: ma.fields.Field = _make_subcast_field(subcast_values)(\n **kwargs\n )\n\n return {\n subcast_keys_instance.deserialize(\n key.strip()\n ): subcast_values_instance.deserialize(val.strip())\n for key, val in (item.split(\"=\", 1) for item in value.split(delimiter) if value)\n }\n\n\ndef _preprocess_json(value: typing.Union[str, typing.Mapping, typing.List], **kwargs):\n try:\n if isinstance(value, str):\n return pyjson.loads(value)\n elif isinstance(value, dict) or isinstance(value, list) or value is None:\n return value\n else:\n raise ma.ValidationError(\"Not valid JSON.\")\n except pyjson.JSONDecodeError as error:\n raise ma.ValidationError(\"Not valid JSON.\") from error\n\n\n_EnumT = typing.TypeVar(\"_EnumT\", bound=Enum)\n\n\ndef _enum_parser(value, type: typing.Type[_EnumT], ignore_case: bool = False) -> _EnumT:\n invalid_exc = ma.ValidationError(f\"Not a valid '{type.__name__}' enum.\")\n\n if not ignore_case:\n try:\n return type[value]\n except KeyError as error:\n raise invalid_exc from error\n\n for enum_value in type:\n if enum_value.name.lower() == value.lower():\n return enum_value\n\n raise invalid_exc\n\n\ndef _dj_db_url_parser(value: str, **kwargs) -> dict:\n try:\n import dj_database_url\n except ImportError as error:\n raise RuntimeError(\n \"The dj_db_url parser requires the dj-database-url package. \"\n \"You can install it with: pip install dj-database-url\"\n ) from error\n try:\n return dj_database_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid database URL.\") from error\n\n\ndef _dj_email_url_parser(value: str, **kwargs) -> dict:\n try:\n import dj_email_url\n except ImportError as error:\n raise RuntimeError(\n \"The dj_email_url parser requires the dj-email-url package. \"\n \"You can install it with: pip install dj-email-url\"\n ) from error\n try:\n return dj_email_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid email URL.\") from error\n\n\ndef _dj_cache_url_parser(value: str, **kwargs) -> dict:\n try:\n import django_cache_url\n except ImportError as error:\n raise RuntimeError(\n \"The dj_cache_url parser requires the django-cache-url package. \"\n \"You can install it with: pip install django-cache-url\"\n ) from error\n try:\n return django_cache_url.parse(value, **kwargs)\n except Exception as error:\n # django_cache_url may raise Exception(\"Unknown backend...\")\n # so use that error message in the validation error\n raise ma.ValidationError(error.args[0]) from error\n\n\nclass URLField(ma.fields.URL):\n def _serialize(self, value: ParseResult, *args, **kwargs) -> str:\n return value.geturl()\n\n # Override deserialize rather than _deserialize because we need\n # to call urlparse *after* validation has occurred\n def deserialize(\n self,\n value: str,\n attr: typing.Optional[str] = None,\n data: typing.Optional[typing.Mapping] = None,\n **kwargs,\n ) -> ParseResult:\n ret = super().deserialize(value, attr, data, **kwargs)\n return urlparse(ret)\n\n\nclass PathField(ma.fields.Str):\n def _deserialize(self, value, *args, **kwargs) -> Path:\n if isinstance(value, Path):\n return value\n ret = super()._deserialize(value, *args, **kwargs)\n return Path(ret)\n\n\nclass LogLevelField(ma.fields.Int):\n def _format_num(self, value) -> int:\n try:\n return super()._format_num(value)\n except (TypeError, ValueError) as error:\n value = value.upper()\n if hasattr(logging, value) and isinstance(getattr(logging, value), int):\n return getattr(logging, value)\n else:\n raise ma.ValidationError(\"Not a valid log level.\") from error\n\n\nclass TimeDeltaField(ma.fields.TimeDelta):\n def _deserialize(self, value, *args, **kwargs) -> timedelta:\n if isinstance(value, timedelta):\n return value\n match = _TIMEDELTA_PATTERN.match(value)\n if match is not None and match.group(0): # disallow \"\", allow \"0s\"\n return timedelta(\n weeks=int(match.group(1) or 0),\n days=int(match.group(2) or 0),\n hours=int(match.group(3) or 0),\n minutes=int(match.group(4) or 0),\n seconds=int(match.group(5) or 0),\n milliseconds=int(match.group(6) or 0),\n microseconds=int(match.group(7) or 0),\n )\n return super()._deserialize(value, *args, **kwargs)\n\n\nclass Env:\n \"\"\"An environment variable reader.\"\"\"\n\n __call__: ParserMethod = _field2method(ma.fields.Field, \"__call__\")\n\n int = _field2method(ma.fields.Int, \"int\")\n bool = _field2method(ma.fields.Bool, \"bool\")\n str = _field2method(ma.fields.Str, \"str\")\n float = _field2method(ma.fields.Float, \"float\")\n decimal = _field2method(ma.fields.Decimal, \"decimal\")\n list = _field2method(\n _make_list_field,\n \"list\",\n preprocess=_preprocess_list,\n preprocess_kwarg_names=(\"subcast\", \"delimiter\"),\n )\n dict = _field2method(\n ma.fields.Dict,\n \"dict\",\n preprocess=_preprocess_dict,\n preprocess_kwarg_names=(\n \"subcast\",\n \"subcast_keys\",\n \"subcast_key\",\n \"subcast_values\",\n \"delimiter\",\n ),\n )\n json = _field2method(ma.fields.Field, \"json\", preprocess=_preprocess_json)\n datetime = _field2method(ma.fields.DateTime, \"datetime\")\n date = _field2method(ma.fields.Date, \"date\")\n time = _field2method(ma.fields.Time, \"time\")\n path = _field2method(PathField, \"path\")\n log_level = _field2method(LogLevelField, \"log_level\")\n timedelta = _field2method(TimeDeltaField, \"timedelta\")\n uuid = _field2method(ma.fields.UUID, \"uuid\")\n url = _field2method(URLField, \"url\")\n enum = _func2method(_enum_parser, \"enum\")\n dj_db_url = _func2method(_dj_db_url_parser, \"dj_db_url\")\n dj_email_url = _func2method(_dj_email_url_parser, \"dj_email_url\")\n dj_cache_url = _func2method(_dj_cache_url_parser, \"dj_cache_url\")\n\n def __init__(self, *, eager: _BoolType = True, expand_vars: _BoolType = False):\n self.eager = eager\n self._sealed: bool = False\n self.expand_vars = expand_vars\n self._fields: typing.Dict[_StrType, typing.Union[ma.fields.Field, type]] = {}\n self._values: typing.Dict[_StrType, typing.Any] = {}\n self._errors: ErrorMapping = collections.defaultdict(list)\n self._prefix: typing.Optional[_StrType] = None\n self.__custom_parsers__: typing.Dict[_StrType, ParserMethod] = {}\n\n def __repr__(self) -> _StrType:\n return f\"<{self.__class__.__name__}(eager=\n... [truncated 7727 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "sloria__environs-9d1ff82555e0", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/sloria__environs-9d1ff82555e0", "repo_key": "sloria__environs", "repo": "sloria/environs", "base_commit": "a873df3460939554806834390a6c82dac194b2ad", "source_files": ["CHANGELOG.md", "src/environs/__init__.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Values read from files include trailing newlines\n\n## Description\nWhen reading a value from a file, any trailing newline characters are retained as part of the retrieved value. For instance, if a file named `config.txt` contains `my_setting\\n`, the value obtained will be `\"my_setting\\n\"`. The expected behavior is that trailing newlines should be automatically stripped, returning `\"my_setting\"` instead.\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `7ed9ec4cf3fc` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### CHANGELOG.md\n```python\n# Changelog\n\n## 14.4.0 (2025-10-29)\n\nFeatures:\n\n- Add support for ISO 8601 durations to `env.timedelta`. ([#434](https://github.com/sloria/environs/pull/434)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for the suggestion and PR.\n\n## 14.3.0 (2025-08-01)\n\nFeatures:\n\n- Add `environs.FileAwareEnv` for reading secret files ([#410](https://github.com/sloria/environs/pull/410)).\n Thanks [holtgrewe](https://github.com/holtgrewe) for the suggestion.\n Thanks [whyscream](https://github.com/whyscream) and [avilaton](https://github.com/avilaton) for the PRs.\n\n## 14.2.0 (2025-05-22)\n\nFeatures:\n\n- Add `key_value_delimiter` argument to `env.dict` ([#419](https://github.com/sloria/environs/issues/419)).\n Thanks [jerr0328](https://github.com/jerr0328) for the suggestion and PR.\n\n## 14.1.1 (2025-02-10)\n\nBug fixes:\n\n- Typing: Fix typing for `env.list` and `env.dict` to properly handle\n `default` and `subcast` arguments ([#406](https://github.com/sloria/environs/issues/406)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for the PR.\n- Add `env` to `__all__` ([#396](https://github.com/sloria/environs/issues/396)).\n Thanks [daveflr](https://github.com/daveflr) for reporting.\n\nChanges:\n\n- _Backwards-incompatible_: `recurse`, `verbose`, `override`,\n and `return_path` parameters to `Env.read_env` are now keyword-only.\n- _Backwards-incompatible_: The `required` argument to parser methods\n is removed. Call a parser method without a default value to make it required.\n\n## 14.1.0 (2025-01-10)\n\nFeatures:\n\n- Add `prefix` parameter to `Env` constructor ([#384](https://github.com/sloria/environs/issues/384)).\n Thanks [arthurc0102](https://github.com/sloria/environs/issues/384)\n for the suggestion.\n- Re-export `validate` module from marshmallow ([#385](https://github.com/sloria/environs/issues/385)).\n\nBug fixes:\n\n- Typing: Fix typing for `Env.enum` to allow `by_value` to be passed ([#386](https://github.com/sloria/environs/issues/386)).\n\n## 14.0.0 (2025-01-07)\n\nFeatures:\n\n- Add `env` singleton ([#194]).\n Thanks [AndBondStyle](https://github.com/AndBondStyle) for the suggestion.\n\n```python\nfrom environs import env\n```\n\nChanges:\n\n- `default` values are expected to be their in their deserialized form.\n _Backwards-incompatible_: Passing serialized values to `default`\n is no longer supported.\n\n```python\nfrom datetime import date, timedelta\nimport environs\n\n# DO\nenable_login = env.bool(\"ENABLE_LOGIN\", True)\nttl = env.timedelta(\"TTL\", default=timedelta(seconds=600))\nrelease_date = env.date(\"RELEASE\", date(2025, 1, 7))\nnumbers = env.list(\"FOO\", [1.0, 2.0, 3.0], subcast=float)\n\n# DON'T\nenable_login = env.bool(\"ENABLE_LOGIN\", \"true\")\nttl = env.timedelta(\"TTL\", default=600)\nrelease_date = env.date(\"RELEASE\", \"2025-01-07\")\nnumbers = env.list(\"NUMBERS\", \"1,2,42\", subcast=float)\n```\n\nThe exceptions to this rule are the Django-related functions, which\naccept string defaults.\n\n```python\nDATABASE_URL = env.dj_db_url(\"DATABASE_URL\", default=\"postgresql://localhost:5432/mydb\")\n```\n\nThis fixes [#297](https://github.com/sloria/environs/issues/297)\nand [#270](https://github.com/sloria/environs/issues/270).\n\n## 13.0.0 (2025-01-07)\n\nFeatures:\n\n- Typing: Add type hints for parser methods ([#367](https://github.com/sloria/environs/issues/367)).\n Thanks [OkeyDev](https://github/OkeyDev) for the PR.\n- Add `by_value` param to `Env.enum`. Pass `by_value=True` to parse Enum by values instead of names.\n\nOther changes:\n\n- Drop support for marshmallow<3.18.0.\n- _Backwards-incompatible_: Remove `load_default` param from parser methods. Use `default` instead.\n- _Backwards-incompatible_: Rename `Env.enum`'s `type` param to `enum`.\n- _Backwards-incompatible_: Remove `ignore_case` param from `Env.enum`.\n- _Backwards-incompatible_: Remove\n `allow_none`, `error_messages`, and `metadata` params from parser methods.\n\n## 12.0.0 (2025-01-06)\n\nFeatures:\n\n- `Env.enum` allows passing an `Enum` as `default`.\n\nOther changes:\n\n- Support marshmallow 4.\n- Support Python 3.9-3.13.\n- _Backwards-incompatible_: Make `Field` classes private. Users should\n not need to access these.\n\n## 11.2.1 (2024-11-20)\n\nBug fixes:\n\n- Fix passing non-string default values to `Env.timedelta` ([#369](https://github.com/sloria/environs/pull/369)).\n Thanks [tcleonard](https://github.com/tcleonard) for reporting and\n thanks [ddelange](https://github.com/ddelange) for the PR.\n- Fix `Env.read_env(recurse=True)` so that it returns as soon as a `.env`\n file is found ([#370](https://github.com/sloria/environs/pull/370)).\n Thanks [senese](https://github.com/senese) for the PR.\n\n## 11.2.0 (2024-11-14)\n\nFeatures:\n\n- `Env.timedelta` can parse [GEP-2257](https://gateway-api.sigs.k8s.io/geps/gep-2257/)\n duration strings ([#366](https://github.com/sloria/environs/pull/366)).\n Thanks [ddelange](https://github.com/ddelange) for the PR.\n\n## 11.1.0 (2024-11-11)\n\nFeatures:\n\n- Add `return_path` argument to `Env.read_env` to return the path of the\n parsed file ([#362](https://github.com/sloria/environs/issues/362)).\n Thanks [senese](https://github.com/senese) for the suggestion and PR.\n NOTE: This is added as a backwards-compatible change that is scheduled to be\n removed in 12.0.0. The path will stored as an attribute of `Env`.\n\n## 11.0.0 (2024-03-04)\n\nFixes:\n\n- Prevent `DeprecationWarning` getting raised by marshmallow 3.21.0 (:issue:`333`).\n\nOther changes:\n\n- Remove `subcast_key` argument of `env.dict`. Use `subcast_keys` instead.\n- Bump minimum required marshmallow version to 3.13.0.\n- Remove `missing` argument from `Env` methods. Use `default` instead.\n- Remove `subcast` argument from `Env` methods that don't use it.\n- _Backwards-incompatible_: Remove `environs.__version__` variable.\n Use `importlib.metadata.version(\"environs\")` instead.\n\n## 10.3.0 (2024-01-11)\n\nFeatures:\n\n- `Env.__repr__` and `Env.__str__` no longer display environment variables, to prevent accidental exfiltration of sensitive data ([#292](https://github.com/sloria/environs/issues/292)).\n Thanks [mro-rhansen2](https://github.com/mro-rhansen2) for the suggestion.\n\nBug fixes:\n\n- Fix passing `None` as default to `env.list` ([#298](https://github.com/sloria/environs/issues/298)).\n Thanks [lucas-bremond](https://github.com/lucas-bremond) for reporting.\n\n## 10.2.0 (2024-01-09)\n\nFeatures:\n\n- `env.read_env` returns `False` if file not found ([#294](https://github.com/sloria/environs/issues/294)).\n Thanks [rptaylor](https://github.com/rptaylor) for the suggestion.\n\n## 10.1.0 (2024-01-08)\n\nFeatures:\n\n- Allow `default` for `env.json` to be a `dict` or `list` ([#240](https://github.com/sloria/environs/pull/240)).\n Thanks [tomgrin10](https://github.com/tomgrin10) and [bvanelli](https://github.com/bvanelli) for the PRs.\n\nOther changes:\n\n- Test against Python 3.12.\n\n## 10.0.0 (2023-12-15)\n\nFeatures:\n\n- Add `delimiter` argument to `env.dict` ([#277](https://github.com/sloria/environs/pull/277)). Thanks [gregoiredx](https://github.com/gregoiredx) for the PR.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for EOL Python 3.6 and 3.7.\n- Test against Python 3.11.\n- Migrate to setup.cfg. Thanks [deronnax](https://github.com/deronnax) for the PR.\n\n## 9.5.0 (2022-01-30)\n\nFeatures:\n\n- Allow callables or custom marshmallow fields to be passed to `subcast`, `subcast_keys`, and `subcast_values`. ([#241](https://github.com/sloria/environs/pull/241)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.4.0 (2022-01-04)\n\nBug fixes:\n\n- Address warning about passing metadata in newer versions of marshmallow.\n\nOther changes:\n\n- Test against Python 3.10.\n\n## 9.3.5 (2021-11-14)\n\nBug fixes:\n\n- Fix `env.url` and other parsers that take field keyword arguments ([#227](https://github.com/sloria/environs/issues/227)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.4 (2021-10-03)\n\nBug fixes:\n\n- Allow default for `env.path` to be a `pathlib.Path` ([#228](https://github.com/sloria/environs/issues/228)).\n Thanks [KochankovID](https://github.com/KochankovID) for the PR.\n\n## 9.3.3 (2021-08-08)\n\nBug fixes:\n\n- Fix compatibility with marshmallow>=3.13.0\n so that no DeprecationWarnings are raised ([#224](https://github.com/sloria/environs/issues/224)).\n\n## 9.3.2 (2021-03-28)\n\nBug fixes:\n\n- Handle JSON decoding errors when using `env.json` ([#212](https://github.com/sloria/environs/pull/212)).\n Thanks [bvanelli](https://github.com/bvanelli) for the PR.\n\n## 9.3.1 (2021-02-07)\n\nBug fixes:\n\n- Apply variable expansion to default values ([#204](https://github.com/sloria/environs/pull/204)).\n Thanks [rjcohn](https://github.com/rjcohn) for the PR.\n\n## 9.3.0 (2020-12-26)\n\nDeprecations:\n\n- Rename `subcast_key` argument of `env.dict` to `subcast_keys`\n for consistency with `subcast_values`. `subcast_key` is deprecated.\n\n## 9.2.0 (2020-11-07)\n\nFeatures:\n\n- Add time parser ([#191](https://github.com/sloria/environs/issues/191)).\n\n## 9.1.0 (2020-11-06)\n\nFeatures:\n\n- Add `enum` parser ([#185](https://github.com/sloria/environs/pull/185)).\n- Add `delimiter` param to `env.list`\n ([#184](https://github.com/sloria/environs/pull/184)).\n\nThanks [tomgrin10](https://github.com/tomgrin10) for the PRs.\n\nBug fixes:\n\n- Loosen `ParserMethod` typing ([#186 (comment)](https://github.com/sloria/environs/issues/186#issuecomment-723163520)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for the PR.\n\nOther changes:\n\n- When using deferred validation (`eager=False`), parser methods return `None`\n for missing or invalid values.\n _Note_: This may break code that depended on parser methods returning `marshmallow.missing`,\n but this behavior was not documented nor tested and therefore is not considered public API.\n\n## 9.0.0 (2020-10-31)\n\n- _Backwards-incompatible_: Rename `subcast` param of `env.dict` to `subcast_values` for consistency with `subcast_keys`.\n- _Backwards-incompatible_: Remove variable proxying. Use variable expansion instead (see 8.1.0 release notes below)\n ([#175](https://github.com/sloria/environs/issues/175)).\n- _Backwards-incompatible_: Drop support for marshmallow 2 and Python 3.5,\n which are both EOL ([#174](https://github.com/sloria/environs/issues/174)).\n\n## 8.1.0 (2020-10-31)\n\nFeatures:\n\n- Add support for variable expansion, e.g. `MY_VAR=${MY_OTHER_VAR:-mydefault}` ([#164](https://github.com/sloria/environs/issues/164)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\nDeprecations:\n\n- Variable proxying using the `{{VAR}}` syntax is deprecated\n and will be removed in environs 9.0.0.\n Use variable expansion using `${VAR}` instead.\n\n```bash\n# Before\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN={{MAILGUN_LOGIN}}\n\n# After\nexport MAILGUN_LOGIN=sloria\nexport SMTP_LOGIN=${MAILGUN_LOGIN}\n```\n\n```python\nfrom environs import Env\n\nenv = Env(expand_vars=True)\n\nSMTP_LOGIN = env.str(\"SMTP_LOGIN\") # => 'sloria'\n```\n\nBug fixes:\n\n- Fix deferred validation behavior for `dj_db_url`, `dj_email_url`, `dj_cache_url`,\n and custom parsers ([#121](https://github.com/sloria/environs/issues/121)).\n Thanks [hukkinj1](https://github.com/hukkinj1) for reporting.\n\nOther changes:\n\n- Test against Python 3.9.\n- Remove usage of implicit `typing.Optional` ([171](https://github.com/sloria/environs/issues/171)).\n\n## 8.0.0 (2020-05-27)\n\nBug fixes:\n\n- Fix behavior of recurse=True when custom filepath is passed to `env.read_env`\n ([#100](https://github.com/sloria/environs/issues/100)). Thanks [ribeaud](https://github.com/ribeaud) and [timoklimmer](https://github.com/sloria/environs/pull/157) for the help.\n\nOther changes:\n\n- _Backwards-incompatible_: As a result of the above fix, passing a directory to `env.read_env` is no longer allowed and will raise a `ValueError`.\n Only file paths or file names should be passed.\n\n## 7.4.0 (2020-04-18)\n\n- Add `subcast_key` argument to `env.dict` ([#151](https://github.com/sloria/environs/issues/151)).\n Thanks [AugPro](https://github.com/AugPro) for the suggestion and PR.\n\n## 7.3.1 (2020-03-22)\n\n- Fix error when parsing empty list with subcast\n [#137](https://github.com/sloria/environs/issues/137).\n Thanks [sabdouni] for the catch and patch.\n\n## 7.3.0 (2020-03-01)\n\n- `log_level` accepts lower-cased log level names and rejects invalid\n names ([#138](https://github.com/sloria/environs/pull/138)).\n Thanks [gnarvaja](https://github.com/gnarvaja) for the PR.\n\n## 7.2.0 (2020-02-09)\n\n- Add `dj_cache_url` for caching Django cache URLs (requires installing with `[django]`)\n ([#126](https://github.com/sloria/environs/issues/126)).\n Thanks [epicserve](https://github.com/epicserve) for the suggestion and PR.\n\n## 7.1.0 (2019-12-07)\n\n- Improve typings and run mypy with dependencies type annotations ([#115](https://github.com/sloria/environs/pull/115)).\n- Distribute types per PEP 561 ([#116](https://github.com/sloria/environs/pull/116)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 7.0.0 (2019-12-02)\n\n- _Backwards-incompatible_: Remove `stream` argument from `read_env`,\n since it had no effect ([#114](https://github.com/sloria/environs/pull/114)).\n- _Backwards-incompatible_: `Env.read_env` consistently returns `None`\n ([#111](https://github.com/sloria/environs/pull/111)).\n- Remove unnecessary `__str__` definition ([#112](https://github.com/sloria/environs/pull/112)).\n\nThanks [hukkinj1](https://github.com/hukkinj1) for the PRs.\n\n## 6.1.0 (2019-11-03)\n\nFeatures:\n\n- Add deferred validation via the `eager` parameter and `env.seal()` ([#56](https://github.com/sloria/environs/issues/56)).\n Thanks [robertlagrant](https://github.com/robertlagrant) for the suggestion.\n\nOther changes:\n\n- Test against Python 3.8 ([#108](https://github.com/sloria/environs/pull/108)).\n\n## 6.0.0 (2019-09-22)\n\nFeatures:\n\n- Default parser methods are now defined as bound methods.\n This enables static analysis features, e.g. autocomplete ([#103](https://github.com/sloria/environs/issues/103)).\n Thanks [rugleb](https://github.com/rugleb) for the suggestion.\n _Backwards-incompatible_: As a result of this change, adding a parser name that is the same as an existing method\n will result in an error being raised.\n\n```python\nimport environs\n\nenv = environs.Env()\n\n\n# Below conflicts with built-in `url` method.\n# In <6.0.0, this would override the built-in method.\n# In >=6.0.0, this raises an error:\n# environs.ParserConflictError: Env already has a method with name 'url'. Use a different name.\n@env.parser_for(\"url\")\ndef https_url(value):\n return \"https://\" + value\n```\n\nBug fixes:\n\n- Fix error message for prefixed variables ([#102](https://github.com/sloria/environs/issues/102)).\n Thanks [AGeekInside](https://github.com/AGeekInside) for reporting.\n\nOther changes:\n\n- _Backwards-incompatible_: Rename `Env.__parser_map__` to `Env.__custom_parsers__`.\n\n## 5.2.1 (2019-08-08)\n\nBug fixes:\n\n- Fix behavior when recursively searching for a specified file\n ([#96](https://github.com/sloria/environs/issues/96)).\n Thanks [ribeaud](https://github.com/ribeaud) for the catch and patch.\n\n## 5.2.0 (2019-07-19)\n\nChanges:\n\n- Improve typings.\n\n## 5.1.0 (2019-07-13)\n\nFeatures:\n\n- Add `env.log_level` ([#7](https://github.com/sloria/environs/issues/7)).\n- Use `raise from` to improve tracebacks.\n\nOther changes:\n\n- Improve typings.\n\n## 5.0.0 (2019-07-06)\n\nFeatures:\n\n- Add `env.path` ([#81](https://github.com/sloria/environs/issues/81)).\n Thanks [umrashrf](https://github.com/umrashrf) for the suggestion.\n- Add type annotations.\n\nOther changes:\n\n- _Backwards-incompatible_: Drop support for Python 2. If you use Python 2,\n you will need to use version 4.2.0 or older.\n\n## 4.2.0 (2019-06-01)\n\n- Minor optimization.\n\nBug fixes:\n\n- Reset prefix when an exception is raised within an `env.prefixed()`\n context ([#78](https://github.com/sloria/environs/issues/78)).\n Thanks [rcuza](https://github.com/rcuza) for the catch and patch.\n\n## 4.1.3 (2019-05-15)\n\nBug fixes:\n\n- Fix behavior when passing a `dict` value as the default\n to `env.dict` ([#76](https://github.com/sloria/environs/pull/76)).\n Thanks [c-w](https://github.com/c-w\n... [truncated 2941 chars]\n\n```\n\n### README.md\n```python\n# environs: simplified environment variable parsing\n\n[![Latest version](https://badgen.net/pypi/v/environs)](https://pypi.org/project/environs/)\n[![Build Status](https://github.com/sloria/environs/actions/workflows/build-release.yml/badge.svg)](https://github.com/sloria/environs/actions/workflows/build-release.yml)\n\n**environs** is a Python library for parsing environment variables.\nIt allows you to store configuration separate from your code, as per\n[The Twelve-Factor App](https://12factor.net/config) methodology.\n\n## Contents\n\n\n\n\n- [Features](#features)\n- [Install](#install)\n- [Basic usage](#basic-usage)\n- [Supported types](#supported-types)\n- [Reading `.env` files](#reading-env-files)\n - [Reading a specific file](#reading-a-specific-file)\n- [Handling prefixes](#handling-prefixes)\n- [Variable expansion](#variable-expansion)\n- [Validation](#validation)\n- [Deferred validation](#deferred-validation)\n- [URL schemes](#url-schemes)\n- [Serialization](#serialization)\n- [Reading Docker-style secret files](#reading-docker-style-secret-files)\n- [Defining custom parser behavior](#defining-custom-parser-behavior)\n- [Usage with Flask](#usage-with-flask)\n- [Usage with Django](#usage-with-django)\n- [Why\\...?](#why%5C)\n - [Why envvars?](#why-envvars)\n - [Why not `os.environ`?](#why-not-osenviron)\n - [Why another library?](#why-another-library)\n- [License](#license)\n\n\n\n## Features\n\n- Type-casting\n- Read `.env` files into `os.environ` (useful for local development)\n- Validation\n- Define custom parser behavior\n- Framework-agnostic, but integrates well with [Flask](#usage-with-flask) and [Django](#usage-with-django)\n\n## Install\n\n pip install environs\n\n## Basic usage\n\nWith some environment variables set...\n\n```bash\nexport GITHUB_USER=sloria\nexport MAX_CONNECTIONS=100\nexport SHIP_DATE='1984-06-25'\nexport TTL=42\nexport ENABLE_LOGIN=true\nexport GITHUB_REPOS=webargs,konch,ped\nexport GITHUB_REPO_PRIORITY=\"webargs=2,konch=3\"\nexport LOCATIONS=\"x:234 y:123\"\nexport COORDINATES=23.3,50.0\nexport LOG_LEVEL=DEBUG\n```\n\nParse them with environs...\n\n```python\nfrom environs import env\n\nenv.read_env() # read .env file, if it exists\n# required variables\ngh_user = env(\"GITHUB_USER\") # => 'sloria'\nsecret = env(\"SECRET\") # => raises error if not set\n\n# casting\nmax_connections = env.int(\"MAX_CONNECTIONS\") # => 100\nship_date = env.date(\"SHIP_DATE\") # => datetime.date(1984, 6, 25)\nttl = env.timedelta(\"TTL\") # => datetime.timedelta(seconds=42)\nlog_level = env.log_level(\"LOG_LEVEL\") # => logging.DEBUG\n\n# providing a default value\nenable_login = env.bool(\"ENABLE_LOGIN\", False) # => True\nenable_feature_x = env.bool(\"ENABLE_FEATURE_X\", False) # => False\n\n# parsing lists\ngh_repos = env.list(\"GITHUB_REPOS\") # => ['webargs', 'konch', 'ped']\ncoords = env.list(\"COORDINATES\", subcast=float) # => [23.3, 50.0]\n\n# parsing dicts\ngh_repos_priorities = env.dict(\n \"GITHUB_REPO_PRIORITY\", subcast_values=int\n) # => {'webargs': 2, 'konch': 3}\n\n# parsing dicts with different delimiters\nlocations = env.dict(\n \"LOCATIONS\", subcast_values=int, delimiter=\" \", key_value_delimiter=\":\"\n) # => {'x': 234, 'y': 123}\n```\n\n## Supported types\n\nThe following are all type-casting methods of `Env`:\n\n- `env.str`\n- `env.bool`\n- `env.int`\n- `env.float`\n- `env.decimal`\n- `env.list` (accepts optional `subcast` and `delimiter` keyword arguments)\n- `env.dict` (accepts optional `subcast_keys`, `subcast_values`, `delimiter`, and `key_value_delimiter` keyword arguments)\n- `env.json`\n- `env.datetime`\n- `env.date`\n- `env.time`\n- `env.timedelta` (assumes value is an integer in seconds, or an ordered duration string like `7h7s` or `7w 7d 7h 7m 7s 7ms 7us`)\n- `env.url`\n - This returns a `urllib.parse.ParseResult` and therefore expects a `ParseResult` for its default.\n\n```python\nfrom urllib.parse import urlparse\n\nfrom environs import env\n\nMY_API_URL = env.url(\n \"MY_API_URL\",\n default=urlparse(\"http://api.example.com\"),\n)\n```\n\nIf you want the return value to be a string, use `env.str` with `validate.URL` instead.\n\n```python\nfrom environs import env, validate\n\nMY_API_URL = env.str(\n \"MY_API_URL\",\n default=\"http://api.example.com\",\n validate=validate.URL(),\n)\n```\n\n- `env.uuid`\n- `env.log_level`\n- `env.path` (casts to a [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html))\n- `env.enum` (casts to any given enum type specified in `enum` keyword argument)\n - Pass `by_value=True` to parse and validate by the Enum's values.\n\n## Reading `.env` files\n\n```bash\n# .env\nDEBUG=true\nPORT=4567\n```\n\nCall `Env.read_env` before parsing variables.\n\n```python\nfrom environs import env\n\n# Read .env into os.environ\nenv.read_env()\n\nenv.bool(\"DEBUG\") # => True\nenv.int(\"PORT\") # => 4567\n```\n\n### Reading a specific file\n\nBy default, `Env.read_env` will look for a `.env` file in current\ndirectory and (if no .env exists in the CWD) recurse\nupwards until a `.env` file is found.\n\nYou can also read a specific file:\n\n```python\nfrom environs import env\n\nwith open(\".env.test\", \"w\") as fobj:\n fobj.write(\"A=foo\\n\")\n fobj.write(\"B=123\\n\")\n\nenv.read_env(\".env.test\", recurse=False)\n\nassert env(\"A\") == \"foo\"\nassert env.int(\"B\") == 123\n```\n\n## Handling prefixes\n\nPass `prefix` to the constructor if all your environment variables have the same prefix.\n\n```python\nfrom environs import Env\n\n# export MYAPP_HOST=lolcathost\n# export MYAPP_PORT=3000\n\n\nenv = Env(prefix=\"MYAPP_\")\n\nhost = env(\"HOST\", \"localhost\") # => 'lolcathost'\nport = env.int(\"PORT\", 5000) # => 3000\n```\n\nAlternatively, you can use the `prefixed` context manager.\n\n```python\nfrom environs import env\n\n# export MYAPP_HOST=lolcathost\n# export MYAPP_PORT=3000\n\nwith env.prefixed(\"MYAPP_\"):\n host = env(\"HOST\", \"localhost\") # => 'lolcathost'\n port = env.int(\"PORT\", 5000) # => 3000\n\n# nested prefixes are also supported:\n\n# export MYAPP_DB_HOST=lolcathost\n# export MYAPP_DB_PORT=10101\n\nwith env.prefixed(\"MYAPP_\"):\n with env.prefixed(\"DB_\"):\n db_host = env(\"HOST\", \"lolcathost\")\n db_port = env.int(\"PORT\", 10101)\n```\n\n## Variable expansion\n\n```python\n# export CONNECTION_URL=https://${USER:-sloria}:${PASSWORD}@${HOST:-localhost}/\n# export PASSWORD=secret\n# export YEAR=${CURRENT_YEAR:-2020}\n\nfrom environs import Env\n\nenv = Env(expand_vars=True)\n\nconnection_url = env(\"CONNECTION_URL\") # =>'https://sloria:secret@localhost'\nyear = env.int(\"YEAR\") # =>2020\n```\n\n## Validation\n\n```python\n# export TTL=-2\n# export NODE_ENV='invalid'\n# export EMAIL='^_^'\n\nfrom environs import env, validate, ValidationError\n\n\n# built-in validators (provided by marshmallow)\nenv.str(\n \"NODE_ENV\",\n validate=validate.OneOf(\n [\"production\", \"development\"], error=\"NODE_ENV must be one of: {choices}\"\n ),\n)\n# => Environment variable \"NODE_ENV\" invalid: ['NODE_ENV must be one of: production, development']\n\n# multiple validators\nenv.str(\"EMAIL\", validate=[validate.Length(min=4), validate.Email()])\n# => Environment variable \"EMAIL\" invalid: ['Shorter than minimum length 4.', 'Not a valid email address.']\n\n\n# custom validator\ndef validator(n):\n if n <= 0:\n raise ValidationError(\"Invalid value.\")\n\n\nenv.int(\"TTL\", validate=validator)\n# => Environment variable \"TTL\" invalid: ['Invalid value.']\n```\n\n`environs.validate` is equivalent to [`marshmallow.validate`](https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html), so you can use any of the validators provided by that module.\n\n## Deferred validation\n\nBy default, a validation error is raised immediately upon calling a parser method for an invalid environment variable.\nTo defer validation and raise an exception with the combined error messages for all invalid variables, pass `eager=False` to `Env`.\nCall `env.seal()` after all variables have been parsed.\n\n```python\n# export TTL=-2\n# export NODE_ENV='invalid'\n# export EMAIL='^_^'\n\nfrom environs import Env\nfrom marshmallow.validate import OneOf, Email, Length, Range\n\nenv = Env(eager=False)\n\nTTL = env.int(\"TTL\", validate=Range(min=0, max=100))\nNODE_ENV = env.str(\n \"NODE_ENV\",\n validate=OneOf(\n [\"production\", \"development\"], error=\"NODE_ENV must be one of: {choices}\"\n ),\n)\nEMAIL = env.str(\"EMAIL\", validate=[Length(min=4), Email()])\n\nenv.seal()\n# environs.EnvValidationError: Environment variables invalid: {'TTL': ['Must be greater than or equal to 0 and less than or equal to 100.'], 'NODE_ENV': ['NODE_ENV must be one of: production, development'], 'EMAIL': ['Shorter than minimum length 4.', 'Not a valid email address.']}\n```\n\n`env.seal()` validates all parsed variables and prevents further parsing (calling a parser method will raise an error).\n\n## URL schemes\n\n`env.url()` supports non-standard URL schemes via the `schemes` argument.\n\n```python\nfrom urllib.parse import urlparse\n\nREDIS_URL = env.url(\n \"REDIS_URL\", urlparse(\"redis://redis:6379\"), schemes=[\"redis\"], require_tld=False\n)\n```\n\n## Serialization\n\n```python\n# serialize to a dictionary of simple types (numbers and strings)\nenv.dump()\n# {'COORDINATES': [23.3, 50.0],\n# 'ENABLE_FEATURE_X': False,\n# 'ENABLE_LOGIN': True,\n# 'GITHUB_REPOS': ['webargs', 'konch', 'ped'],\n# 'GITHUB_USER': 'sloria',\n# 'MAX_CONNECTIONS': 100,\n# 'MYAPP_HOST': 'lolcathost',\n# 'MYAPP_PORT': 3000,\n# 'SHIP_DATE': '1984-06-25',\n# 'TTL': 42}\n```\n\n## Reading Docker-style secret files\n\nSome values should not be stored in the environment. For this use case a commonly\nused technique is to store the value (e.g., a password) in a file and set the path\nto that file in an environment variable. Use `FileAwareEnv` in place of `Env` to automatically check for environment variables with the `_FILE` suffix. If the\nfile is found, its contents will be read and returned.\n\n```python\nfrom environs import FileAwareEnv\n\n# echo 'my secret password' > /run/secrets/password\n# export PASSWORD_FILE=/run/secrets/password\n\nenv = FileAwareEnv()\npassword = env.str(\"PASSWORD\") # => 'my secret password'\n```\n\nIt's also possible to set a different suffix for the variable names:\n\n```python\nfrom environs import FileAwareEnv\n\n# echo 'my secret password' > /run/secrets/password\n# export PASSWORD_SECRET=/run/secrets/password\n\nenv = FileAwareEnv(file_suffix=\"_SECRET\")\npassword = env.str(\"PASSWORD\") # => 'my secret password'\n```\n\n## Defining custom parser behavior\n\n```python\n# export DOMAIN='http://myapp.com'\n# export COLOR=invalid\n\nfrom furl import furl\n\n\n# Register a new parser method for paths\n@env.parser_for(\"furl\")\ndef furl_parser(value):\n return furl(value)\n\n\ndomain = env.furl(\"DOMAIN\") # => furl('https://myapp.com')\n\n\n# Custom parsers can take extra keyword arguments\n@env.parser_for(\"choice\")\ndef choice_parser(value, choices):\n if value not in choices:\n raise environs.EnvError(\"Invalid!\")\n return value\n\n\ncolor = env.choice(\"COLOR\", choices=[\"black\"]) # => raises EnvError\n```\n\n## Usage with Flask\n\n```python\n# myapp/settings.py\n\nfrom environs import Env\n\nenv = Env()\nenv.read_env()\n\n# Override in .env for local development\nDEBUG = env.bool(\"FLASK_DEBUG\", default=False)\n# SECRET_KEY is required\nSECRET_KEY = env.str(\"SECRET_KEY\")\n```\n\nLoad the configuration after you initialize your app.\n\n```python\n# myapp/app.py\n\nfrom flask import Flask\n\napp = Flask(__name__)\napp.config.from_object(\"myapp.settings\")\n```\n\nFor local development, use a `.env` file to override the default\nconfiguration.\n\n```bash\n# .env\nDEBUG=true\nSECRET_KEY=\"not so secret\"\n```\n\nNote: Because environs depends on [python-dotenv](https://github.com/theskumar/python-dotenv),\nthe `flask` CLI will automatically read .env and .flaskenv files.\n\n## Usage with Django\n\nenvirons includes a number of helpers for parsing connection URLs. To\ninstall environs with django support:\n\n pip install environs[django]\n\nUse `env.dj_db_url`, `env.dj_cache_url` and `env.dj_email_url` to parse the `DATABASE_URL`, `CACHE_URL`\nand `EMAIL_URL` environment variables, respectively.\n\nFor more details on URL patterns, see the following projects that environs is using for converting URLs.\n\n- [dj-database-url](https://github.com/jacobian/dj-database-url)\n- [django-cache-url](https://github.com/epicserve/django-cache-url)\n- [dj-email-url](https://github.com/migonzalvar/dj-email-url)\n\nBasic example:\n\n```python\n# myproject/settings.py\nfrom environs import Env\n\nenv = Env()\nenv.read_env()\n\n# Override in .env for local development\nDEBUG = env.bool(\"DEBUG\", default=False)\n# SECRET_KEY is required\nSECRET_KEY = env.str(\"SECRET_KEY\")\n\n# Parse database URLs, e.g. \"postgres://localhost:5432/mydb\"\nDATABASES = {\"default\": env.dj_db_url(\"DATABASE_URL\")}\n\n# Parse email URLs, e.g. \"smtp://\"\nemail = env.dj_email_url(\"EMAIL_URL\", default=\"smtp://\")\nEMAIL_HOST = email[\"EMAIL_HOST\"]\nEMAIL_PORT = email[\"EMAIL_PORT\"]\nEMAIL_HOST_PASSWORD = email[\"EMAIL_HOST_PASSWORD\"]\nEMAIL_HOST_USER = email[\"EMAIL_HOST_USER\"]\nEMAIL_USE_TLS = email[\"EMAIL_USE_TLS\"]\n\n# Parse cache URLS, e.g \"redis://localhost:6379/0\"\nCACHES = {\"default\": env.dj_cache_url(\"CACHE_URL\")}\n```\n\nFor local development, use a `.env` file to override the default\nconfiguration.\n\n```bash\n# .env\nDEBUG=true\nSECRET_KEY=\"not so secret\"\n```\n\nFor a more complete example, see\n[django_example.py](https://github.com/sloria/environs/blob/master/examples/django_example.py)\nin the `examples/` directory.\n\n## Why\\...?\n\n### Why envvars?\n\nSee [The 12-factor App](http://12factor.net/config) section on\n[configuration](http://12factor.net/config).\n\n### Why not `os.environ`?\n\nWhile `os.environ` is enough for simple use cases, a typical application\nwill need a way to manipulate and validate raw environment variables.\nenvirons abstracts common tasks for handling environment variables.\n\nenvirons will help you\n\n- cast envvars to the correct type\n- specify required envvars\n- define default values\n- validate envvars\n- parse list and dict values\n- parse dates, datetimes, and timedeltas\n- parse expanded variables\n- serialize your configuration to JSON, YAML, etc.\n\n### Why another library?\n\nThere are many great Python libraries for parsing environment variables.\nIn fact, most of the credit for environs\\' public API goes to the\nauthors of [envparse](https://github.com/rconradharris/envparse) and\n[django-environ](https://github.com/joke2k/django-environ).\n\nenvirons aims to meet three additional goals:\n\n1. Make it easy to extend parsing behavior and develop plugins.\n2. Leverage the deserialization and validation functionality provided\n by a separate library (marshmallow).\n3. Clean up redundant API.\n\nSee [this GitHub\nissue](https://github.com/rconradharris/envparse/issues/12#issue-151036722)\nwhich details specific differences with envparse.\n\n## License\n\nMIT licensed. See the\n[LICENSE](https://github.com/sloria/environs/blob/master/LICENSE) file\nfor more details.\n\n```\n\n### src/environs/__init__.py\n```python\nfrom __future__ import annotations\n\nimport collections\nimport contextlib\nimport functools\nimport inspect\nimport json as pyjson\nimport os\nimport re\nimport typing\nfrom collections.abc import Mapping\nfrom pathlib import Path\n\nimport marshmallow as ma\nfrom dotenv.main import _walk_to_root, load_dotenv\n\nfrom . import fields\nfrom .exceptions import (\n EnvError,\n EnvSealedError,\n EnvValidationError,\n ParserConflictError,\n)\n\nif typing.TYPE_CHECKING:\n import datetime as dt\n import decimal\n import uuid\n from urllib.parse import ParseResult\n\n from .types import (\n DictFieldMethod,\n EnumFieldMethod,\n ErrorMapping,\n FieldFactory,\n FieldMethod,\n ListFieldMethod,\n ParserMethod,\n Subcast,\n TimeDeltaFieldMethod,\n )\n\n try:\n from dj_database_url import DBConfig\n except ImportError:\n pass\n\n__all__ = [\"Env\", \"EnvError\", \"FileAwareEnv\", \"ValidationError\", \"env\"]\n\n_T = typing.TypeVar(\"_T\")\n_StrType = str\n_BoolType = bool\n_IntType = int\n_ListType = list\n_DictType = dict\n\n_EXPANDED_VAR_PATTERN = re.compile(r\"(? typing.Any:\n def method(\n self: Env,\n name: str,\n default: typing.Any = ...,\n subcast: Subcast[_T] | None = None,\n *,\n # Subset of relevant marshmallow.Field kwargs\n validate: (\n typing.Callable[[typing.Any], typing.Any]\n | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]\n | None\n ) = None,\n # Additional kwargs are passed to Field constructor\n **kwargs,\n ) -> _T | None:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\",\n )\n load_default = default if default is not Ellipsis else ma.missing\n preprocess_kwargs = {\n name: kwargs.pop(name) for name in preprocess_kwarg_names if name in kwargs\n }\n if isinstance(field_or_factory, type) and issubclass(\n field_or_factory,\n ma.fields.Field,\n ):\n field = field_or_factory(\n validate=validate,\n load_default=load_default,\n **kwargs,\n )\n else:\n parsed_subcast = _make_subcast_field(subcast) if subcast else ma.fields.Raw\n field = typing.cast(\"FieldFactory\", field_or_factory)(\n subcast=parsed_subcast,\n validate=validate,\n load_default=load_default,\n )\n parsed_key, value, proxied_key = self._get_from_environ(name, default=Ellipsis)\n self._fields[parsed_key] = field\n source_key = proxied_key or parsed_key\n if value is Ellipsis:\n if default is not Ellipsis:\n self._values[parsed_key] = default\n return default\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set',\n )\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n try:\n if preprocess:\n value = preprocess(value, **preprocess_kwargs)\n value = field.deserialize(value)\n except ma.ValidationError as error:\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n error.messages,\n ) from error\n self._errors[parsed_key].extend(error.messages)\n else:\n self._values[parsed_key] = value\n return typing.cast(\"typing.Optional[_T]\", value)\n\n method.__name__ = method_name\n return method\n\n\ndef _func2method(func: typing.Callable[..., _T], method_name: str) -> typing.Any:\n def method(\n self: Env,\n name: str,\n default: typing.Any = ...,\n **kwargs,\n ) -> _T | None:\n if self._sealed:\n raise EnvSealedError(\n \"Env has already been sealed. New values cannot be parsed.\",\n )\n parsed_key, raw_value, proxied_key = self._get_from_environ(name, default)\n self._fields[parsed_key] = ma.fields.Raw()\n source_key = proxied_key or parsed_key\n if raw_value is Ellipsis:\n if self.eager:\n raise EnvError(\n f'Environment variable \"{proxied_key or parsed_key}\" not set',\n )\n self._errors[parsed_key].append(\"Environment variable not set.\")\n return None\n if raw_value or raw_value == \"\": # noqa: SIM108\n value = raw_value\n else:\n value = None\n try:\n value = func(raw_value, **kwargs)\n except (EnvError, ma.ValidationError) as error:\n messages = (\n error.messages\n if isinstance(error, ma.ValidationError)\n else [error.args[0]]\n )\n if self.eager:\n raise EnvValidationError(\n f'Environment variable \"{source_key}\" invalid: {error.args[0]}',\n messages,\n ) from error\n self._errors[parsed_key].extend(messages)\n else:\n self._values[parsed_key] = value\n return typing.cast(\"typing.Optional[_T]\", value)\n\n method.__name__ = method_name\n return method\n\n\ndef _make_subcast_field(\n subcast: Subcast,\n) -> type[ma.fields.Field]:\n if isinstance(subcast, type) and subcast in ma.Schema.TYPE_MAPPING:\n inner_field = ma.Schema.TYPE_MAPPING[subcast]\n elif isinstance(subcast, type) and issubclass(subcast, ma.fields.Field):\n inner_field = subcast\n elif callable(subcast):\n\n class SubcastField(ma.fields.Field):\n def _deserialize(self, value, *args, **kwargs):\n return subcast(value)\n\n inner_field = SubcastField\n else:\n inner_field = ma.fields.Raw\n return inner_field\n\n\ndef _make_list_field(*, subcast: Subcast | None, **kwargs) -> ma.fields.List:\n inner_field = _make_subcast_field(subcast) if subcast else ma.fields.Raw\n return ma.fields.List(inner_field, **kwargs)\n\n\ndef _preprocess_list(\n value: str | typing.Iterable,\n *,\n delimiter: str = \",\",\n **kwargs,\n) -> typing.Iterable:\n if ma.utils.is_iterable_but_not_string(value) or value is None:\n return value\n return typing.cast(\"str\", value).split(delimiter) if value != \"\" else []\n\n\ndef _preprocess_dict(\n value: str | typing.Mapping,\n *,\n subcast_keys: Subcast | None = None,\n subcast_values: Subcast | None = None,\n delimiter: str = \",\",\n key_value_delimiter: str = \"=\",\n **kwargs,\n) -> typing.Mapping:\n if isinstance(value, Mapping):\n return value\n subcast_keys_instance: ma.fields.Field\n if subcast_keys:\n subcast_keys_instance = _make_subcast_field(subcast_keys)(**kwargs)\n else:\n subcast_keys_instance = ma.fields.Raw()\n subcast_values_instance: ma.fields.Field\n if subcast_values:\n subcast_values_instance = _make_subcast_field(subcast_values)(**kwargs)\n else:\n subcast_values_instance = ma.fields.Raw()\n\n return {\n subcast_keys_instance.deserialize(\n key.strip(),\n ): subcast_values_instance.deserialize(val.strip())\n for key, val in (\n item.split(key_value_delimiter, 1) for item in value.split(delimiter) if value\n )\n }\n\n\ndef _preprocess_json(value: str | typing.Mapping | list, **kwargs):\n try:\n if isinstance(value, str):\n return pyjson.loads(value)\n if isinstance(value, (dict, list)) or value is None:\n return value\n raise ma.ValidationError(\"Not valid JSON.\")\n except pyjson.JSONDecodeError as error:\n raise ma.ValidationError(\"Not valid JSON.\") from error\n\n\ndef _dj_db_url_parser(value: str, **kwargs) -> DBConfig:\n try:\n import dj_database_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_db_url parser requires the dj-database-url package. \"\n \"You can install it with: pip install dj-database-url\",\n ) from error\n try:\n return dj_database_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid database URL.\") from error\n\n\ndef _dj_email_url_parser(value: str, **kwargs) -> dict:\n try:\n import dj_email_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_email_url parser requires the dj-email-url package. \"\n \"You can install it with: pip install dj-email-url\",\n ) from error\n try:\n return dj_email_url.parse(value, **kwargs)\n except Exception as error:\n raise ma.ValidationError(\"Not a valid email URL.\") from error\n\n\ndef _dj_cache_url_parser(value: str, **kwargs) -> dict:\n try:\n import django_cache_url # noqa: PLC0415\n except ImportError as error:\n raise RuntimeError(\n \"The dj_cache_url parser requires the django-cache-url package. \"\n \"You can install it with: pip install django-cache-url\",\n ) from error\n try:\n return django_cache_url.parse(value, **kwargs)\n except Exception as error:\n # django_cache_url may raise Exception(\"Unknown backend...\")\n # so use that error message in the validation error\n raise ma.ValidationError(error.args[0]) from error\n\n\nclass Env:\n \"\"\"An environment variable reader.\"\"\"\n\n __call__: FieldMethod[typing.Any] = _field2method(ma.fields.Raw, \"__call__\")\n\n int: FieldMethod[int] = _field2method(ma.fields.Int, \"int\")\n bool: FieldMethod[bool] = _field2method(ma.fields.Bool, \"bool\")\n str: FieldMethod[str] = _field2method(ma.fields.Str, \"str\")\n float: FieldMethod[float] = _field2method(ma.fields.Float, \"float\")\n decimal: FieldMethod[decimal.Decimal] = _field2method(ma.fields.Decimal, \"decimal\")\n list: ListFieldMethod = _field2method(\n _make_list_field,\n \"list\",\n preprocess=_preprocess_list,\n preprocess_kwarg_names=(\"subcast\", \"delimiter\"),\n )\n dict: DictFieldMethod = _field2method(\n ma.fields.Dict,\n \"dict\",\n preprocess=_preprocess_dict,\n preprocess_kwarg_names=(\n \"subcast_keys\",\n \"subcast_key\",\n \"subcast_values\",\n \"delimiter\",\n \"key_value_delimiter\",\n ),\n )\n json: FieldMethod[_ListType | _DictType] = _field2method(\n ma.fields.Raw,\n \"json\",\n preprocess=_preprocess_json,\n )\n datetime: FieldMethod[dt.datetime] = _field2method(ma.fields.DateTime, \"datetime\")\n date: FieldMethod[dt.date] = _field2method(ma.fields.Date, \"date\")\n time: FieldMethod[dt.time] = _field2method(ma.fields.Time, \"time\")\n timedelta: TimeDeltaFieldMethod = _field2method(fields.TimeDelta, \"timedelta\")\n path: FieldMethod[Path] = _field2method(fields.Path, \"path\")\n log_level: FieldMethod[_IntType] = _field2method(fields.LogLevel, \"log_level\")\n\n uuid: FieldMethod[uuid.UUID] = _field2method(ma.fields.UUID, \"uuid\")\n url: FieldMethod[ParseResult] = _field2method(fields.Url, \"url\")\n\n enum: EnumFieldMethod = _field2method(ma.fields.Enum, \"enum\")\n dj_db_url = _func2method(_dj_db_url_parser, \"dj_db_url\")\n dj_email_url = _func2method(_dj_email_url_parser, \"dj_email_url\")\n dj_cache_url = _func2method(_dj_cache_url_parser, \"dj_cache_url\")\n\n def __init__(\n self,\n *,\n eager: _BoolType = True,\n expand_vars: _BoolType = False,\n prefix: _StrType | None = None,\n ):\n self.eager = eager\n self._sealed: bool = False\n self.expand_vars = expand_vars\n self._fields: dict[_StrType, ma.fields.Field] = {}\n self._values: dict[_StrType, typing.Any] = {}\n self._errors: ErrorMapping = collections.defaultdict(list)\n self._prefix: _StrType | None = prefix\n self.__custom_parsers__: dict[_StrType, ParserMethod] = {}\n\n def __repr__(self) -> _StrType:\n return f\"<{self.__class__.__name__}(eager={self.eager}, expand_vars={self.expand_vars})>\"\n\n @staticmethod\n def read_env(\n path: _StrType | Path | None = None,\n *,\n recurse: _BoolType = True,\n verbose: _BoolType = False,\n override: _BoolType = False,\n return_path: _BoolType = False,\n ) -> _BoolType | _StrType | None:\n \"\"\"Read a .env file into os.environ.\n\n If .env is not found in the directory from which this method is called,\n the default behavior is to recurse up the directory tree until a .env\n file is found. If you do not wish to recurse up the tree, you may pass\n False as a second positional argument.\n \"\"\"\n env_path = None\n is_env_loaded = False\n if path is None:\n # By default, start search from the same directory this function is called\n current_frame = inspect.currentframe()\n if current_frame is None:\n raise RuntimeError(\"Could not get current call frame.\")\n frame = current_frame.f_back\n assert frame is not None # noqa: S101\n caller_dir = Path(frame.f_code.co_filename).parent.resolve()\n start = caller_dir / \".env\"\n else:\n if Path(path).is_dir():\n raise ValueError(\"path must be a filename, not a directory.\")\n start = Path(path)\n if recurse:\n start_dir, env_name = os.path.split(start)\n if not start_dir: # Only a filename was given\n start_dir = os.getcwd()\n for dirname in _walk_to_root(start_dir):\n check_path = Path(dirname) / env_name\n if check_path.exists():\n is_env_loaded = load_dotenv(\n check_path,\n verbose=verbose,\n override=override,\n )\n env_path = str(check_path)\n break\n\n else:\n is_env_loaded = load_dotenv(str(start), verbose=verbose, override=override)\n env_path = str(start)\n\n if return_path:\n return env_path\n return is_env_loaded\n\n @contextlib.contextmanager\n def prefixed(self, prefix: _StrType) -> typing.Iterator[Env]:\n \"\"\"Context manager for parsing envvars with a common prefix.\"\"\"\n try:\n old_prefix = self._prefix\n if old_prefix is None:\n self._prefix = prefix\n else:\n self._prefix = f\"{old_prefix}{prefix}\"\n yield self\n finally:\n # explicitly reset the stored prefix on completion and exceptions\n self._prefix = None\n self._prefix = old_prefix\n\n def seal(self):\n \"\"\"Validate parsed values and prevent new values from being added.\n\n :raises: environs.EnvValidationError\n \"\"\"\n self._sealed = True\n if self._errors:\n error_messages = dict(self._errors)\n self._errors = {}\n raise EnvValidationError(\n f\"Environment variables invalid: {error_messages}\",\n error_messages,\n )\n\n def __getattr__(self, name: _StrType):\n try:\n return functools.partial(self.__custom_parsers__[name], self)\n except KeyError as error:\n raise AttributeError(f\"{se\n... [truncated 5688 chars]\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "sloria__environs-aa99f02fb39d", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/sloria__environs-aa99f02fb39d", "repo_key": "sloria__environs", "repo": "sloria/environs", "base_commit": "7ed9ec4cf3fc27c83efd8fe8d29a442a09a457d0", "source_files": ["CHANGELOG.md", "README.md", "src/environs/__init__.py"]}} {"prompt": [{"role": "system", "content": "You are an expert Python software engineer. You will be given a bug report for a repository and the current contents of the relevant source files. Produce a fix as a single unified diff against the repository root, inside one ```diff fenced block, and nothing else. Do not modify or add tests."}, {"role": "user", "content": "# Issue\n\n**Title:** Numeric literal validation incorrectly handles negative numbers and leading zeros\n\n## Description\nThe current numeric literal validation logic incorrectly processes values that include a negative sign or leading zeros. For instance, a valid negative number like `-123` might be flagged as invalid, or an invalid number with leading zeros such as `0123` might be incorrectly accepted as a valid decimal literal. The expected behavior is for the validator to correctly identify and accept valid negative numbers and reject invalid numeric literals with leading zeros (e.g., `0123` should be rejected, while `0` should be accepted).\n\n## Task\n\nModify the repository so that the issue described above is resolved. The task's test suite verifies your patch by applying it on top of the base commit `6b26984a0127` and running the modified tests.\n\n## Relevant files (at the current commit)\n\n### src/toon_format/_literal_utils.py\n```python\n# Copyright (c) 2025 TOON Format Organization\n# SPDX-License-Identifier: MIT\n\"\"\"Utilities for detecting literal token types.\n\nThis module provides functions to identify different types of literal\nvalues in TOON syntax, such as booleans, null, and numeric literals.\nUsed during decoding to distinguish between literal values and strings.\n\"\"\"\n\nfrom .constants import FALSE_LITERAL, NULL_LITERAL, TRUE_LITERAL\n\n\ndef is_boolean_or_null_literal(token: str) -> bool:\n \"\"\"Check if a token is a boolean or null literal (`true`, `false`, `null`).\n\n Args:\n token: The token to check\n\n Returns:\n True if the token is a boolean or null literal\n\n Examples:\n >>> is_boolean_or_null_literal(\"true\")\n True\n >>> is_boolean_or_null_literal(\"null\")\n True\n >>> is_boolean_or_null_literal(\"hello\")\n False\n \"\"\"\n return token == TRUE_LITERAL or token == FALSE_LITERAL or token == NULL_LITERAL\n\n\ndef is_numeric_literal(token: str) -> bool:\n \"\"\"Check if a token represents a valid numeric literal.\n\n Rejects numbers with leading zeros (except `\"0\"` itself or decimals like `\"0.5\"`).\n Per Section 7.3 of the TOON specification.\n\n Args:\n token: The token to check\n\n Returns:\n True if the token is a valid numeric literal\n\n Examples:\n >>> is_numeric_literal(\"42\")\n True\n >>> is_numeric_literal(\"3.14\")\n True\n >>> is_numeric_literal(\"0.5\")\n True\n >>> is_numeric_literal(\"0123\") # Leading zero - not valid\n False\n >>> is_numeric_literal(\"hello\")\n False\n \"\"\"\n if not token:\n return False\n\n # Must not have leading zeros (except for `\"0\"` itself or decimals like `\"0.5\"`)\n if len(token) > 1 and token[0] == \"0\" and token[1] != \".\":\n return False\n\n # Check if it's a valid number\n try:\n num = float(token)\n # Reject NaN and infinity\n return not (num != num or not (-float(\"inf\") < num < float(\"inf\")))\n except ValueError:\n return False\n\n```\n\nReturn the fix as one unified diff in a ```diff block."}], "label": "toon-format__toon-python-728120d9bb03", "metadata": {"task_dir": "/Users/beneecs/work/projects/openrsi/code/assets/release/heldout/toon-format__toon-python-728120d9bb03", "repo_key": "toon-format__toon-python", "repo": "toon-format/toon-python", "base_commit": "6b26984a01279defdcf40ab9d09bc418fe8133ac", "source_files": ["src/toon_format/_literal_utils.py"]}}