internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: codespell-project/codespell

Issue:
Report when we're using setup.cfg, .codespellrc, pyproject.toml etc
identified in https://github.com/bids-standard/bids-specification/pull/1322#issuecomment-1280914648

How to reproduce:

- run a basic codespell GH action (without passing `with:` arguments)
- add a `.codespellrc` configuration file to the repo root
- the config file **is** being observed BUT
- the "argument summary" in the GH actions log is not reflecting that

![image](https://user-images.githubusercontent.com/9084751/196197800-7c5be6d3-6204-4535-83cd-4eb0db93ce2f.png)


Discussion:
Pedantically I think that's accurate. If you run the same command locally, without any options, you'd get the same behaviour.

For me as a user that was the thinking too, if I want to recreate it on the command line locally, that's all I should need to know.
For consistency and clarity it would be good to say what we're using out of `setup.cfg`, `.codespellrc`, `pyproject.toml` both from the command-line and this action. @sappelhoff up for a PR to codespell first to add it there (probably via some verbosity level if not already present), then the action could just inherit the behavior?
I'll put it on my list and will look into it :heavy_check_mark: 
I've moved this to the main codespell repo now and tweaked the title given it's not directly action specific.

Resolving patch:
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -423,8 +423,17 @@ def parse_options(args):
         with open(toml_file, 'rb') as f:
             data = tomli.load(f).get('tool', {})
         config.read_dict(data)
-    config.read(cfg_files)
 
+    # Collect which config files are going to be used
+    used_cfg_files = []
+    for cfg_file in cfg_files:
+        _cfg = configparser.ConfigParser()
+        _cfg.read(cfg_file)
+        if _cfg.has_section('codespell'):
+            used_cfg_files.append(cfg_file)
+
+    # Use config files
+    config.read(cfg_files)
     if config.has_section('codespell'):
         # Build a "fake" argv list using option name and value.
         cfg_args = []
@@ -445,7 +454,7 @@ def parse_options(args):
     if not options.files:
         options.files.append('.')
 
-    return options, parser
+    return options, parser, used_cfg_files
 
 
 def parse_ignore_words_option(ignore_words_option):
@@ -776,7 +785,13 @@ def _script_main():
 
 def main(*args):
     """Contains flow control"""
-    options, parser = parse_options(args)
+    options, parser, used_cfg_files = parse_options(args)
+
+    # Report used config files
+    if len(used_cfg_files) > 0:
+        print('Used config files:')
+    for ifile, cfg_file in enumerate(used_cfg_files, start=1):
+        print('    %i: %s' % (ifile, cfg_file))
 
     if options.regex and options.write_changes:
         print("ERROR: --write-changes cannot be used together with "


Test patch:
Repository: codespell-project/codespell

Issue:
`python setup.py check` → `twine check`
Because `setup.py ...` is deprecated, we need an alternative to `setup.py check` such as `twine`.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
deleted file mode 100755
--- a/setup.py
+++ /dev/null
@@ -1,6 +0,0 @@
-#! /usr/bin/env python
-
-from setuptools import setup
-
-if __name__ == "__main__":
-    setup()


Test patch:
Repository: codespell-project/codespell

Issue:
codespell toml parsing with python 3.11
Hi,

this seems not to work currently.

the pyproject.toml

```yaml
toml = [
    "tomli; python_version < '3.11'"
]
```

but without tomli nothing will be parsed, because nowhere the python 3.11 stdlib tomlib gets imported and used.


Discussion:

Resolving patch:
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -544,25 +544,29 @@ def parse_options(
     config = configparser.ConfigParser(interpolation=None)
 
     # Read toml before other config files.
-    toml_files_errors = []
+    toml_files = []
+    tomlib_raise_error = False
     if os.path.isfile("pyproject.toml"):
-        toml_files_errors.append(("pyproject.toml", False))
+        toml_files.append("pyproject.toml")
     if options.toml:
-        toml_files_errors.append((options.toml, True))
-    for toml_file, raise_error in toml_files_errors:
+        toml_files.append(options.toml)
+        tomlib_raise_error = True
+    if toml_files:
         try:
-            import tomli
-        except Exception as exc:
-            if raise_error:
-                raise ImportError(
-                    f"tomli is required to read pyproject.toml but could not "
-                    f"be imported, got: {exc}"
-                ) from None
-            else:
-                continue
-        with open(toml_file, "rb") as f:
-            data = tomli.load(f).get("tool", {})
-        config.read_dict(data)
+            import tomlib  # type: ignore
+        except ModuleNotFoundError:
+            try:
+                import tomli as tomlib  # type: ignore
+            except ImportError as e:
+                if tomlib_raise_error:
+                    raise ImportError(
+                        f"tomlib or tomli are required to read pyproject.toml "
+                        f"but could not be imported, got: {e}"
+                    ) from None
+        for toml_file in toml_files:
+            with open(toml_file, "rb") as f:
+                data = tomlib.load(f).get("tool", {})
+            config.read_dict(data)
 
     # Collect which config files are going to be used
     used_cfg_files = []


Test patch:
Repository: codespell-project/codespell

Issue:
Default word regex and grave accent (`)
Why include the grave accent (**&#x0060;**) in the default word regex?

https://github.com/codespell-project/codespell/blob/2eeb8b992e7fec4940a12bdac5e8837f0ffd6c98/codespell_lib/_codespell.py#L31

This messes up Markdown checking, just for the sake of catching these two typos:
```
coulden`t->couldn't
woulden`t->wouldn't
```
These two fixes don't really make sense, we don't even catch the same typos with the apostrophe (**&#x0027;**) or acute accent (**&#x00B4;**), :
```
coulden't->couldn't
coulden´t->couldn't
woulden't->wouldn't
woulden´t->wouldn't
```


Discussion:

Resolving patch:
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -28,7 +28,7 @@
 # autogenerated by setuptools_scm
 from ._version import __version__ as VERSION  # type: ignore  # noqa: N812
 
-word_regex_def = "[\\w\\-'’`]+"
+word_regex_def = r"[\w\-'’]+"
 # While we want to treat characters like ( or " as okay for a starting break,
 # these may occur unescaped in URIs, and so we are more restrictive on the
 # endpoint.  Emails are more restrictive, so the endpoint remains flexible.
@@ -402,7 +402,7 @@ def parse_options(
         type=str,
         help="regular expression that is used to find words. "
         "By default any alphanumeric character, the "
-        "underscore, the hyphen, and the apostrophe is "
+        "underscore, the hyphen, and the apostrophe are "
         "used to build words. This option cannot be "
         "specified together with --write-changes.",
     )


Test patch:
diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py
--- a/codespell_lib/tests/test_basic.py
+++ b/codespell_lib/tests/test_basic.py
@@ -159,6 +159,16 @@ def test_basic(
     assert cs.main(tmp_path) == 0
 
 
+def test_default_word_parsing(
+    tmp_path: Path,
+    capsys: pytest.CaptureFixture[str],
+) -> None:
+    fname = tmp_path / "backtick"
+    with fname.open("a") as f:
+        f.write("`abandonned`\n")
+    assert cs.main(fname) == 1, "bad"
+
+
 def test_bad_glob(
     tmp_path: Path,
     capsys: pytest.CaptureFixture[str],
Repository: codespell-project/codespell

Issue:
ruff is causing PR checks to fail
PR checks are failing on "Run make check" due to this error:

```
ruff .
Error: codespell_lib/_codespell.py:194:17: PLE1300 Unsupported format character '}'
make: *** [Makefile:42: ruff] Error 1
Error: Process completed with exit code 2.
```

Recently, the ruff version increased from `ruff-0.0.282` to `ruff-0.0.283`. Either fix the Python code, or downgrade ruff.


Discussion:
The relevant line is:
https://github.com/codespell-project/codespell/blob/c5febe68414ac95f54fc9a8df1d9cc51fca8de65/codespell_lib/_codespell.py#L194

The above Python code seems legal to me. From [Format String Syntax](https://docs.python.org/3/library/string.html#format-string-syntax):
> A _format_spec_ field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed.

@int-y1 Do you have reasons to believe the Python code needs to be fixed? If that were the case, I would rather fix the Python code.

Resolving patch:
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -190,10 +190,7 @@ def __str__(self) -> str:
         keys.sort()
 
         return "\n".join(
-            [
-                "{0}{1:{width}}".format(key, self.summary.get(key), width=15 - len(key))
-                for key in keys
-            ]
+            [f"{key}{self.summary.get(key):{15 - len(key)}}" for key in keys]
         )
 
 


Test patch:
Repository: codespell-project/codespell

Issue:
Codespell don't handle KeyboardInterrupt exception
This should be catched and the program should stop gracefully but instead show default stack trace:

```
^CTraceback (most recent call last):
  File "/home/kuba/.local/bin/codespell", line 8, in <module>
    sys.exit(_script_main())
             ^^^^^^^^^^^^^^
  File "/home/kuba/.local/lib/python3.12/site-packages/codespell_lib/_codespell.py", line 1017, in _script_main
    return main(*sys.argv[1:])
           ^^^^^^^^^^^^^^^^^^^
  File "/home/kuba/.local/lib/python3.12/site-packages/codespell_lib/_codespell.py", line 1185, in main
    bad_count += parse_file(
                 ^^^^^^^^^^^
  File "/home/kuba/.local/lib/python3.12/site-packages/codespell_lib/_codespell.py", line 903, in parse_file
    check_matches = extract_words_iter(line, word_regex, ignore_word_regex)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/kuba/.local/lib/python3.12/site-packages/codespell_lib/_codespell.py", line 793, in extract_words_iter
    return list(word_regex.finditer(_ignore_word_sub(text, ignore_word_regex)))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyboardInterrupt
```

There is no need to show `KeyboardInterrupt` exception stack trace.


Discussion:

Resolving patch:
diff --git a/codespell_lib/__main__.py b/codespell_lib/__main__.py
--- a/codespell_lib/__main__.py
+++ b/codespell_lib/__main__.py
@@ -3,4 +3,7 @@
 from ._codespell import _script_main
 
 if __name__ == "__main__":
-    sys.exit(_script_main())
+    try:
+        sys.exit(_script_main())
+    except KeyboardInterrupt:
+        pass


Test patch:
Repository: codespell-project/codespell

Issue:
Repo-Review
Apply suggestions from [Repo-Review](https://learn.scientific-python.org/development/guides/repo-review/?repo=codespell-project%2Fcodespell&branch=master).


Discussion:

Resolving patch:
diff --git a/codespell_lib/__init__.py b/codespell_lib/__init__.py
--- a/codespell_lib/__init__.py
+++ b/codespell_lib/__init__.py
@@ -1,4 +1,4 @@
 from ._codespell import _script_main, main
-from ._version import __version__  # type: ignore
+from ._version import __version__  # type: ignore[import-not-found]
 
 __all__ = ["_script_main", "main", "__version__"]
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -28,7 +28,9 @@
 from typing import Any, Dict, List, Match, Optional, Pattern, Sequence, Set, Tuple
 
 # autogenerated by setuptools_scm
-from ._version import __version__ as VERSION  # type: ignore  # noqa: N812
+from ._version import (  # type: ignore[import-not-found]
+    __version__ as VERSION,  # noqa: N812
+)
 
 word_regex_def = r"[\w\-'’]+"
 # While we want to treat characters like ( or " as okay for a starting break,


Test patch:
Repository: codespell-project/codespell

Issue:
Enable defining settings using comma-separated-values as lists
This is a proposal for a minor update in defining some settings.

Settings involving sequences of values (e.g. words to be ignored, files to be skipped) could be declared not as comma-separated strings, but as lists.

The idea particularly regards `pyproject.toml`, but could be potentially applicable to pre-commit hook as well.

Of course, I think we can all live with the way it's implemented now, but I guess using lists would make the `codespell` configuration more consistent with the remaining tools set up in the config files.

Anyway, the tool is great! I thank all the contributors for their efforts! 🙇🏻‍♂️ 👍🏻 


Discussion:
Isn't this a duplicate of #2767?

Resolving patch:
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -325,7 +325,11 @@ def _split_lines(self, text: str, width: int) -> List[str]:
 
 def _toml_to_parseconfig(toml_dict: Dict[str, Any]) -> Dict[str, Any]:
     """Convert a dict read from a TOML file to the parseconfig.read_dict() format."""
-    return {k: "" if v is True else v for k, v in toml_dict.items() if v is not False}
+    return {
+        k: "" if v is True else ",".join(v) if isinstance(v, list) else v
+        for k, v in toml_dict.items()
+        if v is not False
+    }
 
 
 def _supports_ansi_colors() -> bool:


Test patch:
diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py
--- a/codespell_lib/tests/test_basic.py
+++ b/codespell_lib/tests/test_basic.py
@@ -1150,7 +1150,7 @@ def test_ill_formed_ini_config_file(
     assert "ill-formed config file" in stderr
 
 
-@pytest.mark.parametrize("kind", ("toml", "cfg"))
+@pytest.mark.parametrize("kind", ("cfg", "toml", "toml_list"))
 def test_config_toml(
     tmp_path: Path,
     capsys: pytest.CaptureFixture[str],
@@ -1182,7 +1182,7 @@ def test_config_toml(
 count =
 """
         )
-    else:
+    elif kind == "toml":
         assert kind == "toml"
         if sys.version_info < (3, 11):
             pytest.importorskip("tomli")
@@ -1194,6 +1194,20 @@ def test_config_toml(
 skip = 'bad.txt,whatever.txt'
 check-filenames = false
 count = true
+"""
+        )
+    else:
+        assert kind == "toml_list"
+        if sys.version_info < (3, 11):
+            pytest.importorskip("tomli")
+        tomlfile = tmp_path / "pyproject.toml"
+        args = ("--toml", tomlfile)
+        tomlfile.write_text(
+            """\
+[tool.codespell]
+skip = ['bad.txt', 'whatever.txt']
+check-filenames = false
+count = true
 """
         )
Repository: codespell-project/codespell

Issue:
The value of "--interactive"  is not restricted
There is no restriction on the value of the interactive model entered by the user, but when the codespell is running, it only supports four types of interactive models, 0, 1, 2 and 3. 

When other values are entered, the way of interaction will be confused. Here are some examples：

```
% codespell code.c -i 0 -w 
code.c:16: buring ==> burying, burning, burin, during
FIXED: code.c
% codespell code.c -i 10 -w
    fd = opem("/tmp/a", O_RDONLY);
 Choose an option (blank for none):  0) open: 0
    // buring your cpu
 Choose an option (blank for none):  0) burying 1) burning 2) burin 3) during: 0
FIXED: code.c
% codespell code.c -i 20 -w
code.c:16: buring ==> burying, burning, burin, during
FIXED: code.c
% codespell code.c -i -1 -w
FIXED: code.c
```

-i 20 and -i 0 give the same result, -i 10 and -i 2 give the same result, and -i -1 gives a different result from all the others.


Discussion:

Resolving patch:
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -501,11 +501,13 @@ def parse_options(
         action="store",
         type=int,
         default=0,
+        choices=range(0, 4),
         help="set interactive mode when writing changes:\n"
         "- 0: no interactivity.\n"
         "- 1: ask for confirmation.\n"
         "- 2: ask user to choose one fix when more than one is available.\n"
         "- 3: both 1 and 2",
+        metavar="MODE",
     )
 
     parser.add_argument(
@@ -514,6 +516,7 @@ def parse_options(
         action="store",
         type=int,
         default=34,
+        choices=range(0, 64),
         help="bitmask that allows suppressing messages:\n"
         "- 0: print all messages.\n"
         "- 1: disable warnings about wrong encoding.\n"
@@ -526,6 +529,7 @@ def parse_options(
         "combined; e.g. use 3 for levels 1+2, 7 for "
         "1+2+4, 23 for 1+2+4+16, etc. "
         "The default mask is %(default)s.",
+        metavar="LEVEL",
     )
 
     parser.add_argument(


Test patch:
diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py
--- a/codespell_lib/tests/test_basic.py
+++ b/codespell_lib/tests/test_basic.py
@@ -9,6 +9,7 @@
 from pathlib import Path
 from shutil import copyfile
 from typing import Any, Generator, Optional, Tuple, Union
+from unittest import mock
 
 import pytest
 
@@ -237,7 +238,11 @@ def test_interactivity(
     try:
         assert cs.main(fname) == 0, "empty file"
         fname.write_text("abandonned\n")
-        assert cs.main("-i", "-1", fname) == 1, "bad"
+        with mock.patch.object(sys, "argv", ("-i", "-1", fname)):
+            with pytest.raises(SystemExit) as e:
+                cs.main("-i", "-1", fname)
+            assert e.type == SystemExit
+            assert e.value.code != 0
         with FakeStdin("y\n"):
             assert cs.main("-i", "3", fname) == 1
         with FakeStdin("n\n"):
Repository: replicate/cog

Issue:
Support importing model from subdirectories
This works:

```yaml
model: "predict.py:MyModel"
```

But this doesn't:

```yaml:
model: "mymodel/predict.py:MyModel"
```

It should.


Discussion:

Resolving patch:
diff --git a/python/cog/predictor.py b/python/cog/predictor.py
--- a/python/cog/predictor.py
+++ b/python/cog/predictor.py
@@ -81,9 +81,11 @@ def load_predictor():
             "Can't run predictions: 'predict' option not found in cog.yaml"
         )
 
-    # TODO: handle predict scripts in subdirectories
     predict_string = config["predict"]
-    module_name, class_name = predict_string.split(".py:", 1)
-    module = importlib.import_module(module_name)
+    module_path, class_name = predict_string.split(":", 1)
+    module_name = os.path.basename(module_path).split(".py", 1)[0]
+    spec = importlib.util.spec_from_file_location(module_name, module_path)
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
     predictor_class = getattr(module, class_name)
     return predictor_class()


Test patch:
diff --git a/test-integration/test_integration/test_predict.py b/test-integration/test_integration/test_predict.py
--- a/test-integration/test_integration/test_predict.py
+++ b/test-integration/test_integration/test_predict.py
@@ -97,3 +97,44 @@ def test_predict_with_remote_image(tmpdir_factory):
     # lots of docker pull logs are written to stdout before writing the actual output
     # TODO: clean up docker output so cog predict is always clean
     assert out.strip().endswith("hello world")
+
+
+def test_predict_in_subdirectory_with_imports(tmpdir_factory):
+    tmpdir = tmpdir_factory.mktemp("project")
+    subdir = tmpdir.mkdir("my-subdir")
+    with open(subdir / "predict.py", "w") as f:
+        f.write(
+            """
+import cog
+
+from mylib import concat
+
+class Predictor(cog.Predictor):
+    def setup(self):
+        pass
+
+    @cog.input("input", type=str)
+    def predict(self, input):
+        return concat("hello", input)
+        """
+        )
+    with open(tmpdir / "mylib.py", "w") as f:
+        f.write(
+            """
+def concat(a, b):
+    return a + " " + b
+        """
+        )
+    with open(tmpdir / "cog.yaml", "w") as f:
+        cog_yaml = """
+build:
+  python_version: "3.8"
+predict: "my-subdir/predict.py:Predictor"
+        """
+        f.write(cog_yaml)
+
+    result = subprocess.run(
+        ["cog", "predict", "-i", "world"], cwd=tmpdir, check=True, capture_output=True
+    )
+    # stdout should be clean without any log messages so it can be piped to other commands
+    assert result.stdout == b"hello world\n"
Repository: replicate/cog

Issue:
`choices` turn input to enum type
With 'choices' of strings, the input is no long string but changed to enum type. 
Refer to https://github.com/wty-ustc/HairCLIP/pull/16/files#diff-73c1982d8a085dc10fda2ac7b6f202ae3ff9530ee6a15991c5339051eb10a49aR61, where `editing_type` should be string eg. "both" but the value shows `editing_type.both` and type `<enum 'editing_type'>`




Discussion:

Resolving patch:
diff --git a/python/cog/predictor.py b/python/cog/predictor.py
--- a/python/cog/predictor.py
+++ b/python/cog/predictor.py
@@ -77,6 +77,11 @@ def load_predictor():
 # Base class for inputs, constructed dynamically in get_input_type().
 # (This can't be a docstring or it gets passed through to the schema.)
 class BaseInput(BaseModel):
+    class Config:
+        # When using `choices`, the type is converted into an enum to validate
+        # But, after validation, we want to pass the actual value to predict(), not the enum object
+        use_enum_values = True
+
     def cleanup(self):
         """
         Cleanup any temporary files created by the input.


Test patch:
diff --git a/python/tests/server/test_http_input.py b/python/tests/server/test_http_input.py
--- a/python/tests/server/test_http_input.py
+++ b/python/tests/server/test_http_input.py
@@ -259,7 +259,8 @@ def predict(self, num: float = Input(ge=3.01, le=10.5)) -> float:
 def test_choices_str():
     class Predictor(BasePredictor):
         def predict(self, text: str = Input(choices=["foo", "bar"])) -> str:
-            return str(text)
+            assert type(text) == str
+            return text
 
     client = make_client(Predictor())
     resp = client.post("/predictions", json={"input": {"text": "foo"}})
Repository: replicate/cog

Issue:
Support lists of `BaseModel` for outputs
The following model fails on Replicate.com with a cryptic `Can't pickle <class 'predict.Output'>: it's not the same object as predict.Output` error:

```python
class Output(BaseModel):
    foo: str
    bar: str

class Predictor(BasePredictor):
    def predict(self) -> List[Output]:
        return [Output(foo="foo", bar="bar")]
```

This is [documented deep in Cog's Python layer](https://github.com/replicate/cog/blob/main/python/cog/server/runner.py#L238).

We should support this type of output.


Discussion:

Resolving patch:
diff --git a/python/cog/server/runner.py b/python/cog/server/runner.py
--- a/python/cog/server/runner.py
+++ b/python/cog/server/runner.py
@@ -248,5 +248,7 @@ class Output(BaseModel):
     """
     if isinstance(obj, BaseModel):
         return obj.dict(exclude_unset=True)
+    elif isinstance(obj, List):
+        return [make_pickleable(item) for item in obj]
     else:
         return obj


Test patch: