repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
listlengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
pantsbuild/pants
20,357
pantsbuild__pants-20357
[ "20356" ]
faa50896b7ae80c254d3b97d85086c84db58297a
diff --git a/src/python/pants/backend/scala/compile/scalac.py b/src/python/pants/backend/scala/compile/scalac.py --- a/src/python/pants/backend/scala/compile/scalac.py +++ b/src/python/pants/backend/scala/compile/scalac.py @@ -25,9 +25,11 @@ ScalaArtifactsForVersionResult, ScalaVersion, ) -from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest -from pants.engine.fs import EMPTY_DIGEST, Digest, MergeDigests -from pants.engine.process import FallibleProcessResult +from pants.core.util_rules.source_files import SourceFilesRequest +from pants.core.util_rules.stripped_source_files import StrippedSourceFiles +from pants.core.util_rules.system_binaries import BashBinary, ZipBinary +from pants.engine.fs import EMPTY_DIGEST, CreateDigest, Digest, Directory, MergeDigests +from pants.engine.process import FallibleProcessResult, Process, ProcessResult from pants.engine.rules import Get, MultiGet, collect_rules, rule from pants.engine.target import CoarsenedTarget, SourcesField from pants.engine.unions import UnionRule @@ -44,9 +46,9 @@ from pants.jvm.jdk_rules import JdkEnvironment, JdkRequest, JvmProcess from pants.jvm.resolve.common import ArtifactRequirements from pants.jvm.resolve.coursier_fetch import ToolClasspath, ToolClasspathRequest +from pants.jvm.strip_jar import strip_jar from pants.jvm.strip_jar.strip_jar import StripJarRequest from pants.jvm.subsystems import JvmSubsystem -from pants.jvm.target_types import NO_MAIN_CLASS from pants.util.logging import LogLevel logger = logging.getLogger(__name__) @@ -72,6 +74,8 @@ async def compile_scala_source( scala: ScalaSubsystem, jvm: JvmSubsystem, scalac: Scalac, + bash: BashBinary, + zip_binary: ZipBinary, request: CompileScalaSourceRequest, ) -> FallibleClasspathEntry: # Request classpath entries for our direct dependencies. @@ -98,7 +102,9 @@ async def compile_scala_source( component_members_with_sources, await MultiGet( Get( - SourceFiles, + # Some Scalac plugins (i.e. SemanticDB) require us to use stripped source files so the plugin + # would emit compilation output that correlates with the appropiate paths in the input files. + StrippedSourceFiles, SourceFilesRequest( (t.get(SourcesField),), for_sources_types=(ScalaSourceField, JavaSourceField), @@ -175,7 +181,11 @@ async def compile_scala_source( classpath_arg = ":".join(user_classpath.immutable_inputs_args(prefix=usercp)) output_file = compute_output_jar_filename(request.component) - process_result = await Get( + compilation_output_dir = "__out" + compilation_empty_dir = await Get(Digest, CreateDigest([Directory(compilation_output_dir)])) + merged_digest = await Get(Digest, MergeDigests([sources_digest, compilation_empty_dir])) + + compile_result = await Get( FallibleProcessResult, JvmProcess( jdk=jdk, @@ -187,12 +197,8 @@ async def compile_scala_source( *local_plugins.args(local_scalac_plugins_relpath), *(("-classpath", classpath_arg) if classpath_arg else ()), *scalac.args, - # NB: We set a non-existent main-class so that using `-d` produces a `jar` manifest - # with stable content. - "-Xmain-class", - NO_MAIN_CLASS, "-d", - output_file, + compilation_output_dir, *sorted( chain.from_iterable( sources.snapshot.files @@ -200,17 +206,44 @@ async def compile_scala_source( ) ), ], - input_digest=sources_digest, + input_digest=merged_digest, extra_immutable_input_digests=extra_immutable_input_digests, extra_nailgun_keys=extra_nailgun_keys, - output_files=(output_file,), + output_directories=(compilation_output_dir,), description=f"Compile {request.component} with scalac", level=LogLevel.DEBUG, ), ) output: ClasspathEntry | None = None - if process_result.exit_code == 0: - output_digest = process_result.output_digest + if compile_result.exit_code == 0: + # We package the outputs into a JAR file in a similar way as how it's + # done in the `javac.py` implementation + jar_result = await Get( + ProcessResult, + Process( + argv=[ + bash.path, + "-c", + " ".join( + [ + "cd", + compilation_output_dir, + ";", + zip_binary.path, + "-r", + f"../{output_file}", + ".", + ] + ), + ], + input_digest=compile_result.output_digest, + output_files=(output_file,), + description=f"Capture outputs of {request.component} for scalac", + level=LogLevel.TRACE, + ), + ) + output_digest = jar_result.output_digest + if jvm.reproducible_jars: output_digest = await Get( Digest, StripJarRequest(digest=output_digest, filenames=(output_file,)) @@ -220,7 +253,7 @@ async def compile_scala_source( return FallibleClasspathEntry.from_fallible_process_result( str(request.component), - process_result, + compile_result, output, ) @@ -251,5 +284,6 @@ def rules(): *scala_artifact_rules(), *scalac_plugins_rules(), *versions.rules(), + *strip_jar.rules(), UnionRule(ClasspathEntryRequest, CompileScalaSourceRequest), ] diff --git a/src/python/pants/jvm/jar_tool/jar_tool.py b/src/python/pants/jvm/jar_tool/jar_tool.py --- a/src/python/pants/jvm/jar_tool/jar_tool.py +++ b/src/python/pants/jvm/jar_tool/jar_tool.py @@ -72,19 +72,22 @@ def __init__( manifest: str | None = None, jars: Iterable[str] | None = None, file_mappings: Mapping[str, str] | None = None, + files: Iterable[str] | None = None, default_action: JarDuplicateAction | None = None, policies: Iterable[tuple[str, str | JarDuplicateAction]] | None = None, skip: Iterable[str] | None = None, compress: bool = False, update: bool = False, ) -> None: + _file_mappings = {**(file_mappings or {}), **({f: f for f in (files or [])})} + object.__setattr__(self, "jar_name", jar_name) object.__setattr__(self, "digest", digest) object.__setattr__(self, "main_class", main_class) object.__setattr__(self, "manifest", manifest) object.__setattr__(self, "classpath_entries", tuple(classpath_entries or ())) object.__setattr__(self, "jars", tuple(jars or ())) - object.__setattr__(self, "file_mappings", FrozenDict(file_mappings or {})) + object.__setattr__(self, "file_mappings", FrozenDict(_file_mappings)) object.__setattr__(self, "default_action", default_action) object.__setattr__(self, "policies", tuple(JarToolRequest.__parse_policies(policies or ()))) object.__setattr__(self, "skip", tuple(skip or ()))
diff --git a/src/python/pants/backend/codegen/protobuf/scala/rules_integration_test.py b/src/python/pants/backend/codegen/protobuf/scala/rules_integration_test.py --- a/src/python/pants/backend/codegen/protobuf/scala/rules_integration_test.py +++ b/src/python/pants/backend/codegen/protobuf/scala/rules_integration_test.py @@ -234,7 +234,7 @@ def assert_gen(addr: Address, expected: Iterable[str]) -> None: assert_files_generated( rule_runner, addr, - source_roots=["src/python", "/src/protobuf", "/tests/protobuf"], + source_roots=["src/python", "/src/protobuf", "/tests/protobuf", "src/jvm"], expected_files=list(expected), ) diff --git a/src/python/pants/backend/codegen/thrift/scrooge/scala/rules_integration_test.py b/src/python/pants/backend/codegen/thrift/scrooge/scala/rules_integration_test.py --- a/src/python/pants/backend/codegen/thrift/scrooge/scala/rules_integration_test.py +++ b/src/python/pants/backend/codegen/thrift/scrooge/scala/rules_integration_test.py @@ -200,7 +200,7 @@ def assert_gen(addr: Address, expected: list[str]) -> None: assert_files_generated( rule_runner, addr, - source_roots=["src/python", "/src/thrift", "/tests/thrift"], + source_roots=["src/python", "/src/thrift", "/tests/thrift", "src/jvm"], expected_files=expected, ) diff --git a/src/python/pants/backend/scala/compile/acyclic.test.lock b/src/python/pants/backend/scala/compile/acyclic.test.lock --- a/src/python/pants/backend/scala/compile/acyclic.test.lock +++ b/src/python/pants/backend/scala/compile/acyclic.test.lock @@ -1,6 +1,6 @@ # This lockfile was autogenerated by Pants. To regenerate, run: # -# ./pants internal-generate-test-lockfile-fixtures :: +# pants internal-generate-test-lockfile-fixtures :: # # --- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE --- # { diff --git a/src/python/pants/backend/scala/compile/joda-time.test.lock b/src/python/pants/backend/scala/compile/joda-time.test.lock --- a/src/python/pants/backend/scala/compile/joda-time.test.lock +++ b/src/python/pants/backend/scala/compile/joda-time.test.lock @@ -1,6 +1,6 @@ # This lockfile was autogenerated by Pants. To regenerate, run: # -# ./pants internal-generate-test-lockfile-fixtures :: +# pants internal-generate-test-lockfile-fixtures :: # # --- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE --- # { diff --git a/src/python/pants/backend/scala/compile/multiple-scalac-plugins.test.lock b/src/python/pants/backend/scala/compile/multiple-scalac-plugins.test.lock --- a/src/python/pants/backend/scala/compile/multiple-scalac-plugins.test.lock +++ b/src/python/pants/backend/scala/compile/multiple-scalac-plugins.test.lock @@ -1,6 +1,6 @@ # This lockfile was autogenerated by Pants. To regenerate, run: # -# ./pants internal-generate-test-lockfile-fixtures :: +# pants internal-generate-test-lockfile-fixtures :: # # --- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE --- # { diff --git a/src/python/pants/backend/scala/compile/scala-library-2.12.test.lock b/src/python/pants/backend/scala/compile/scala-library-2.12.test.lock --- a/src/python/pants/backend/scala/compile/scala-library-2.12.test.lock +++ b/src/python/pants/backend/scala/compile/scala-library-2.12.test.lock @@ -1,6 +1,6 @@ # This lockfile was autogenerated by Pants. To regenerate, run: # -# ./pants internal-generate-test-lockfile-fixtures :: +# pants internal-generate-test-lockfile-fixtures :: # # --- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE --- # { diff --git a/src/python/pants/backend/scala/compile/scala-library-2.13.test.lock b/src/python/pants/backend/scala/compile/scala-library-2.13.test.lock --- a/src/python/pants/backend/scala/compile/scala-library-2.13.test.lock +++ b/src/python/pants/backend/scala/compile/scala-library-2.13.test.lock @@ -1,6 +1,6 @@ # This lockfile was autogenerated by Pants. To regenerate, run: # -# ./pants internal-generate-test-lockfile-fixtures :: +# pants internal-generate-test-lockfile-fixtures :: # # --- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE --- # { diff --git a/src/python/pants/backend/scala/compile/scala-library-3.test.lock b/src/python/pants/backend/scala/compile/scala-library-3.test.lock --- a/src/python/pants/backend/scala/compile/scala-library-3.test.lock +++ b/src/python/pants/backend/scala/compile/scala-library-3.test.lock @@ -1,6 +1,6 @@ # This lockfile was autogenerated by Pants. To regenerate, run: # -# ./pants internal-generate-test-lockfile-fixtures :: +# pants internal-generate-test-lockfile-fixtures :: # # --- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE --- # { diff --git a/src/python/pants/backend/scala/compile/scalac_test.py b/src/python/pants/backend/scala/compile/scalac_test.py --- a/src/python/pants/backend/scala/compile/scalac_test.py +++ b/src/python/pants/backend/scala/compile/scalac_test.py @@ -26,7 +26,7 @@ from pants.backend.scala.target_types import rules as target_types_rules from pants.build_graph.address import Address from pants.core.goals.check import CheckResults -from pants.core.util_rules import source_files +from pants.core.util_rules import source_files, stripped_source_files, system_binaries from pants.engine.addresses import Addresses from pants.engine.internals.parametrize import Parametrize from pants.engine.internals.scheduler import ExecutionError @@ -56,11 +56,13 @@ def rule_runner() -> RuleRunner: *strip_jar.rules(), *scalac_rules(), *source_files.rules(), + *stripped_source_files.rules(), *target_types_rules(), *testutil.rules(), *util_rules(), *scala_dep_inf_rules(), *scala_artifact_rules(), + *system_binaries.rules(), QueryRule(CheckResults, (ScalacCheckRequest,)), QueryRule(CoarsenedTargets, (Addresses,)), QueryRule(FallibleClasspathEntry, (CompileScalaSourceRequest,)), @@ -164,7 +166,6 @@ def test_compile_no_deps( ) assert classpath.content == { ".ExampleLib.scala.lib.scalac.jar": { - "META-INF/MANIFEST.MF", "org/pantsbuild/example/lib/C.class", } } @@ -290,7 +291,6 @@ def test_compile_with_deps( ) assert classpath.content == { ".Example.scala.main.scalac.jar": { - "META-INF/MANIFEST.MF", "org/pantsbuild/example/Main$.class", "org/pantsbuild/example/Main.class", } @@ -392,7 +392,6 @@ def main(args: Array[String]): Unit = { ) assert classpath.content == { ".Example.scala.main.scalac.jar": { - "META-INF/MANIFEST.MF", "org/pantsbuild/example/Main$.class", "org/pantsbuild/example/Main.class", } @@ -869,7 +868,6 @@ def test_compile_no_deps_scala3( ) assert classpath.content == { ".ExampleLib.scala.lib.scalac.jar": { - "META-INF/MANIFEST.MF", "org/pantsbuild/example/lib/C.class", "org/pantsbuild/example/lib/C.tasty", } @@ -967,7 +965,6 @@ def test_compile_dep_on_scala_artifact( ".ExampleLib.scala.lib.scalac.jar": { "ExampleLib$.class", "ExampleLib.class", - "META-INF/MANIFEST.MF", } } @@ -1103,3 +1100,66 @@ class B { assert classpath_2_13.result == CompileResult.FAILED and classpath_2_13.stderr assert "error: Unwanted cyclic dependency" in classpath_2_13.stderr + + [email protected] +def scala2_semanticdb_lockfile_def() -> JVMLockfileFixtureDefinition: + return JVMLockfileFixtureDefinition( + "semanticdb-scalac-2.13.test.lock", + ["org.scala-lang:scala-library:2.13.12", "org.scalameta:semanticdb-scalac_2.13.12:4.8.14"], + ) + + [email protected] +def scala2_semanticdb_lockfile( + scala2_semanticdb_lockfile_def: JVMLockfileFixtureDefinition, request +) -> JVMLockfileFixture: + return scala2_semanticdb_lockfile_def.load(request) + + +@maybe_skip_jdk_test +def test_scalac_plugin_extra_output( + rule_runner: RuleRunner, scala2_semanticdb_lockfile: JVMLockfileFixture +) -> None: + rule_runner.write_files( + { + "3rdparty/jvm/default.lock": scala2_semanticdb_lockfile.serialized_lockfile, + "3rdparty/jvm/BUILD": scala2_semanticdb_lockfile.requirements_as_jvm_artifact_targets(), + "src/jvm/Foo.scala": dedent( + """\ + import scala.collection.immutable + object Foo { immutable.Seq.empty[Int] } + """ + ), + "src/jvm/BUILD": dedent( + """\ + scalac_plugin( + name="semanticdb", + artifact="//3rdparty/jvm:org.scalameta_semanticdb-scalac_2.13.12", + ) + + scala_sources(scalac_plugins=["semanticdb"]) + """ + ), + } + ) + + rule_runner.set_options( + [ + f"--source-root-patterns={repr(['src/jvm'])}", + f"--scala-version-for-resolve={repr({'jvm-default': '2.13.12'})}", + ], + env_inherit=PYTHON_BOOTSTRAP_ENV, + ) + + request = CompileScalaSourceRequest( + component=expect_single_expanded_coarsened_target( + rule_runner, Address(spec_path="src/jvm") + ), + resolve=make_resolve(rule_runner), + ) + rendered_classpath = rule_runner.request(RenderedClasspath, [request]) + assert ( + "META-INF/semanticdb/Foo.scala.semanticdb" + in rendered_classpath.content["src.jvm.Foo.scala.scalac.jar"] + ) diff --git a/src/python/pants/backend/scala/compile/semanticdb-scalac-2.13.test.lock b/src/python/pants/backend/scala/compile/semanticdb-scalac-2.13.test.lock new file mode 100644 --- /dev/null +++ b/src/python/pants/backend/scala/compile/semanticdb-scalac-2.13.test.lock @@ -0,0 +1,50 @@ +# This lockfile was autogenerated by Pants. To regenerate, run: +# +# pants internal-generate-test-lockfile-fixtures :: +# +# --- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE --- +# { +# "version": 1, +# "generated_with_requirements": [ +# "org.scala-lang:scala-library:2.13.12,url=not_provided,jar=not_provided", +# "org.scalameta:semanticdb-scalac_2.13.12:4.8.14,url=not_provided,jar=not_provided" +# ] +# } +# --- END PANTS LOCKFILE METADATA --- + +[[entries]] +directDependencies = [] +dependencies = [] +file_name = "org.scala-lang_scala-library_2.13.12.jar" + +[entries.coord] +group = "org.scala-lang" +artifact = "scala-library" +version = "2.13.12" +packaging = "jar" +[entries.file_digest] +fingerprint = "c6a879e4973a60f6162668542a33eaccc2bb565d1c934fb061c5844259131dd1" +serialized_bytes_length = 5917034 +[[entries]] +file_name = "org.scalameta_semanticdb-scalac_2.13.12_4.8.14.jar" +[[entries.directDependencies]] +group = "org.scala-lang" +artifact = "scala-library" +version = "2.13.12" +packaging = "jar" + +[[entries.dependencies]] +group = "org.scala-lang" +artifact = "scala-library" +version = "2.13.12" +packaging = "jar" + + +[entries.coord] +group = "org.scalameta" +artifact = "semanticdb-scalac_2.13.12" +version = "4.8.14" +packaging = "jar" +[entries.file_digest] +fingerprint = "516da9260db08ec221f712eaf3c454a693121ebd64da501200bbf29dd28fcfc4" +serialized_bytes_length = 17218706 diff --git a/src/python/pants/backend/scala/lint/scalafmt/rules_integration_test.py b/src/python/pants/backend/scala/lint/scalafmt/rules_integration_test.py --- a/src/python/pants/backend/scala/lint/scalafmt/rules_integration_test.py +++ b/src/python/pants/backend/scala/lint/scalafmt/rules_integration_test.py @@ -15,7 +15,7 @@ from pants.backend.scala.target_types import ScalaSourcesGeneratorTarget, ScalaSourceTarget from pants.build_graph.address import Address from pants.core.goals.fmt import FmtResult, Partitions -from pants.core.util_rules import config_files, source_files +from pants.core.util_rules import config_files, source_files, stripped_source_files from pants.core.util_rules.external_tool import rules as external_tool_rules from pants.engine.fs import PathGlobs, Snapshot from pants.engine.rules import QueryRule @@ -39,6 +39,7 @@ def rule_runner() -> RuleRunner: *coursier_setup_rules(), *external_tool_rules(), *source_files.rules(), + *stripped_source_files.rules(), *strip_jar.rules(), *scalac_rules(), *util_rules(), diff --git a/src/python/pants/backend/scala/test/scalatest_test.py b/src/python/pants/backend/scala/test/scalatest_test.py --- a/src/python/pants/backend/scala/test/scalatest_test.py +++ b/src/python/pants/backend/scala/test/scalatest_test.py @@ -25,7 +25,7 @@ from pants.build_graph.address import Address from pants.core.goals.test import TestResult, get_filtered_environment from pants.core.target_types import FilesGeneratorTarget, FileTarget, RelocatedFiles -from pants.core.util_rules import config_files, source_files, system_binaries +from pants.core.util_rules import config_files, source_files, stripped_source_files, system_binaries from pants.engine.addresses import Addresses from pants.engine.target import CoarsenedTargets from pants.jvm import classpath @@ -59,6 +59,7 @@ def rule_runner() -> RuleRunner: *scala_target_types_rules(), *scalac_rules(), *source_files.rules(), + *stripped_source_files.rules(), *system_binaries.rules(), *target_types_rules(), *util_rules(), diff --git a/src/python/pants/jvm/compile_test.py b/src/python/pants/jvm/compile_test.py --- a/src/python/pants/jvm/compile_test.py +++ b/src/python/pants/jvm/compile_test.py @@ -311,7 +311,6 @@ def test_compile_mixed( ) assert rendered_classpath.content[".Example.scala.main.scalac.jar"] == { - "META-INF/MANIFEST.MF", "org/pantsbuild/example/Main$.class", "org/pantsbuild/example/Main.class", } diff --git a/src/python/pants/jvm/test/junit_test.py b/src/python/pants/jvm/test/junit_test.py --- a/src/python/pants/jvm/test/junit_test.py +++ b/src/python/pants/jvm/test/junit_test.py @@ -21,7 +21,7 @@ from pants.backend.scala.target_types import rules as scala_target_types_rules from pants.core.goals.test import TestResult, get_filtered_environment from pants.core.target_types import FilesGeneratorTarget, FileTarget, RelocatedFiles -from pants.core.util_rules import config_files, source_files +from pants.core.util_rules import config_files, source_files, stripped_source_files from pants.core.util_rules.external_tool import rules as external_tool_rules from pants.engine.addresses import Addresses from pants.engine.target import CoarsenedTargets @@ -59,6 +59,7 @@ def rule_runner() -> RuleRunner: *scala_target_types_rules(), *scalac_rules(), *source_files.rules(), + *stripped_source_files.rules(), *target_types_rules(), *util_rules(), *non_jvm_dependencies_rules(),
Scalac fails when using plugins that emit additional compilation results **Describe the bug** Some Scala compiler plugins emit additional compilation results from the typical output that comes out of `scalac`. Some of those plugins are `semanticdb`, `scalajs`, `scalanative` and others. The scenario workspace is as follows: `3rdparty/jvm/BUILD`: ```python jvm_artifact( name="scala-library", group="org.scala-lang", artifact="scala-library", version="2.13.12", ) scala_artifact( name="semanticdb-jar", group="org.scalameta", artifact="semanticdb-scalac", version="4.8.15", crossversion="full" ) scalac_plugin( name="semanticdb", artifact=":semanticdb-jar" ) ``` `pants.toml`: ```toml [GLOBAL] pants_version = "2.18.1" backend_packages = [ "pants.backend.experimental.scala", ] [source] root_patterns = [ '/src/scala', ] [jvm] jdk = "temurin:1.11" tool_jdk = "temurin:1.11" [scala.version_for_resolve] jvm-default = "2.13.12" [scalac] args = ["-Yrangepos"] [scalac.plugins_for_resolve] jvm-default = "semanticdb" ``` `src/scala/example/BUILD`: ```python scala_sources() ``` `src/scala/example/SimpleApp.scala`: ```scala package example object SimpleApp { def main(args: Array[String]) { println("Hello World") } } ``` When running `pants check ::` the following error is shown: ``` 2:34:01.06 [ERROR] Completed: pants.backend.scala.compile.scalac.compile_scala_source - src/scala/example/SimpleApp.scala failed (exit code 1). error: src.scala.example.SimpleApp.scala.scalac.jar (Is a directory) 1 error 12:34:01.06 [ERROR] Completed: Check compilation for Scala - scalac - scalac failed (exit code 1). ``` **Pants version** 2.18.1 **OS** Both **Additional info** The error comes from the process running `scalac` as Pants expect it to output a JAR file but the additional output from the `scalac` plugin changes its behavior as it now produces a directory.
2023-12-31T11:49:47
pantsbuild/pants
20,365
pantsbuild__pants-20365
[ "20354" ]
2e5c50511f809aa3c007bb54924277c3b0348f64
diff --git a/src/python/pants/backend/python/lint/docformatter/subsystem.py b/src/python/pants/backend/python/lint/docformatter/subsystem.py --- a/src/python/pants/backend/python/lint/docformatter/subsystem.py +++ b/src/python/pants/backend/python/lint/docformatter/subsystem.py @@ -14,7 +14,7 @@ class Docformatter(PythonToolBase): help = "The Python docformatter tool (https://github.com/myint/docformatter)." default_main = ConsoleScript("docformatter") - default_requirements = ["docformatter>=1.4,<1.6"] + default_requirements = ["docformatter>=1.4,<1.5"] register_interpreter_constraints = True diff --git a/src/python/pants/backend/python/subsystems/setup.py b/src/python/pants/backend/python/subsystems/setup.py --- a/src/python/pants/backend/python/subsystems/setup.py +++ b/src/python/pants/backend/python/subsystems/setup.py @@ -225,7 +225,7 @@ def interpreter_constraints(self) -> tuple[str, ...]: ), ) pip_version = StrOption( - default="23.1.2", + default="24.0", help=softwrap( f""" Use this version of Pip for resolving requirements and generating lockfiles.
Most built-in tool lockfiles do not work with Python 3.12 **Describe the bug** The built-in lockfiles for tools like: pytest, mypy, ..., use pip 23.0.1, which doesn't work with Python 3.12: ``` 13:28:11.08 [INFO] Completed: Building pytest.pex from resource://pants.backend.python.subsystems/pytest.lock 13:28:11.09 [ERROR] 1 Exception encountered: Engine traceback: in `test` goal ProcessExecutionFailure: Process 'Building pytest.pex from resource://pants.backend.python.subsystems/pytest.lock' failed with exit code 1. stdout: stderr: The Pip requested was pip==23.0.1 but it does not work with the interpreter selected which is CPython 3.12.0 at /Users/huon/.pyenv/versions/3.12.0/bin/python3.12. Pip 23.0.1 requires Python <3.12,>=3.7. ``` Reproducer: ```shell cd $(mktemp -d) cat > pants.toml <<EOF [GLOBAL] pants_version = "2.19.0rc2" backend_packages = [ "pants.backend.python", ] [python] interpreter_constraints = ["==3.12.*"] EOF echo 'python_tests(name="t")' > BUILD echo 'def test_foo(): pass' > test_example.py # BUG: fails by default with Python 3.12 pants test :: #> The Pip requested was pip==23.0.1 but it does not work with the interpreter selected which is CPython 3.12.0 at /Users/huon/.pyenv/versions/3.12.0/bin/python3.12. Pip 23.0.1 requires Python <3.12,>=3.7. # OKAY: works fine pants test --python-interpreter-constraints='["==3.11.*"]' :: ``` Workaround: use custom lockfiles, with `python_requirement`s/`install_from_resolve`. **Pants version** 2.19.0rc2 (NB. 2.18.1 uses a version of pex that doesn't support Python 3.12 by default, but would likely be still affected by this if one specifies a newer pex in `[pex-cli]`.) **OS** macOS **Additional info** Discussed in https://github.com/pantsbuild/pants/pull/20310#pullrequestreview-1797974655 Details of pip version support in https://github.com/pantsbuild/pex/blob/4eb5c9aa25c6a695bf55263ab239189b720cebaf/pex/pip/version.py#L128-L233 See https://github.com/search?q=repo%3Apantsbuild%2Fpants%20pip_version%2023.0.1&type=code for 27 current lock files using pip version 23.0.1.
The lockfiles are mostly using 23.0.1, and that has a version range of >=3.7,<3.12: https://github.com/pantsbuild/pex/blob/4eb5c9aa25c6a695bf55263ab239189b720cebaf/pex/pip/version.py#L182-L187 Thus, I imagine it's not a problem to regenerate to a newer versions that just _increase_ this range, while still supporting 3.7: https://github.com/pantsbuild/pex/blob/4eb5c9aa25c6a695bf55263ab239189b720cebaf/pex/pip/version.py#L210-L233 That said, pip suggests that pants' default pip version (23.1.2) doesn't work with python 3.12 (this seems potentially incorrect? https://github.com/pantsbuild/pex/pull/2314), so we might need to leap to an even newer pip and/or bump the default pip version too.
2024-01-04T05:46:18
pantsbuild/pants
20,367
pantsbuild__pants-20367
[ "20344" ]
5b75d6dad728c0e62a67272cf3437885f33538b9
diff --git a/build-support/bin/generate_docs.py b/build-support/bin/generate_docs.py --- a/build-support/bin/generate_docs.py +++ b/build-support/bin/generate_docs.py @@ -35,6 +35,7 @@ from pants.base.build_environment import get_buildroot, get_pants_cachedir from pants.help.help_info_extracter import to_help_str +from pants.option.scope import GLOBAL_SCOPE, GLOBAL_SCOPE_CONFIG_SECTION from pants.util.strutil import softwrap from pants.version import MAJOR_MINOR @@ -333,6 +334,10 @@ def _generate_toml_snippet(option_data, scope) -> str: # This option is not configurable. return "" + if scope == GLOBAL_SCOPE: + # make sure we're rendering with the section name as appears in pants.toml + scope = GLOBAL_SCOPE_CONFIG_SECTION + toml_lines = [] example_cli = option_data["display_args"][0] config_key = option_data["config_key"]
Empty TOML section `[]` in GLOBAL options docs **Describe the bug** The toml suggestion for options in the GLOBAL section end up with `[]` as their TOML section, e.g. https://www.pantsbuild.org/v2.19/docs/reference-global#level <img width="224" alt="image" src="https://github.com/pantsbuild/pants/assets/1203825/97654b4c-eefe-479a-a20b-7f4c664d5c7e"> That should show: ```toml [GLOBAL] level = <LogLevel> ``` **Pants version** 2.19 **OS** N/A **Additional info** #19718
2024-01-05T03:31:16
pantsbuild/pants
20,429
pantsbuild__pants-20429
[ "20418" ]
a7ae87be2d570b2c584a9478df47244edf35087a
diff --git a/src/python/pants/engine/internals/graph.py b/src/python/pants/engine/internals/graph.py --- a/src/python/pants/engine/internals/graph.py +++ b/src/python/pants/engine/internals/graph.py @@ -429,6 +429,16 @@ def _parametrized_target_generators_with_templates( field_value = generator_fields.pop(field_type.alias, None) if field_value is not None: template_fields[field_type.alias] = field_value + + # Move parametrize groups over to `template_fields` in order to expand them. + parametrize_group_field_names = [ + name + for name, field in generator_fields.items() + if isinstance(field, Parametrize) and field.is_group + ] + for field_name in parametrize_group_field_names: + template_fields[field_name] = generator_fields.pop(field_name) + field_type_aliases = target_type._get_field_aliases_to_field_types( target_type.class_field_types(union_membership) ).keys()
diff --git a/src/python/pants/engine/internals/defaults_test.py b/src/python/pants/engine/internals/defaults_test.py --- a/src/python/pants/engine/internals/defaults_test.py +++ b/src/python/pants/engine/internals/defaults_test.py @@ -306,6 +306,31 @@ def _determenistic_parametrize_group_keys(value: Mapping[str, Any]) -> dict[str, ), id="overrides value not frozen (issue #18784)", ), + pytest.param( + Scenario( + args=( + { + TestGenTargetGenerator.alias: { + "tags": Parametrize(["foo"], ["bar"], baz=["baz"]), + **Parametrize( + "splat", description="splat-desc", dependencies=["splat:dep"] + ), + } + }, + ), + expected_defaults={ + "test_gen_targets": _determenistic_parametrize_group_keys( + { + "tags": ParametrizeDefault(("foo",), ("bar",), baz=("baz",)), # type: ignore[arg-type] + **ParametrizeDefault( + "splat", description="splat-desc", dependencies=["splat:dep"] + ), + } + ) + }, + ), + id="parametrizations on target generator (issue #20418)", + ), ], ) def test_set_defaults( diff --git a/src/python/pants/engine/internals/graph_test.py b/src/python/pants/engine/internals/graph_test.py --- a/src/python/pants/engine/internals/graph_test.py +++ b/src/python/pants/engine/internals/graph_test.py @@ -1506,6 +1506,9 @@ def test_parametrize_partial_exclude(generated_targets_rule_runner: RuleRunner) def test_parametrize_16190(generated_targets_rule_runner: RuleRunner) -> None: + """Field subclassing defeats automatic filling of parameters for explicit dependencies on + parametrized targets.""" + class ParentField(Field): alias = "parent" help = "foo" @@ -1558,6 +1561,7 @@ class ChildTarget(Target): ], ) def test_parametrize_16910(generated_targets_rule_runner: RuleRunner, field_content: str) -> None: + """Misleading errror message for parametrized field that is unknown.""" with engine_error( InvalidTargetException, contains=f"demo/BUILD:1: Unrecognized field `{field_content}`" ): @@ -1589,6 +1593,40 @@ def test_parametrize_single_value_16978(generated_targets_rule_runner: RuleRunne ) +def test_parametrize_group_on_target_generator_20418( + generated_targets_rule_runner: RuleRunner, +) -> None: + assert_generated( + generated_targets_rule_runner, + Address("demo", target_name="t"), + dedent( + """\ + generator( + name='t', + sources=['f1.ext', 'f2.ext'], + **parametrize('a1', resolve='a', tags=['1']), + **parametrize('b2', resolve='b', tags=['2']), + ) + """ + ), + ["f1.ext", "f2.ext"], + expected_dependencies={ + "demo/f1.ext:t@parametrize=a1": set(), + "demo/f1.ext:t@parametrize=b2": set(), + "demo/f2.ext:t@parametrize=a1": set(), + "demo/f2.ext:t@parametrize=b2": set(), + "demo:t@parametrize=a1": { + "demo/f1.ext:t@parametrize=a1", + "demo/f2.ext:t@parametrize=a1", + }, + "demo:t@parametrize=b2": { + "demo/f1.ext:t@parametrize=b2", + "demo/f2.ext:t@parametrize=b2", + }, + }, + ) + + # ----------------------------------------------------------------------------------------------- # Test `SourcesField`. Also see `engine/target_test.py`. # -----------------------------------------------------------------------------------------------
Multi-parametrize doesn't work with defaults or target generators **Describe the bug** The new group-parametrization logic added by [this PR](https://github.com/pantsbuild/pants/pull/20065) only works for individual targets and not target generators or `__defaults__`. **Pants version** 2.19.0rc4 **OS** Mac **Additional info** Below is an example of the error message I see when I try and parametrize generators/defaults. ``` Unrecognized field `parametrize_-8470896455302443883:580806178752=parametrize('py38', interpreter_constraints=('==3.8.*',), resolve='py38')` in target <my target>. Valid fields for the target type `python_sources`: ['dependencies', 'description', 'interpreter_constraints', 'overrides', 'resolve', 'restartable', 'run_goal_use_sandbox', 'skip_black', 'skip_docformatter', 'skip_isort', 'skip_mypy', 'skip_ruff', 'sources', 'tags']. ```
To confirm, the issue with `__defaults__` is also only when applied for target generators, right?
2024-01-17T10:08:29
pantsbuild/pants
20,433
pantsbuild__pants-20433
[ "20418", "20418" ]
8189a08235457f47b05d83f3e69361f80836c3ec
diff --git a/src/python/pants/engine/internals/graph.py b/src/python/pants/engine/internals/graph.py --- a/src/python/pants/engine/internals/graph.py +++ b/src/python/pants/engine/internals/graph.py @@ -429,6 +429,16 @@ def _parametrized_target_generators_with_templates( field_value = generator_fields.pop(field_type.alias, None) if field_value is not None: template_fields[field_type.alias] = field_value + + # Move parametrize groups over to `template_fields` in order to expand them. + parametrize_group_field_names = [ + name + for name, field in generator_fields.items() + if isinstance(field, Parametrize) and field.is_group + ] + for field_name in parametrize_group_field_names: + template_fields[field_name] = generator_fields.pop(field_name) + field_type_aliases = target_type._get_field_aliases_to_field_types( target_type.class_field_types(union_membership) ).keys()
diff --git a/src/python/pants/engine/internals/defaults_test.py b/src/python/pants/engine/internals/defaults_test.py --- a/src/python/pants/engine/internals/defaults_test.py +++ b/src/python/pants/engine/internals/defaults_test.py @@ -306,6 +306,31 @@ def _determenistic_parametrize_group_keys(value: Mapping[str, Any]) -> dict[str, ), id="overrides value not frozen (issue #18784)", ), + pytest.param( + Scenario( + args=( + { + TestGenTargetGenerator.alias: { + "tags": Parametrize(["foo"], ["bar"], baz=["baz"]), + **Parametrize( + "splat", description="splat-desc", dependencies=["splat:dep"] + ), + } + }, + ), + expected_defaults={ + "test_gen_targets": _determenistic_parametrize_group_keys( + { + "tags": ParametrizeDefault(("foo",), ("bar",), baz=("baz",)), # type: ignore[arg-type] + **ParametrizeDefault( + "splat", description="splat-desc", dependencies=["splat:dep"] + ), + } + ) + }, + ), + id="parametrizations on target generator (issue #20418)", + ), ], ) def test_set_defaults( diff --git a/src/python/pants/engine/internals/graph_test.py b/src/python/pants/engine/internals/graph_test.py --- a/src/python/pants/engine/internals/graph_test.py +++ b/src/python/pants/engine/internals/graph_test.py @@ -1506,6 +1506,9 @@ def test_parametrize_partial_exclude(generated_targets_rule_runner: RuleRunner) def test_parametrize_16190(generated_targets_rule_runner: RuleRunner) -> None: + """Field subclassing defeats automatic filling of parameters for explicit dependencies on + parametrized targets.""" + class ParentField(Field): alias = "parent" help = "foo" @@ -1558,6 +1561,7 @@ class ChildTarget(Target): ], ) def test_parametrize_16910(generated_targets_rule_runner: RuleRunner, field_content: str) -> None: + """Misleading errror message for parametrized field that is unknown.""" with engine_error( InvalidTargetException, contains=f"demo/BUILD:1: Unrecognized field `{field_content}`" ): @@ -1589,6 +1593,40 @@ def test_parametrize_single_value_16978(generated_targets_rule_runner: RuleRunne ) +def test_parametrize_group_on_target_generator_20418( + generated_targets_rule_runner: RuleRunner, +) -> None: + assert_generated( + generated_targets_rule_runner, + Address("demo", target_name="t"), + dedent( + """\ + generator( + name='t', + sources=['f1.ext', 'f2.ext'], + **parametrize('a1', resolve='a', tags=['1']), + **parametrize('b2', resolve='b', tags=['2']), + ) + """ + ), + ["f1.ext", "f2.ext"], + expected_dependencies={ + "demo/f1.ext:t@parametrize=a1": set(), + "demo/f1.ext:t@parametrize=b2": set(), + "demo/f2.ext:t@parametrize=a1": set(), + "demo/f2.ext:t@parametrize=b2": set(), + "demo:t@parametrize=a1": { + "demo/f1.ext:t@parametrize=a1", + "demo/f2.ext:t@parametrize=a1", + }, + "demo:t@parametrize=b2": { + "demo/f1.ext:t@parametrize=b2", + "demo/f2.ext:t@parametrize=b2", + }, + }, + ) + + # ----------------------------------------------------------------------------------------------- # Test `SourcesField`. Also see `engine/target_test.py`. # -----------------------------------------------------------------------------------------------
Multi-parametrize doesn't work with defaults or target generators **Describe the bug** The new group-parametrization logic added by [this PR](https://github.com/pantsbuild/pants/pull/20065) only works for individual targets and not target generators or `__defaults__`. **Pants version** 2.19.0rc4 **OS** Mac **Additional info** Below is an example of the error message I see when I try and parametrize generators/defaults. ``` Unrecognized field `parametrize_-8470896455302443883:580806178752=parametrize('py38', interpreter_constraints=('==3.8.*',), resolve='py38')` in target <my target>. Valid fields for the target type `python_sources`: ['dependencies', 'description', 'interpreter_constraints', 'overrides', 'resolve', 'restartable', 'run_goal_use_sandbox', 'skip_black', 'skip_docformatter', 'skip_isort', 'skip_mypy', 'skip_ruff', 'sources', 'tags']. ``` Multi-parametrize doesn't work with defaults or target generators **Describe the bug** The new group-parametrization logic added by [this PR](https://github.com/pantsbuild/pants/pull/20065) only works for individual targets and not target generators or `__defaults__`. **Pants version** 2.19.0rc4 **OS** Mac **Additional info** Below is an example of the error message I see when I try and parametrize generators/defaults. ``` Unrecognized field `parametrize_-8470896455302443883:580806178752=parametrize('py38', interpreter_constraints=('==3.8.*',), resolve='py38')` in target <my target>. Valid fields for the target type `python_sources`: ['dependencies', 'description', 'interpreter_constraints', 'overrides', 'resolve', 'restartable', 'run_goal_use_sandbox', 'skip_black', 'skip_docformatter', 'skip_isort', 'skip_mypy', 'skip_ruff', 'sources', 'tags']. ```
To confirm, the issue with `__defaults__` is also only when applied for target generators, right? > To confirm, the issue with `__defaults__` is also only when applied for target generators, right? Just confirmed that is indeed the case. To confirm, the issue with `__defaults__` is also only when applied for target generators, right? > To confirm, the issue with `__defaults__` is also only when applied for target generators, right? Just confirmed that is indeed the case.
2024-01-17T15:18:05
pantsbuild/pants
20,496
pantsbuild__pants-20496
[ "20474" ]
6521bddf451eaf049d4fd84ff325bb16a5daad29
diff --git a/src/python/pants/backend/python/util_rules/pex_cli.py b/src/python/pants/backend/python/util_rules/pex_cli.py --- a/src/python/pants/backend/python/util_rules/pex_cli.py +++ b/src/python/pants/backend/python/util_rules/pex_cli.py @@ -35,7 +35,7 @@ class PexCli(TemplatedExternalTool): name = "pex" help = "The PEX (Python EXecutable) tool (https://github.com/pantsbuild/pex)." - default_version = "v2.1.159" + default_version = "v2.1.162" default_url_template = "https://github.com/pantsbuild/pex/releases/download/{version}/pex" version_constraints = ">=2.1.135,<3.0" @@ -46,8 +46,8 @@ def default_known_versions(cls): ( cls.default_version, plat, - "83c3090938b4d276703864c34ba50bcb3616db0663c54b56dd0521a668d9555f", - "3671772", + "95babb1aa147e2803b7744ba0c025aede8e5fc00322ed535675a51563672486b", + "3676166", ) ) for plat in ["macos_arm64", "macos_x86_64", "linux_x86_64", "linux_arm64"]
Pants 2.19 fails to download WHLs with URL-escaped chars **Describe the bug** Pants 2.19 fails to download WHL files hosted on URLs that contain URL-escaped characters. This applies to both URLs already present in the lockfile and to URLs retrieved during `generate-lockfiles`. For example, instead of: https://download.pytorch.org/whl/cpu/torch-2.0.1%2Bcpu-cp311-cp311-linux_x86_64.whl it attempts (and fails) to download: https://download.pytorch.org/whl/cpu/torch-2.0.1+cpu-cp311-cp311-linux_x86_64.whl Seems to be related to the `v2.1.148` PEX version, as downgrading to `v2.1.137` resolves the issue **Pants version** 2.19.0 **OS** Both MacOS and Linux **Additional info** Minimalist example to reproduce: ```BUILD python_requirement( requirements=["torch==2.0.1+cpu"], ) ``` ```pants.toml [GLOBAL] pants_version = "2.19.0" backend_packages = [ "pants.backend.python", ] [python] interpreter_constraints = ["==3.11.*"] enable_resolves = true [python-repos] find_links = [ "https://download.pytorch.org/whl/torch_stable.html", ] # Workaround: Downgrade to a previous PEX version #[pex-cli] #known_versions = [ # "v2.1.137|macos_arm64|faad51a6a108fba9d40b2a10e82a2646fccbaf8c3d9be47818f4bffae02d94b8|4098329", # "v2.1.137|macos_x86_64|faad51a6a108fba9d40b2a10e82a2646fccbaf8c3d9be47818f4bffae02d94b8|4098329", # "v2.1.137|linux_x86_64|faad51a6a108fba9d40b2a10e82a2646fccbaf8c3d9be47818f4bffae02d94b8|4098329", # "v2.1.137|linux_arm64|faad51a6a108fba9d40b2a10e82a2646fccbaf8c3d9be47818f4bffae02d94b8|4098329" #] #version = "v2.1.137" ```
I tried to bisect with: ``` $ python3.10 -m pex.cli lock create --interpreter-constraint $'CPython==3.11.*' --style=universal --pip-version=23.1.2 --resolver-version pip-2020-resolver --find-links=https://download.pytorch.org/whl/torch_stable.html "torch==2.0.1+cpu" -o tmp/tmp.lock ``` and ended up at https://github.com/pantsbuild/pex/commit/45eea4bb274b65bc185e1ea8cfc67f507209aea0 Thanks @cburroughs. Wonder if this is something Pants does wrong when invoking Pex or if it's a Pex issue. I see a few added unquote f.ex., which would lead to the issues observed if not quoted on-use. For clarity, can you show the same regression with extra-indexes as well? Or is this find-links specific code paths? > For clarity, can you show the same regression with extra-indexes as well? Or is this find-links specific code paths? If someone knows of a package on PyPi that uses the `+` syntax I'm happy to try to concoct a test, but I didn't know that was valid before today. It's a local version specifier, and I don't think PyPi would accept them -- they're meant for distro patches, primarily. Torch using them for API spec is... a stretch, semantically. I did a test myself using torch's extra index and couldn't repro, so seems like find-links is the issue.
2024-02-06T20:56:42
pantsbuild/pants
20,502
pantsbuild__pants-20502
[ "20467" ]
30058b7cc99073a94eaf1a0eca88e85a7c59d0c4
diff --git a/src/python/pants/backend/python/util_rules/pex_cli.py b/src/python/pants/backend/python/util_rules/pex_cli.py --- a/src/python/pants/backend/python/util_rules/pex_cli.py +++ b/src/python/pants/backend/python/util_rules/pex_cli.py @@ -35,7 +35,7 @@ class PexCli(TemplatedExternalTool): name = "pex" help = "The PEX (Python EXecutable) tool (https://github.com/pantsbuild/pex)." - default_version = "v2.1.162" + default_version = "v2.1.163" default_url_template = "https://github.com/pantsbuild/pex/releases/download/{version}/pex" version_constraints = ">=2.1.135,<3.0" @@ -46,8 +46,8 @@ def default_known_versions(cls): ( cls.default_version, plat, - "95babb1aa147e2803b7744ba0c025aede8e5fc00322ed535675a51563672486b", - "3676166", + "21cb16072357af4b1f4c4e91d2f4d3b00a0f6cc3b0470da65e7176bbac17ec35", + "3677552", ) ) for plat in ["macos_arm64", "macos_x86_64", "linux_x86_64", "linux_arm64"]
Generating lockfiles fails with: unknown error (_ssl.c:3161) **Describe the bug** When trying to generate lockfiles command fails with the following error: `Failed to spawn a job for /home/manos/Workspace/pants-repo/.conda/bin/python3.9: unknown error (_ssl.c:3161)` ``` pants --print-stacktrace -ldebug generate-lockfiles :: 18:15:17.57 [INFO] Initialization options changed: reinitializing scheduler... 18:15:22.39 [INFO] Scheduler initialized. 18:15:23.84 [INFO] Completed: Generate lockfile for python-default 18:15:23.84 [ERROR] 1 Exception encountered: Engine traceback: in select .. in pants.core.goals.generate_lockfiles.generate_lockfiles_goal `generate-lockfiles` goal Traceback (most recent call last): File "/home/manos/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 626, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/home/manos/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/core/goals/generate_lockfiles.py", line 557, in generate_lockfiles_goal results = await MultiGet( File "/home/manos/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 361, in MultiGet return await _MultiGet(tuple(__arg0)) File "/home/manos/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 168, in __await__ result = yield self.gets File "/home/manos/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 626, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/home/manos/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/backend/python/goals/lockfile.py", line 110, in generate_lockfile result = await Get( File "/home/manos/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self pants.engine.process.ProcessExecutionFailure: Process 'Generate lockfile for python-default' failed with exit code 1. stdout: stderr: Failed to spawn a job for /home/manos/Workspace/pants-repo/.conda/bin/python3.9: unknown error (_ssl.c:3161) Use `--keep-sandboxes=on_failure` to preserve the process chroot for inspection. ``` **Pants version** Tested with versions: - 2.16.0 - 2.17.0 - 2.18.0 - 2.18.2 - 2.19.0rc5 (same result for all tested versions) **OS** Tested with - Fedora 38 (Linux 6.6.13-100.fc38.x86_64) - Fedora 39 (Linux 6.6.13-200.fc39.x86_64) (same result for all tested versions) **Additional info** I think this issue started happening after a kernel update from Fedora. Has anyone else run into this issue before? Any suggestions on how to resolve this would be very appreciated!
The source is free to read. My reading says the underlying SSL lib CPython is linking against is not supported (you're probably on the right track): https://github.com/python/cpython/blob/8fc8c45b6717be58ad927def1bf3ea05c83cab8c/Modules/_ssl.c#L3161 I'd `ldd /home/manos/Workspace/pants-repo/.conda/bin/python3.9` to see the linkage and work from there. This is a much lower level issue than Pants and it would be good to cut Pants out of the debugging. I'm experiencing the same issues, Also using Fedora. I'm only ever able to replicate the issue when using what's in the sandbox. I can't: - Get any helpful error messages - Get the python3.9 urllib from the scie-pants venv to error the same way alone. Using distrobox to try and run in older versions of fedora seems to have the same issue, but it doesn't seem to be entirely isolating things from the rest of the system. The sandbox blanks out env vars and that can be important. @xlevus can you `ldd` and investigate your env vs sandbox env to help isolate if this is an LD_LIBRARY_PATH or other env var required but blocked by Pants issue? The whole scie-pants thing is almost certainly way off track. If Pants launches at all, scie-pants is long out of the picture entirely. ``` 📦[xlevus@pants-debug2 gymkhana]$ pants --keep-sandboxes=on_failure generate-lockfiles :: 10:54:06.16 [INFO] Preserving local process execution dir /tmp/pants-sandbox-ouAMHY for Generate lockfile for python-default 10:54:06.16 [INFO] Completed: Generate lockfile for python-default 10:54:06.16 [ERROR] 1 Exception encountered: Engine traceback: in `generate-lockfiles` goal ProcessExecutionFailure: Process 'Generate lockfile for python-default' failed with exit code 1. stdout: stderr: Failed to spawn a job for /usr/bin/python3.10: unknown error (_ssl.c:3161) 📦[xlevus@pants-debug2 gymkhana]$ ldd /usr/bin/python3.10 linux-vdso.so.1 (0x00007ffeaefee000) libpython3.10.so.1.0 => /lib64/libpython3.10.so.1.0 (0x00007fc5a9b64000) libc.so.6 => /lib64/libc.so.6 (0x00007fc5a9987000) libm.so.6 => /lib64/libm.so.6 (0x00007fc5a98a7000) /lib64/ld-linux-x86-64.so.2 (0x00007fc5a9ebe000) 📦[xlevus@pants-debug2 gymkhana]$ python3.10 Python 3.10.13 (main, Aug 28 2023, 00:00:00) [GCC 12.3.1 20230508 (Red Hat 12.3.1-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import _ssl >>> _ssl.__file__ '/usr/lib64/python3.10/lib-dynload/_ssl.cpython-310-x86_64-linux-gnu.so' >>> _ssl.OPENSSL_VERSION 'OpenSSL 3.0.9 30 May 2023' 📦[xlevus@pants-debug2 gymkhana]$ ldd /usr/lib64/python3.10/lib-dynload/_ssl.cpython-310-x86_64-linux-gnu.so linux-vdso.so.1 (0x00007ffec9df8000) libssl.so.3 => /lib64/libssl.so.3 (0x00007ffbd04b3000) libcrypto.so.3 => /lib64/libcrypto.so.3 (0x00007ffbd0088000) libc.so.6 => /lib64/libc.so.6 (0x00007ffbcfeab000) libz.so.1 => /lib64/libz.so.1 (0x00007ffbcfe91000) /lib64/ld-linux-x86-64.so.2 (0x00007ffbd0592000) 📦[xlevus@pants-debug2 gymkhana]$ ``` ``` 📦[xlevus@pants-debug2 pants-sandbox-z3rdnp]$ ldd /home/xlevus/.cache/nce/29319df9a6ca02e838617675b5b8dd7e5b18a393c27e74979823158b85c015d9/bindings/venvs/2.18.0/bin/python3.9 linux-vdso.so.1 (0x00007ffc1a626000) /home/xlevus/.cache/nce/29319df9a6ca02e838617675b5b8dd7e5b18a393c27e74979823158b85c015d9/bindings/venvs/2.18.0/bin/../lib/libpython3.9.so.1.0 => not found libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f91208e7000) libdl.so.2 => /lib64/libdl.so.2 (0x00007f91208e2000) libutil.so.1 => /lib64/libutil.so.1 (0x00007f91208dd000) libm.so.6 => /lib64/libm.so.6 (0x00007f91207fd000) librt.so.1 => /lib64/librt.so.1 (0x00007f91207f6000) libc.so.6 => /lib64/libc.so.6 (0x00007f9120619000) /lib64/ld-linux-x86-64.so.2 (0x00007f91208f8000) 📦[xlevus@pants-debug2 pants-sandbox-z3rdnp]$ /home/xlevus/.cache/nce/29319df9a6ca02e838617675b5b8dd7e5b18a393c27e74979823158b85c015d9/bindings/venvs/2.18.0/bin/python3.9 Python 3.9.18 (main, Jan 8 2024, 05:40:12) [Clang 17.0.6 ] on linux Type "help", "copyright", "credits" or "license" for more information. Cannot read termcap database; using dumb terminal settings. >>> import _ssl >>> _ssl.__file__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module '_ssl' has no attribute '__file__' >>> _ssl.OPENSSL_VERSION 'OpenSSL 3.0.12 24 Oct 2023' ``` the original `__run.sh` contents: ``` env -i CPPFLAGS= LANG=en_NZ.UTF-8 LDFLAGS= PATH=$'/home/xlevus/.nix-profile/bin:/nix/var/nix/profiles/default/bin:/home/xlevus/.local/bin:/home/xlevus/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin' PEX_IGNORE_RCFILES=true PEX_PYTHON=/home/xlevus/.cache/nce/29319df9a6ca02e838617675b5b8dd7e5b18a393c27e74979823158b85c015d9/bindings/venvs/2.18.0/bin/python3.9 PEX_ROOT=.cache/pex_root PEX_SCRIPT=pex3 /home/xlevus/.cache/nce/29319df9a6ca02e838617675b5b8dd7e5b18a393c27e74979823158b85c015d9/bindings/venvs/2.18.0/bin/python3.9 ./pex lock create --tmpdir .tmp --python-path $'/home/xlevus/.pyenv/versions/3.10.13/bin:/home/xlevus/.pyenv/versions/3.12.1/bin:/home/xlevus/.nix-profile/bin:/nix/var/nix/profiles/default/bin:/home/xlevus/.local/bin:/home/xlevus/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin' $'--output=lock.json' --no-emit-warnings $'--style=universal' --pip-version 23.1.2 --resolver-version pip-2020-resolver --target-system linux --target-system mac $'--indent=2' --no-pypi $'--index=https://pypi.org/simple/' --manylinux manylinux2014 --interpreter-constraint $'CPython==3.10.*' django ``` when changing `PEX_PYTHON` to `PEX_PYTHON=/usr/bin/python3.10` or the system installed python3.9 `__run.sh` runs OK and generates a lockfile. Further: Unpacking `pex` and changing `__run.sh` to invoke `__main__.py` instead, I can trace the error to : https://github.com/pantsbuild/pex/blob/v2.1.137/pex/fetcher.py#L48 `(Pdb) sys.executable '/home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/bin/python3.9` ```(Pdb) w /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/threading.py(937)_bootstrap() -> self._bootstrap_inner() /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/threading.py(980)_bootstrap_inner() -> self.run() /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/threading.py(917)run() -> self._target(*self._args, **self._kwargs) /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/jobs.py(525)spawn_jobs() -> result = Spawn(item, spawn_func(item)) /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/resolver.py(130)_spawn_download() -> self.observer.observe_download(target=target, download_dir=download_dir) /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/resolve/lockfile/create.py(201)observe_download() -> url_fetcher=URLFetcher( > /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/fetcher.py(51)__init__() -> ssl_context = ssl.create_default_context() /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/ssl.py(738)create_default_context() -> context = SSLContext(PROTOCOL_TLS) /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/ssl.py(484)__new__() -> self = _SSLContext.__new__(cls, protocol) ``` The `protocol` version being passed in is: `<_SSLMethod.PROTOCOL_TLS: 2>` Buuuuut, changing the `__run.sh` script to (i.e. call that function, using the same environment & interpreter) it works fine ???: ```env -i CPPFLAGS= LANG=en_NZ.UTF-8 LDFLAGS= PATH=$'/home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.local/bin:/home/xlevus/Projects/xlvs/gymkhana/TMPHOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/xlevus/.nix-profile/bin:/nix/var/nix/profiles/default/bin:/home/xlevus/.local/bin:/home/xlevus/bin' PEX_IGNORE_RCFILES=true PEX_PYTHON=/home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/29319df9a6ca02e838617675b5b8dd7e5b18a393c27e74979823158b85c015d9/bindings/venvs/2.18.0/bin/python3.9 PEX_ROOT=.cache/pex_root PEX_SCRIPT=pex3 /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/29319df9a6ca02e838617675b5b8dd7e5b18a393c27e74979823158b85c015d9/bindings/venvs/2.18.0/bin/python3.9 -c "import ssl; ssl.create_default_context()"``` @xlevus it looks like you have everything at hand you need to dig. If you can come up with a docker-based repro, perhaps someone can help out, but as it stands you have the files, paths, etc. I've created a docker-based reproduction here: https://github.com/xlevus/pants-issue-20467 and it seems to work in a Fedora VM, trying to get an ubuntu VM up to confirm it works in one of those too. Will poke around more tonight. But i'm a little stumped tbqh. It _appears_ to only be an issue when specifically combining the distributed python3.9 venv for pants, and `pex`. The venv's ssl-context code works fine, and the pex code works fine. but combine the two and ??? Great - thanks. I'll try to poke around with the repro case. That said, this is crazy-making "It appears to only be an issue when specifically combining the distributed python3.9" since your OP is this: ``` $ pants --keep-sandboxes=on_failure generate-lockfiles :: 10:54:06.16 [INFO] Preserving local process execution dir /tmp/pants-sandbox-ouAMHY for Generate lockfile for python-default 10:54:06.16 [INFO] Completed: Generate lockfile for python-default 10:54:06.16 [ERROR] 1 Exception encountered: Engine traceback: in `generate-lockfiles` goal ProcessExecutionFailure: Process 'Generate lockfile for python-default' failed with exit code 1. stdout: stderr: Failed to spawn a job for /usr/bin/python3.10: unknown error (_ssl.c:3161) ``` That is definitely not python3.9 let alone the scie-pants hermetic python3.9. > Great - thanks. I'll try to poke around with the repro case. That said, this is crazy-making "It appears to only be an issue when specifically combining the distributed python3.9" since your OP is this: > > ``` > $ pants --keep-sandboxes=on_failure generate-lockfiles :: > 10:54:06.16 [INFO] Preserving local process execution dir /tmp/pants-sandbox-ouAMHY for Generate lockfile for python-default > 10:54:06.16 [INFO] Completed: Generate lockfile for python-default > 10:54:06.16 [ERROR] 1 Exception encountered: > > Engine traceback: > in `generate-lockfiles` goal > > ProcessExecutionFailure: Process 'Generate lockfile for python-default' failed with exit code 1. > stdout: > > stderr: > Failed to spawn a job for /usr/bin/python3.10: unknown error (_ssl.c:3161) > ``` > > That is definitely not python3.9 let alone the scie-pants hermetic python3.9. The error message is misleading. The 'failed to spawn a job' is from Pex's Job runner. I'm ~~100%~~ 89% confident the error comes from within a python3.9 executable. Here's my hacked up sandbox with a pdb.breakpoint stuck right before the failing ssl call: ``` 📦[xlevus@pants-debug2 pants-sandbox-WRfUMY]$ ./__run.sh Cannot read termcap database; using dumb terminal settings. > /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/fetcher.py(51)__init__() -> ssl_context = ssl.create_default_context() (Pdb) w /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/threading.py(937)_bootstrap() -> self._bootstrap_inner() /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/threading.py(980)_bootstrap_inner() -> self.run() /home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/threading.py(917)run() -> self._target(*self._args, **self._kwargs) /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/jobs.py(525)spawn_jobs() -> result = Spawn(item, spawn_func(item)) /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/resolver.py(130)_spawn_download() -> self.observer.observe_download(target=target, download_dir=download_dir) /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/resolve/lockfile/create.py(201)observe_download() -> url_fetcher=URLFetcher( > /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/fetcher.py(51)__init__() -> ssl_context = ssl.create_default_context() (Pdb) !import sys (Pdb) pp sys.executable '/home/xlevus/Projects/xlvs/gymkhana/TMPHOME/.cache/nce/67912efc04f9156d8f5b48a0348983defb964de043b8c13ddc6cc8a002f8e691/cpython-3.9.18+20240107-x86_64-unknown-linux-gnu-install_only.tar.gz/python/bin/python3.9' (Pdb) n ssl.SSLError: unknown error (_ssl.c:3161) > /tmp/pants-sandbox-WRfUMY/.deps/pex-2.1.137-py2.py3-none-any.whl/pex/fetcher.py(51)__init__() -> ssl_context = ssl.create_default_context() (pdb) ``` Ok, thanks for the repro case @xlevus - super helpful. I have not figured out why [PBS Python 3.9](https://github.com/indygreg/python-build-standalone/releases/tag/20240107) is different here, and apparently only different in a Fedora context to boot, but the issue is related to threading. If you use a PBS 3.9 repl to `import ssl; ssl.create_default_context()` - no issue as you found out. The relevant difference in the Pex case is this function is called not in the main application thread, but in a job spawn thread used for spawning parallel (subprocess) jobs. If I create an SSL context early in the main thread, all is well and the lock succeeds: ```diff [root@3d2dd3ceaa5c pants-sandbox-qAIWax]# diff -u .deps/pex-2.1.137-py2.py3-none-any.whl/pex/fetcher.py pex-venv/lib/python3.9/site-packages/pex/fetcher.py --- .deps/pex-2.1.137-py2.py3-none-any.whl/pex/fetcher.py 1980-01-01 00:00:00.000000000 +0000 +++ pex-venv/lib/python3.9/site-packages/pex/fetcher.py 2024-01-28 21:18:01.662789434 +0000 @@ -4,6 +4,8 @@ from __future__ import absolute_import import ssl +ssl.create_default_context() + import time from contextlib import closing, contextmanager [root@3d2dd3ceaa5c pants-sandbox-qAIWax]# ``` There the diff represents some sandbox mucking about, but the upshot is trying to grab the context on import of `pex/fetcher.py` is enough to ensure this happens in the main thread and all is well. The remaining work to do is to see what is buggy here. Is this a PBS Python build buggy somehow? Is it a bug in Pex code - should SSLContext only ever be created in the application main thread? Is this a Fedora glibc modern (which includes libpthread) vs libpthread.so.0 which PBS links to (unlike the system Python 3.9)? I have no clue at the moment. I'll note that I'm dropping work for the evening and I'm AFK likely until the 1st. Further Investigation: - Swapping PBS 2024 build with 20230826 works (but did require me to install libxcrypt on Fedora) - Swapping PBS 2024 build with 20231002 errors in the same place. Possible key change between the two is: > OpenSSL 1.1 -> 3.0 on supported platforms. Linux and macOS now use OpenSSL 3.0.x. Windows uses OpenSSL 3.0.x on CPython 3.11+. @xlevus I'm working on a short-term fix in https://github.com/pantsbuild/pex/issues/2355. I'd still love to know what's really going on here, but 1st to stop the bleeding. I've flipped this back to a bug - apologies @mjimlittle, you ended up being right there. With @xlevus's help debugging, a fix for this issue in Pex is now released in 2.1.163: https://github.com/pantsbuild/pex/releases/tag/v2.1.163 A Pants maintainer will take it from here and upgrade Pants / instruct you how to do so for your Pants version. Hey @jsirois thanks for the update. Also, I am sorry I could not help out in tracing the source of the issue. I'm relatively new to the python/pants ecosystem so I could not keep up with @xlevus :D As a workaround, I have Dockerized pants using an Ubuntu base image and I can successfully generate needed lock files.
2024-02-07T15:21:21
pantsbuild/pants
20,505
pantsbuild__pants-20505
[ "20503" ]
48fe8350992e2e3a9f16d555e70ae5c9649155f5
diff --git a/src/python/pants/init/specs_calculator.py b/src/python/pants/init/specs_calculator.py --- a/src/python/pants/init/specs_calculator.py +++ b/src/python/pants/init/specs_calculator.py @@ -4,6 +4,7 @@ import logging from typing import cast +from pants.base.glob_match_error_behavior import GlobMatchErrorBehavior from pants.base.specs import AddressLiteralSpec, FileLiteralSpec, RawSpecs, Specs from pants.base.specs_parser import SpecsParser from pants.core.util_rules.environments import determine_bootstrap_environment @@ -96,7 +97,11 @@ def calculate_specs( # target-aware vs. target-less goals, e.g. `list` vs `count-loc`. address_literals=tuple(address_literal_specs), file_literals=file_literal_specs, - unmatched_glob_behavior=unmatched_cli_globs, + # The globs here are synthesized from VCS data by the `changed` mechanism. + # As such it does not make sense to apply user-facing matching errors to them. + # In particular, they can legitimately not match anything, if entire git + # subtrees were deleted for example. + unmatched_glob_behavior=GlobMatchErrorBehavior.ignore, filter_by_global_options=True, from_change_detection=True, description_of_origin="`--changed-since`", diff --git a/src/python/pants/vcs/git.py b/src/python/pants/vcs/git.py --- a/src/python/pants/vcs/git.py +++ b/src/python/pants/vcs/git.py @@ -91,7 +91,7 @@ def changed_files( committed_changes = self._git_binary._invoke_unsandboxed( self._create_git_cmdline(committed_cmd) ) - files.update(committed_changes.split()) + files.update(committed_changes.splitlines()) if include_untracked: untracked_cmd = [ "ls-files", @@ -102,14 +102,14 @@ def changed_files( untracked = self._git_binary._invoke_unsandboxed( self._create_git_cmdline(untracked_cmd) ) - files.update(untracked.split()) + files.update(untracked.splitlines()) # git will report changed files relative to the worktree: re-relativize to relative_to return {self._fix_git_relative_path(f, relative_to) for f in files} def changes_in(self, diffspec: str, relative_to: PurePath | str | None = None) -> set[str]: relative_to = PurePath(relative_to) if relative_to is not None else self.worktree cmd = ["diff-tree", "--no-commit-id", "--name-only", "-r", diffspec] - files = self._git_binary._invoke_unsandboxed(self._create_git_cmdline(cmd)).split() + files = self._git_binary._invoke_unsandboxed(self._create_git_cmdline(cmd)).splitlines() return {self._fix_git_relative_path(f.strip(), relative_to) for f in files} def _create_git_cmdline(self, args: Iterable[str]) -> list[str]:
diff --git a/src/python/pants/vcs/git_test.py b/src/python/pants/vcs/git_test.py --- a/src/python/pants/vcs/git_test.py +++ b/src/python/pants/vcs/git_test.py @@ -139,6 +139,9 @@ def test_integration(worktree: Path, readme_file: Path, git: MutatingGitWorktree assert {"README"} == git.changed_files() assert {"README", "INSTALL"} == git.changed_files(include_untracked=True) + (worktree / "WITH SPACE").write_text("space in path") + assert {"README", "INSTALL", "WITH SPACE"} == git.changed_files(include_untracked=True) + # Confirm that files outside of a given relative_to path are ignored assert set() == git.changed_files(relative_to="non-existent")
Deleted files cause `pants tailor` with `--changed-since` to fail **Describe the bug** I use the following command in CI to validate the monorepo, as recommended by the docs: ```shell > pants \ --changed-since=origin/main \ tailor --check \ update-build-files --check \ lint ``` However, if I delete a package, including its `BUILD` file in a PR, the `--changed-since` flag causes `tailor` to try to run on those files, which `pants` blows up on: ```shell 16:40:57.91 [ERROR] 1 Exception encountered: Engine traceback: in `tailor` goal IntrinsicError: Unmatched glob from `--changed-since`: "aws/projects/my_project_name/*" Do the file(s) exist? If so, check if the file(s) are in your `.gitignore` or the global `pants_ignore` option, which may result in Pants not being able to see the file(s) even though they exist on disk. Refer to https://www.pantsbuild.org/v2.19/docs/troubleshooting#pants-cannot-find-a-file-in-your-project. Exited with code exit status 1 ``` If files are deleted, yes, they are changed, but they shouldn't throw an error. **Pants version** 2.19.0 **OS** Linux (CircleCI Ubuntu executor) **Additional info** N/A
Thanks for the bug report. This feels familiar, but I can't find an existing issue for it. Sure - thanks for the project! I also filed https://github.com/pantsbuild/pants/issues/20479 last week that's similar, but not exactly this issue.
2024-02-07T21:45:21
pantsbuild/pants
20,580
pantsbuild__pants-20580
[ "20576" ]
5779896fdd01e1a55d63043a4fb3a1f16ac6bee5
diff --git a/src/python/pants/core/goals/update_build_files.py b/src/python/pants/core/goals/update_build_files.py --- a/src/python/pants/core/goals/update_build_files.py +++ b/src/python/pants/core/goals/update_build_files.py @@ -234,10 +234,17 @@ async def update_build_files( raise ValueError(f"Unrecognized formatter: {update_build_files_subsystem.formatter}") for request in union_membership[RewrittenBuildFileRequest]: - if update_build_files_subsystem.fmt and issubclass(request, chosen_formatter_request_class): + if update_build_files_subsystem.fmt and request == chosen_formatter_request_class: rewrite_request_classes.append(request) - if update_build_files_subsystem.fix_safe_deprecations or not issubclass( + if update_build_files_subsystem.fix_safe_deprecations and issubclass( + request, DeprecationFixerRequest + ): + rewrite_request_classes.append(request) + + # If there are other types of requests that aren't the standard formatter + # backends or deprecation fixers, add them here. + if request not in formatter_to_request_class.values() and not issubclass( request, DeprecationFixerRequest ): rewrite_request_classes.append(request)
diff --git a/src/python/pants/core/goals/update_build_files_test.py b/src/python/pants/core/goals/update_build_files_test.py --- a/src/python/pants/core/goals/update_build_files_test.py +++ b/src/python/pants/core/goals/update_build_files_test.py @@ -74,12 +74,24 @@ def reverse_lines(request: MockRewriteReverseLines) -> RewrittenBuildFile: def generic_goal_rule_runner() -> RuleRunner: return RuleRunner( rules=( - update_build_files, add_line, reverse_lines, + format_build_file_with_ruff, + format_build_file_with_yapf, + update_build_files, + *config_files.rules(), + *pex.rules(), + # Ruff and Yapf are included, but Black isn't because + # that's the formatter we enable in pants.toml. + # These tests check that Ruff and Yapf are NOT invoked, + # but the other rewrite targets are invoked. + *Ruff.rules(), + *Yapf.rules(), *UpdateBuildFilesSubsystem.rules(), UnionRule(RewrittenBuildFileRequest, MockRewriteAddLine), UnionRule(RewrittenBuildFileRequest, MockRewriteReverseLines), + UnionRule(RewrittenBuildFileRequest, FormatWithRuffRequest), + UnionRule(RewrittenBuildFileRequest, FormatWithYapfRequest), ) ) @@ -204,12 +216,20 @@ def black_rule_runner() -> RuleRunner: return RuleRunner( rules=( format_build_file_with_black, + format_build_file_with_ruff, + format_build_file_with_yapf, update_build_files, *config_files.rules(), *pex.rules(), *Black.rules(), + # Even though Ruff and Yapf are included here, + # only Black should be used for formatting. + *Ruff.rules(), + *Yapf.rules(), *UpdateBuildFilesSubsystem.rules(), UnionRule(RewrittenBuildFileRequest, FormatWithBlackRequest), + UnionRule(RewrittenBuildFileRequest, FormatWithRuffRequest), + UnionRule(RewrittenBuildFileRequest, FormatWithYapfRequest), ), target_types=[GenericTarget], )
2.20 runs ruff and yapf on BUILD files without opting in to them **Describe the bug** The default behaviour of `pants update-build-files ::` seems to have changed in 2.20, compared to 2.19. In particular, it seems to now build and run yapf and ruff, in addition to black, without opting in to the ruff or yapf formatters via the `pants.backend.build_files.fmt.*` backends. (https://www.pantsbuild.org/2.20/docs/using-pants/key-concepts/backends#available-stable-backends) Reproducer: ```shell cd $(mktemp -d) cat > pants.toml <<EOF [GLOBAL] pants_version = "2.20.0a0" backend_packages = [] EOF # https://docs.astral.sh/ruff/formatter/black/#single-element-tuples-are-always-parenthesized echo '(1, 2),' > BUILD pants update-build-files :: ``` This sets up a build file that has different expected formatting for black vs. ruff by abuse a difference between them. Running with `PANTS_VERSION=2.19.0 bash run.sh` (or anything up to `PANTS_VERSION=2.20.0.dev7 bash run.sh`) has output: ``` 12:37:40.96 [INFO] Initializing scheduler... 12:37:41.14 [INFO] Scheduler initialized. 12:37:45.89 [INFO] Starting: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:37:46.76 [INFO] Completed: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:37:47.37 [INFO] No required changes to BUILD files found.However, there may still be deprecations that `update-build-files` doesn't know how to fix. See https://www.pantsbuild.org/v2.19/docs/upgrade-tips for upgrade tips. ``` Notably: - builds black ✅ - doesn't reformat ✅ Running with `bash run.sh` has output: ``` PANTS_LOCAL_CACHE=false bash run.sh 12:39:35.21 [INFO] Initializing scheduler... 12:39:35.39 [INFO] Scheduler initialized. ... 12:39:37.04 [INFO] Starting: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:39:37.82 [INFO] Completed: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:39:38.11 [INFO] Starting: Building yapf.pex from resource://pants.backend.python.lint.yapf/yapf.lock 12:39:38.86 [INFO] Completed: Building yapf.pex from resource://pants.backend.python.lint.yapf/yapf.lock 12:39:38.97 [INFO] Starting: Building ruff.pex from resource://pants.backend.python.lint.ruff/ruff.lock 12:39:39.88 [INFO] Completed: Building ruff.pex from resource://pants.backend.python.lint.ruff/ruff.lock Updated BUILD: - Format with Ruff ``` Notably: - builds black ✅ and ruff ❌ and yapf ❌ - reformats with ruff ❌ **Pants version** 2.20.0a0 This seems to be a regression between that and 2.20.0.dev7 likely related to #20411. - https://github.com/pantsbuild/pants/releases/tag/release_2.20.0a0 - https://github.com/pantsbuild/pants/compare/release_2.20.0.dev7...release_2.20.0a0 **OS** macOS **Additional info** N/A
2024-02-19T23:39:49
pantsbuild/pants
20,581
pantsbuild__pants-20581
[ "20575" ]
62828b7f56abeeea79b9249b8d97ae7d78847785
diff --git a/src/python/pants/core/util_rules/adhoc_process_support.py b/src/python/pants/core/util_rules/adhoc_process_support.py --- a/src/python/pants/core/util_rules/adhoc_process_support.py +++ b/src/python/pants/core/util_rules/adhoc_process_support.py @@ -411,7 +411,7 @@ async def create_tool_runner( Get( ResolvedExecutionDependencies, ResolveExecutionDependenciesRequest( - address=runnable_address, + address=request.target.address, execution_dependencies=request.execution_dependencies, runnable_dependencies=request.runnable_dependencies, ),
diff --git a/src/python/pants/backend/adhoc/adhoc_tool_test.py b/src/python/pants/backend/adhoc/adhoc_tool_test.py --- a/src/python/pants/backend/adhoc/adhoc_tool_test.py +++ b/src/python/pants/backend/adhoc/adhoc_tool_test.py @@ -268,3 +268,37 @@ def test_env_vars(rule_runner: PythonRuleRunner) -> None: Address("src", target_name="envvars"), expected_contents={"out.log": f"{envvar_value}\n"}, ) + + +def test_execution_dependencies_and_runnable_dependencies(rule_runner: PythonRuleRunner) -> None: + file_contents = "example contents" + + rule_runner.write_files( + { + # put the runnable in its own directory, so we're sure that the dependencies are + # resolved relative to the adhoc_tool target + "a/BUILD": """system_binary(name="bash", binary_name="bash")""", + "b/BUILD": dedent( + """ + system_binary(name="renamed_cat", binary_name="cat") + files(name="f", sources=["f.txt"]) + + adhoc_tool( + name="deps", + runnable="a:bash", + args=["-c", "renamed_cat f.txt"], + execution_dependencies=[":f"], + runnable_dependencies=[":renamed_cat"], + stdout="stdout", + ) + """ + ), + "b/f.txt": file_contents, + } + ) + + assert_adhoc_tool_result( + rule_runner, + Address("b", target_name="deps"), + expected_contents={"b/stdout": file_contents}, + ) diff --git a/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py b/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py --- a/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py +++ b/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py @@ -10,6 +10,8 @@ CodeQualityToolUnsupportedGoalError, base_rules, ) +from pants.backend.adhoc.run_system_binary import rules as run_system_binary_rules +from pants.backend.adhoc.target_types import SystemBinaryTarget from pants.backend.python import register as register_python from pants.backend.python.target_types import PythonSourceTarget from pants.core.goals.fix import Fix @@ -35,6 +37,7 @@ def make_rule_runner(*cfgs: CodeQualityToolRuleBuilder): *core_rules(), *process.rules(), *register_python.rules(), + *run_system_binary_rules(), *base_rules(), ] for cfg in cfgs: @@ -45,6 +48,7 @@ def make_rule_runner(*cfgs: CodeQualityToolRuleBuilder): CodeQualityToolTarget, FileTarget, PythonSourceTarget, + SystemBinaryTarget, ], rules=rules, ) @@ -276,3 +280,48 @@ def test_several_formatters(): assert "badtogood made changes" in res.stderr assert "underscoreit" not in res.stderr assert "goodcode = 50\ngoodcode = 100\n" == rule_runner.read_file("do_not_underscore.py") + + +def test_execution_dependencies_and_runnable_dependencies(): + input_contents = "input contents\n" + output_contents = "original output contents" + # confirm that comparing these strings confirms that the test behaved as expected + assert input_contents != output_contents + + cfg = CodeQualityToolRuleBuilder( + goal="fmt", target="b:overwriter", name="Overwriter", scope="overwriter" + ) + + # Formatter that copies the `b/input.txt` file over `b/output.txt` file via bash (relying on + # there being only one file, and a workaround for #19103 meaning we can't use `cp` as a system + # binary) + rule_runner = make_rule_runner(cfg) + rule_runner.write_files( + { + # put the runnable in its own directory, so we're sure that the dependencies are + # resolved relative to the code_quality_tool target + "a/BUILD": """system_binary(name="bash", binary_name="bash")""", + "b/BUILD": dedent( + """ + system_binary(name="renamed_cat", binary_name="cat") + file(name="input", source="input.txt") + file(name="output", source="output.txt") + + code_quality_tool( + name="overwriter", + runnable="a:bash", + args=["-c", "renamed_cat b/input.txt > $1", "ignored"], + execution_dependencies=[":input"], + runnable_dependencies=[":renamed_cat"], + file_glob_include=["**/*.txt"], + ) + """ + ), + "b/input.txt": input_contents, + "b/output.txt": output_contents, + } + ) + res = rule_runner.run_goal_rule(Fmt, args=["b/output.txt"]) + assert res.exit_code == 0 + assert "overwriter made changes" in res.stderr + assert input_contents == rule_runner.read_file("b/output.txt")
2.20 changes `adhoc_tool` to resolve target specs in `execution_dependencies` relative to `runnable`, not target **Describe the bug** It seems 2.20 changes behaviour for how the dependency target specs are resolved in a BUILD file like: ```python file(name="f", source="f.txt") adhoc_tool( name="tool", runnable="a:cat", args=["f.txt"], execution_dependencies=[":f"], log_output=True, ) ``` If that's in `b/`, then the `execution_dependencies` field refers to: - 2.19: `b:f` - 2.20: `a:f` This is a regression/breakage that may require users to update code, so, if it's a desirable change, we'd _preferably_ not do it without warning/deprecation (although it is experimental, so maybe we decide it's worth it)... but it seems undesirable? Reproducer: ```shell cd $(mktemp -d) cat > pants.toml <<EOF [GLOBAL] pants_version = "2.20.0a0" backend_packages = [ "pants.backend.experimental.adhoc", ] EOF mkdir -p a b cat > a/BUILD <<EOF system_binary(name="cat", binary_name="cat") EOF cat > b/BUILD <<EOF file(name="f", source="f.txt") adhoc_tool( name="tool", runnable="a:cat", args=["f.txt"], execution_dependencies=[":f"], log_output=True, ) EOF echo "contents of f.txt here" > b/f.txt # OKAY: successfully cats the file, and exports PANTS_VERSION=2.19.0 pants export-codegen b:tool # BUG: 'ResolveError: The address a:f from the `execution_dependencies` from the target a:cat does not exist.' pants export-codegen b:tool ``` **Pants version** 2.20.0a0 This appears to be be a regression from 2.20.0.dev3 (works like 2.19) to 2.20.0.dev4 (has this new behaviour). - https://github.com/pantsbuild/pants/releases/tag/release_2.20.0.dev4 - https://github.com/pantsbuild/pants/compare/release_2.20.0.dev3...release_2.20.0.dev4 **OS** macOS **Additional info** N/A
2024-02-19T23:48:07
pantsbuild/pants
20,582
pantsbuild__pants-20582
[ "20576" ]
d55b718b5eefc55ac9cfd71622728427fb6e6099
diff --git a/src/python/pants/core/goals/update_build_files.py b/src/python/pants/core/goals/update_build_files.py --- a/src/python/pants/core/goals/update_build_files.py +++ b/src/python/pants/core/goals/update_build_files.py @@ -234,10 +234,17 @@ async def update_build_files( raise ValueError(f"Unrecognized formatter: {update_build_files_subsystem.formatter}") for request in union_membership[RewrittenBuildFileRequest]: - if update_build_files_subsystem.fmt and issubclass(request, chosen_formatter_request_class): + if update_build_files_subsystem.fmt and request == chosen_formatter_request_class: rewrite_request_classes.append(request) - if update_build_files_subsystem.fix_safe_deprecations or not issubclass( + if update_build_files_subsystem.fix_safe_deprecations and issubclass( + request, DeprecationFixerRequest + ): + rewrite_request_classes.append(request) + + # If there are other types of requests that aren't the standard formatter + # backends or deprecation fixers, add them here. + if request not in formatter_to_request_class.values() and not issubclass( request, DeprecationFixerRequest ): rewrite_request_classes.append(request)
diff --git a/src/python/pants/core/goals/update_build_files_test.py b/src/python/pants/core/goals/update_build_files_test.py --- a/src/python/pants/core/goals/update_build_files_test.py +++ b/src/python/pants/core/goals/update_build_files_test.py @@ -74,12 +74,24 @@ def reverse_lines(request: MockRewriteReverseLines) -> RewrittenBuildFile: def generic_goal_rule_runner() -> RuleRunner: return RuleRunner( rules=( - update_build_files, add_line, reverse_lines, + format_build_file_with_ruff, + format_build_file_with_yapf, + update_build_files, + *config_files.rules(), + *pex.rules(), + # Ruff and Yapf are included, but Black isn't because + # that's the formatter we enable in pants.toml. + # These tests check that Ruff and Yapf are NOT invoked, + # but the other rewrite targets are invoked. + *Ruff.rules(), + *Yapf.rules(), *UpdateBuildFilesSubsystem.rules(), UnionRule(RewrittenBuildFileRequest, MockRewriteAddLine), UnionRule(RewrittenBuildFileRequest, MockRewriteReverseLines), + UnionRule(RewrittenBuildFileRequest, FormatWithRuffRequest), + UnionRule(RewrittenBuildFileRequest, FormatWithYapfRequest), ) ) @@ -204,12 +216,20 @@ def black_rule_runner() -> RuleRunner: return RuleRunner( rules=( format_build_file_with_black, + format_build_file_with_ruff, + format_build_file_with_yapf, update_build_files, *config_files.rules(), *pex.rules(), *Black.rules(), + # Even though Ruff and Yapf are included here, + # only Black should be used for formatting. + *Ruff.rules(), + *Yapf.rules(), *UpdateBuildFilesSubsystem.rules(), UnionRule(RewrittenBuildFileRequest, FormatWithBlackRequest), + UnionRule(RewrittenBuildFileRequest, FormatWithRuffRequest), + UnionRule(RewrittenBuildFileRequest, FormatWithYapfRequest), ), target_types=[GenericTarget], )
2.20 runs ruff and yapf on BUILD files without opting in to them **Describe the bug** The default behaviour of `pants update-build-files ::` seems to have changed in 2.20, compared to 2.19. In particular, it seems to now build and run yapf and ruff, in addition to black, without opting in to the ruff or yapf formatters via the `pants.backend.build_files.fmt.*` backends. (https://www.pantsbuild.org/2.20/docs/using-pants/key-concepts/backends#available-stable-backends) Reproducer: ```shell cd $(mktemp -d) cat > pants.toml <<EOF [GLOBAL] pants_version = "2.20.0a0" backend_packages = [] EOF # https://docs.astral.sh/ruff/formatter/black/#single-element-tuples-are-always-parenthesized echo '(1, 2),' > BUILD pants update-build-files :: ``` This sets up a build file that has different expected formatting for black vs. ruff by abuse a difference between them. Running with `PANTS_VERSION=2.19.0 bash run.sh` (or anything up to `PANTS_VERSION=2.20.0.dev7 bash run.sh`) has output: ``` 12:37:40.96 [INFO] Initializing scheduler... 12:37:41.14 [INFO] Scheduler initialized. 12:37:45.89 [INFO] Starting: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:37:46.76 [INFO] Completed: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:37:47.37 [INFO] No required changes to BUILD files found.However, there may still be deprecations that `update-build-files` doesn't know how to fix. See https://www.pantsbuild.org/v2.19/docs/upgrade-tips for upgrade tips. ``` Notably: - builds black ✅ - doesn't reformat ✅ Running with `bash run.sh` has output: ``` PANTS_LOCAL_CACHE=false bash run.sh 12:39:35.21 [INFO] Initializing scheduler... 12:39:35.39 [INFO] Scheduler initialized. ... 12:39:37.04 [INFO] Starting: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:39:37.82 [INFO] Completed: Building black.pex from resource://pants.backend.python.lint.black/black.lock 12:39:38.11 [INFO] Starting: Building yapf.pex from resource://pants.backend.python.lint.yapf/yapf.lock 12:39:38.86 [INFO] Completed: Building yapf.pex from resource://pants.backend.python.lint.yapf/yapf.lock 12:39:38.97 [INFO] Starting: Building ruff.pex from resource://pants.backend.python.lint.ruff/ruff.lock 12:39:39.88 [INFO] Completed: Building ruff.pex from resource://pants.backend.python.lint.ruff/ruff.lock Updated BUILD: - Format with Ruff ``` Notably: - builds black ✅ and ruff ❌ and yapf ❌ - reformats with ruff ❌ **Pants version** 2.20.0a0 This seems to be a regression between that and 2.20.0.dev7 likely related to #20411. - https://github.com/pantsbuild/pants/releases/tag/release_2.20.0a0 - https://github.com/pantsbuild/pants/compare/release_2.20.0.dev7...release_2.20.0a0 **OS** macOS **Additional info** N/A
Thanks for noticing I'd filed this @krishnan-chandra, assigned to you based on #20580 existing 😄
2024-02-20T01:15:54
pantsbuild/pants
20,600
pantsbuild__pants-20600
[ "20596" ]
e4532cb765bc1de2b515a19b2d418a742e13949a
diff --git a/src/python/pants/backend/docker/goals/package_image.py b/src/python/pants/backend/docker/goals/package_image.py --- a/src/python/pants/backend/docker/goals/package_image.py +++ b/src/python/pants/backend/docker/goals/package_image.py @@ -18,6 +18,7 @@ from pants.backend.docker.subsystems.docker_options import DockerOptions from pants.backend.docker.target_types import ( DockerBuildKitOptionField, + DockerBuildOptionFieldListOfMultiValueDictMixin, DockerBuildOptionFieldMixin, DockerBuildOptionFieldMultiValueDictMixin, DockerBuildOptionFieldMultiValueMixin, @@ -336,6 +337,7 @@ def get_build_options( ( DockerBuildOptionFieldMixin, DockerBuildOptionFieldMultiValueDictMixin, + DockerBuildOptionFieldListOfMultiValueDictMixin, DockerBuildOptionFieldValueMixin, DockerBuildOptionFieldMultiValueMixin, DockerBuildOptionFlagFieldMixin, diff --git a/src/python/pants/backend/docker/target_types.py b/src/python/pants/backend/docker/target_types.py --- a/src/python/pants/backend/docker/target_types.py +++ b/src/python/pants/backend/docker/target_types.py @@ -29,6 +29,7 @@ DictStringToStringField, Field, InvalidFieldException, + ListOfDictStringToStringField, OptionalSingleSourceField, StringField, StringSequenceField, @@ -312,6 +313,23 @@ def options(self, value_formatter: OptionValueFormatter, **kwargs) -> Iterator[s ) +class DockerBuildOptionFieldListOfMultiValueDictMixin(ListOfDictStringToStringField): + """Inherit this mixin class to provide multiple key-value options to docker build: + + `--flag=key1=value1,key2=value2 --flag=key3=value3,key4=value4` + """ + + docker_build_option: ClassVar[str] + + @final + def options(self, value_formatter: OptionValueFormatter, **kwargs) -> Iterator[str]: + if self.value: + for item in self.value: + yield f"{self.docker_build_option}=" + ",".join( + f"{key}={value_formatter(value)}" for key, value in item.items() + ) + + class DockerBuildKitOptionField: """Mixin to indicate a BuildKit-specific option.""" @@ -330,6 +348,10 @@ class DockerImageBuildImageCacheToField( f""" Export image build cache to an external cache destination. + Note that Docker [supports](https://docs.docker.com/build/cache/backends/#multiple-caches) + multiple cache sources - Pants will pass these as multiple `--cache_from` arguments to the + Docker CLI. Docker will only use the first cache hit (i.e. the image exists) in the build. + {DockerBuildKitOptionField.required_help} Example: @@ -340,10 +362,10 @@ class DockerImageBuildImageCacheToField( "type": "local", "dest": "/tmp/docker-cache/example" }}, - cache_from={{ + cache_from=[{{ "type": "local", "src": "/tmp/docker-cache/example" - }} + }}] ) {_interpolation_help.format(kind="Values")} @@ -353,12 +375,14 @@ class DockerImageBuildImageCacheToField( class DockerImageBuildImageCacheFromField( - DockerBuildOptionFieldMultiValueDictMixin, DictStringToStringField, DockerBuildKitOptionField + DockerBuildOptionFieldListOfMultiValueDictMixin, + ListOfDictStringToStringField, + DockerBuildKitOptionField, ): alias = "cache_from" help = help_text( f""" - Use an external cache source when building the image. + Use external cache sources when building the image. {DockerBuildKitOptionField.required_help} @@ -368,12 +392,18 @@ class DockerImageBuildImageCacheFromField( name="example-local-cache-backend", cache_to={{ "type": "local", - "dest": "/tmp/docker-cache/example" + "dest": "/tmp/docker-cache/primary" }}, - cache_from={{ - "type": "local", - "src": "/tmp/docker-cache/example" - }} + cache_from=[ + {{ + "type": "local", + "src": "/tmp/docker-cache/primary" + }}, + {{ + "type": "local", + "src": "/tmp/docker-cache/secondary" + }} + ] ) {_interpolation_help.format(kind="Values")} diff --git a/src/python/pants/engine/target.py b/src/python/pants/engine/target.py --- a/src/python/pants/engine/target.py +++ b/src/python/pants/engine/target.py @@ -1918,6 +1918,39 @@ def compute_value( return FrozenDict(value_or_default) +class ListOfDictStringToStringField(Field): + value: Optional[Tuple[FrozenDict[str, str]]] + default: ClassVar[Optional[list[FrozenDict[str, str]]]] = None + + @classmethod + def compute_value( + cls, raw_value: Optional[list[Dict[str, str]]], address: Address + ) -> Optional[Tuple[FrozenDict[str, str], ...]]: + value_or_default = super().compute_value(raw_value, address) + if value_or_default is None: + return None + invalid_type_exception = InvalidFieldTypeException( + address, + cls.alias, + raw_value, + expected_type="a list of dictionaries (or a single dictionary) of string -> string", + ) + + # Also support passing in a single dictionary by wrapping it + if not isinstance(value_or_default, list): + value_or_default = [value_or_default] + + result_lst: list[FrozenDict[str, str]] = [] + for item in value_or_default: + if not isinstance(item, collections.abc.Mapping): + raise invalid_type_exception + if not all(isinstance(k, str) and isinstance(v, str) for k, v in item.items()): + raise invalid_type_exception + result_lst.append(FrozenDict(item)) + + return tuple(result_lst) + + class NestedDictStringToStringField(Field): value: Optional[FrozenDict[str, FrozenDict[str, str]]] default: ClassVar[Optional[FrozenDict[str, FrozenDict[str, str]]]] = None
diff --git a/src/python/pants/backend/docker/goals/package_image_test.py b/src/python/pants/backend/docker/goals/package_image_test.py --- a/src/python/pants/backend/docker/goals/package_image_test.py +++ b/src/python/pants/backend/docker/goals/package_image_test.py @@ -1152,7 +1152,7 @@ def test_docker_cache_from_option(rule_runner: RuleRunner) -> None: """\ docker_image( name="img1", - cache_from={"type": "local", "dest": "/tmp/docker/pants-test-cache"}, + cache_from=[{"type": "local", "dest": "/tmp/docker/pants-test-cache1"}, {"type": "local", "dest": "/tmp/docker/pants-test-cache2"}], ) """ ), @@ -1164,7 +1164,8 @@ def check_docker_proc(process: Process): "/dummy/docker", "buildx", "build", - "--cache-from=type=local,dest=/tmp/docker/pants-test-cache", + "--cache-from=type=local,dest=/tmp/docker/pants-test-cache1", + "--cache-from=type=local,dest=/tmp/docker/pants-test-cache2", "--output=type=docker", "--pull=False", "--tag", diff --git a/src/python/pants/engine/target_test.py b/src/python/pants/engine/target_test.py --- a/src/python/pants/engine/target_test.py +++ b/src/python/pants/engine/target_test.py @@ -31,6 +31,7 @@ InvalidFieldTypeException, InvalidGeneratedTargetException, InvalidTargetException, + ListOfDictStringToStringField, MultipleSourcesField, NestedDictStringToStringField, OptionalSingleSourceField, @@ -870,6 +871,34 @@ class ExampleDefault(DictStringToStringField): assert ExampleDefault(None, addr).value == FrozenDict({"default": "val"}) +def test_list_of_dict_string_to_string_field() -> None: + class Example(ListOfDictStringToStringField): + alias = "example" + + addr = Address("", target_name="example") + + assert Example(None, addr).value is None + assert Example([{}], addr).value == (FrozenDict(),) + assert Example([{"hello": "world"}], addr).value == (FrozenDict({"hello": "world"}),) + # Test support for single dict not passed in a list + assert Example({"hello": "world"}, addr).value == (FrozenDict({"hello": "world"}),) + + def assert_invalid_type(raw_value: Any) -> None: + with pytest.raises(InvalidFieldTypeException): + Example(raw_value, addr) + + for v in [0, [0], [object()], ["hello"], [["hello"]], [{"hello": 0}], [{0: "world"}]]: + assert_invalid_type(v) + + # Test that a default can be set. + class ExampleDefault(ListOfDictStringToStringField): + alias = "example" + # Note that we use `FrozenDict` so that the object can be hashable. + default = [FrozenDict({"default": "val"})] + + assert ExampleDefault(None, addr).value == (FrozenDict({"default": "val"}),) + + def test_nested_dict_string_to_string_field() -> None: class Example(NestedDictStringToStringField): alias = "example"
Allow multiple `cache_from` entries for `docker_image` **Is your feature request related to a problem? Please describe.** buildx supports multiple `cache-from` arguments (though the [documentation is a bit lacking](https://github.com/docker/docs/issues/8531)). **Describe the solution you'd like** Allow `cache_from`'s type to be `list[dict[str, str]] | dict[str, str] | None` in `docker_image`
2024-02-24T03:53:58
pantsbuild/pants
20,607
pantsbuild__pants-20607
[ "20440" ]
e4532cb765bc1de2b515a19b2d418a742e13949a
diff --git a/src/python/pants/backend/docker/goals/run_image.py b/src/python/pants/backend/docker/goals/run_image.py --- a/src/python/pants/backend/docker/goals/run_image.py +++ b/src/python/pants/backend/docker/goals/run_image.py @@ -8,7 +8,11 @@ from pants.backend.docker.goals.package_image import BuiltDockerImage, DockerPackageFieldSet from pants.backend.docker.subsystems.docker_options import DockerOptions -from pants.backend.docker.target_types import DockerImageRegistriesField, DockerImageSourceField +from pants.backend.docker.target_types import ( + DockerImageRegistriesField, + DockerImageRunExtraArgsField, + DockerImageSourceField, +) from pants.backend.docker.util_rules.docker_binary import DockerBinary from pants.core.goals.package import BuiltPackage, PackageFieldSet from pants.core.goals.run import RunFieldSet, RunInSandboxBehavior, RunRequest @@ -22,6 +26,11 @@ class DockerRunFieldSet(RunFieldSet): required_fields = (DockerImageSourceField,) run_in_sandbox_behavior = RunInSandboxBehavior.RUN_REQUEST_HERMETIC + extra_run_args: DockerImageRunExtraArgsField + + def get_run_args(self, options: DockerOptions) -> tuple[str, ...]: + return tuple(options.run_args + (self.extra_run_args.value or ())) + @rule async def docker_image_run_request( @@ -49,8 +58,13 @@ async def docker_image_run_request( Get(EnvironmentVars, EnvironmentVarsRequest(options_env_aware.env_vars)), Get(BuiltPackage, PackageFieldSet, build_request), ) + tag = cast(BuiltDockerImage, image.artifacts[0]).tags[0] - run = docker.run_image(tag, docker_run_args=options.run_args, env=env) + run = docker.run_image( + tag, + docker_run_args=field_set.get_run_args(options), + env=env, + ) return RunRequest( digest=image.digest, diff --git a/src/python/pants/backend/docker/target_types.py b/src/python/pants/backend/docker/target_types.py --- a/src/python/pants/backend/docker/target_types.py +++ b/src/python/pants/backend/docker/target_types.py @@ -12,6 +12,7 @@ from typing_extensions import final from pants.backend.docker.registries import ALL_DEFAULT_REGISTRIES +from pants.backend.docker.subsystems.docker_options import DockerOptions from pants.base.build_environment import get_buildroot from pants.core.goals.package import OutputPathField from pants.core.goals.run import RestartableField @@ -559,6 +560,14 @@ class DockerImageBuildPlatformOptionField( docker_build_option = "--platform" +class DockerImageRunExtraArgsField(StringSequenceField): + alias: ClassVar[str] = "extra_run_args" + default = () + help = help_text( + lambda: f"Extra arguments to pass into the invocation of `docker run`. These are in addition to those at the `[{DockerOptions.options_scope}].run_args`" + ) + + class DockerImageTarget(Target): alias = "docker_image" core_fields = ( @@ -584,6 +593,7 @@ class DockerImageTarget(Target): DockerImageBuildImageCacheToField, DockerImageBuildImageCacheFromField, DockerImageBuildImageOutputField, + DockerImageRunExtraArgsField, OutputPathField, RestartableField, )
diff --git a/src/python/pants/backend/docker/goals/run_image_integration_test.py b/src/python/pants/backend/docker/goals/run_image_integration_test.py --- a/src/python/pants/backend/docker/goals/run_image_integration_test.py +++ b/src/python/pants/backend/docker/goals/run_image_integration_test.py @@ -5,6 +5,9 @@ from textwrap import dedent +import pytest + +from pants.backend.docker.target_types import DockerImageRunExtraArgsField from pants.testutil.pants_integration_test import PantsResult, run_pants, setup_tmpdir @@ -20,22 +23,37 @@ def run_pants_with_sources(sources: dict[str, str], *args: str) -> PantsResult: ) -def test_docker_run() -> None: [email protected]("override_run_args", [True, False]) +def test_docker_run(override_run_args) -> None: + """This test exercises overriding the run args at the target level. + + It works by setting a default value for an envvar in the Dockerfile with the `ENV` statement, + and then overriding that envvar with the `-e` option on the target level. + """ + + expected_value = "override" if override_run_args else "build" + docker_run_args_attribute = ( + f'{DockerImageRunExtraArgsField.alias}=["-e", "mykey=override"]' + if override_run_args + else "" + ) + sources = { - "BUILD": "docker_image(name='run-image')", + "BUILD": f"docker_image(name='run-image', {docker_run_args_attribute})", "Dockerfile": dedent( """\ FROM alpine - CMD echo "Hello from Docker image" + ENV mykey=build + CMD echo "Hello from Docker image with mykey=$mykey" """ ), } + result = run_pants_with_sources( sources, "run", "{tmpdir}:run-image", ) - print("pants stderr\n", result.stderr) - assert "Hello from Docker image\n" == result.stdout + assert f"Hello from Docker image with mykey={expected_value}\n" == result.stdout result.assert_success()
Add support for adding arbitrary docker flags **Is your feature request related to a problem? Please describe.** Docker has a lot of different flags, most of which are not officially supported via pants, I'd like to be able to use them without needing code changes to pants. E.g. right now I need to add --debug to my command to see some stack traces from docker. Previously I wanted to use the cache_to/from args before they were officially in pants. I would also like to be able to setup run args, e.g. ports to forward, volumes to map, etc. **Describe the solution you'd like** I'd like docker_image and pants.toml to get some extra parameters for extra_command_line_build_args to be passed to docker build and extra_command_line_run_args to be passed to docker run. Adding formatting for putting variables (eg homedir, pants hash, etc) into args would also be helpful. **Describe alternatives you've considered** Adding every flag to pants that does not need special handling seems wasteful.
@kaos thoughts? yes, this has been agreed before to be a good idea. the main issue has been to come up with the design for it that is intuitive to use. the unfortunate bit is that we have `[docker].build_args` which are for `docker build --arg` so not arbitrary args for the build step, while for `docker run` this already [exists](https://www.pantsbuild.org/2.18/reference/subsystems/docker#run_args). at this point, probably just adding it with proper docs to get it done could be acceptable. perhaps something along the lines of `[docker].build_cli_args`.. > [...] and extra_command_line_run_args to be passed to docker run. This is `[docker].run_args`. I personally need run_args to be in the docker_image target, which I at least don't see in the docs. > I personally need run_args to be in the docker_image target, which I at least don't see in the docs. Ah, right. No, it's only globally in configuration thus far. PR welcome to address these features if you're able to :) Thoughts on whether the per-target option should shadow or add to the global option?
2024-02-25T05:06:27
pantsbuild/pants
20,608
pantsbuild__pants-20608
[ "20575" ]
6c5e3f3e72dbb52ee0b67c7b78a2c2622b73f4cb
diff --git a/src/python/pants/core/util_rules/adhoc_process_support.py b/src/python/pants/core/util_rules/adhoc_process_support.py --- a/src/python/pants/core/util_rules/adhoc_process_support.py +++ b/src/python/pants/core/util_rules/adhoc_process_support.py @@ -411,7 +411,7 @@ async def create_tool_runner( Get( ResolvedExecutionDependencies, ResolveExecutionDependenciesRequest( - address=runnable_address, + address=request.target.address, execution_dependencies=request.execution_dependencies, runnable_dependencies=request.runnable_dependencies, ),
diff --git a/src/python/pants/backend/adhoc/adhoc_tool_test.py b/src/python/pants/backend/adhoc/adhoc_tool_test.py --- a/src/python/pants/backend/adhoc/adhoc_tool_test.py +++ b/src/python/pants/backend/adhoc/adhoc_tool_test.py @@ -268,3 +268,37 @@ def test_env_vars(rule_runner: PythonRuleRunner) -> None: Address("src", target_name="envvars"), expected_contents={"out.log": f"{envvar_value}\n"}, ) + + +def test_execution_dependencies_and_runnable_dependencies(rule_runner: PythonRuleRunner) -> None: + file_contents = "example contents" + + rule_runner.write_files( + { + # put the runnable in its own directory, so we're sure that the dependencies are + # resolved relative to the adhoc_tool target + "a/BUILD": """system_binary(name="bash", binary_name="bash")""", + "b/BUILD": dedent( + """ + system_binary(name="renamed_cat", binary_name="cat") + files(name="f", sources=["f.txt"]) + + adhoc_tool( + name="deps", + runnable="a:bash", + args=["-c", "renamed_cat f.txt"], + execution_dependencies=[":f"], + runnable_dependencies=[":renamed_cat"], + stdout="stdout", + ) + """ + ), + "b/f.txt": file_contents, + } + ) + + assert_adhoc_tool_result( + rule_runner, + Address("b", target_name="deps"), + expected_contents={"b/stdout": file_contents}, + ) diff --git a/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py b/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py --- a/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py +++ b/src/python/pants/backend/adhoc/code_quality_tool_integration_test.py @@ -10,6 +10,8 @@ CodeQualityToolUnsupportedGoalError, base_rules, ) +from pants.backend.adhoc.run_system_binary import rules as run_system_binary_rules +from pants.backend.adhoc.target_types import SystemBinaryTarget from pants.backend.python import register as register_python from pants.backend.python.target_types import PythonSourceTarget from pants.core.goals.fix import Fix @@ -35,6 +37,7 @@ def make_rule_runner(*cfgs: CodeQualityToolRuleBuilder): *core_rules(), *process.rules(), *register_python.rules(), + *run_system_binary_rules(), *base_rules(), ] for cfg in cfgs: @@ -45,6 +48,7 @@ def make_rule_runner(*cfgs: CodeQualityToolRuleBuilder): CodeQualityToolTarget, FileTarget, PythonSourceTarget, + SystemBinaryTarget, ], rules=rules, ) @@ -276,3 +280,48 @@ def test_several_formatters(): assert "badtogood made changes" in res.stderr assert "underscoreit" not in res.stderr assert "goodcode = 50\ngoodcode = 100\n" == rule_runner.read_file("do_not_underscore.py") + + +def test_execution_dependencies_and_runnable_dependencies(): + input_contents = "input contents\n" + output_contents = "original output contents" + # confirm that comparing these strings confirms that the test behaved as expected + assert input_contents != output_contents + + cfg = CodeQualityToolRuleBuilder( + goal="fmt", target="b:overwriter", name="Overwriter", scope="overwriter" + ) + + # Formatter that copies the `b/input.txt` file over `b/output.txt` file via bash (relying on + # there being only one file, and a workaround for #19103 meaning we can't use `cp` as a system + # binary) + rule_runner = make_rule_runner(cfg) + rule_runner.write_files( + { + # put the runnable in its own directory, so we're sure that the dependencies are + # resolved relative to the code_quality_tool target + "a/BUILD": """system_binary(name="bash", binary_name="bash")""", + "b/BUILD": dedent( + """ + system_binary(name="renamed_cat", binary_name="cat") + file(name="input", source="input.txt") + file(name="output", source="output.txt") + + code_quality_tool( + name="overwriter", + runnable="a:bash", + args=["-c", "renamed_cat b/input.txt > $1", "ignored"], + execution_dependencies=[":input"], + runnable_dependencies=[":renamed_cat"], + file_glob_include=["**/*.txt"], + ) + """ + ), + "b/input.txt": input_contents, + "b/output.txt": output_contents, + } + ) + res = rule_runner.run_goal_rule(Fmt, args=["b/output.txt"]) + assert res.exit_code == 0 + assert "overwriter made changes" in res.stderr + assert input_contents == rule_runner.read_file("b/output.txt")
2.20 changes `adhoc_tool` to resolve target specs in `execution_dependencies` relative to `runnable`, not target **Describe the bug** It seems 2.20 changes behaviour for how the dependency target specs are resolved in a BUILD file like: ```python file(name="f", source="f.txt") adhoc_tool( name="tool", runnable="a:cat", args=["f.txt"], execution_dependencies=[":f"], log_output=True, ) ``` If that's in `b/`, then the `execution_dependencies` field refers to: - 2.19: `b:f` - 2.20: `a:f` This is a regression/breakage that may require users to update code, so, if it's a desirable change, we'd _preferably_ not do it without warning/deprecation (although it is experimental, so maybe we decide it's worth it)... but it seems undesirable? Reproducer: ```shell cd $(mktemp -d) cat > pants.toml <<EOF [GLOBAL] pants_version = "2.20.0a0" backend_packages = [ "pants.backend.experimental.adhoc", ] EOF mkdir -p a b cat > a/BUILD <<EOF system_binary(name="cat", binary_name="cat") EOF cat > b/BUILD <<EOF file(name="f", source="f.txt") adhoc_tool( name="tool", runnable="a:cat", args=["f.txt"], execution_dependencies=[":f"], log_output=True, ) EOF echo "contents of f.txt here" > b/f.txt # OKAY: successfully cats the file, and exports PANTS_VERSION=2.19.0 pants export-codegen b:tool # BUG: 'ResolveError: The address a:f from the `execution_dependencies` from the target a:cat does not exist.' pants export-codegen b:tool ``` **Pants version** 2.20.0a0 This appears to be be a regression from 2.20.0.dev3 (works like 2.19) to 2.20.0.dev4 (has this new behaviour). - https://github.com/pantsbuild/pants/releases/tag/release_2.20.0.dev4 - https://github.com/pantsbuild/pants/compare/release_2.20.0.dev3...release_2.20.0.dev4 **OS** macOS **Additional info** N/A
2024-02-25T23:21:55
pantsbuild/pants
20,628
pantsbuild__pants-20628
[ "20627" ]
2e5c50511f809aa3c007bb54924277c3b0348f64
diff --git a/src/python/pants/engine/internals/graph.py b/src/python/pants/engine/internals/graph.py --- a/src/python/pants/engine/internals/graph.py +++ b/src/python/pants/engine/internals/graph.py @@ -11,7 +11,7 @@ import os.path from dataclasses import dataclass from pathlib import PurePath -from typing import Any, Iterable, Iterator, NamedTuple, Sequence, Type, cast +from typing import Any, Iterable, Iterator, NamedTuple, Sequence, Type, TypeVar, cast from pants.base.deprecated import warn_or_error from pants.base.specs import AncestorGlobSpec, RawSpecsWithoutFileOwners, RecursiveGlobSpec @@ -303,12 +303,12 @@ async def resolve_generator_target_requests( generator_fields, union_membership, ) - base_generator = target_type( - generator_fields, + base_generator = _create_target( req.address, - name_explicitly_set=target_adaptor.name_explicitly_set, - union_membership=union_membership, - description_of_origin=target_adaptor.description_of_origin, + target_type, + target_adaptor, + generator_fields, + union_membership, ) overrides = await _target_generator_overrides(base_generator, unmatched_build_file_globs) return ResolvedTargetGeneratorRequests( @@ -362,6 +362,36 @@ async def resolve_target_parametrizations( return _TargetParametrizations(parametrizations) +_TargetType = TypeVar("_TargetType", bound=Target) + + +def _create_target( + address: Address, + target_type: type[_TargetType], + target_adaptor: TargetAdaptor, + field_values: dict[str, Any], + union_membership: UnionMembership, + name_explicitly_set: bool | None = None, +) -> _TargetType: + target = target_type( + field_values, + address, + name_explicitly_set=( + target_adaptor.name_explicitly_set + if name_explicitly_set is None + else name_explicitly_set + ), + union_membership=union_membership, + description_of_origin=target_adaptor.description_of_origin, + ) + # Check for any deprecated field usage. + for field_type in target.field_types: + if field_type.deprecated_alias is not None and field_type.deprecated_alias in field_values: + warn_deprecated_field_type(field_type) + + return target + + def _target_parametrizations( address: Address, target_adaptor: TargetAdaptor, @@ -375,12 +405,12 @@ def _target_parametrizations( generated = FrozenDict( ( parameterized_address, - target_type( - parameterized_fields, + _create_target( parameterized_address, - name_explicitly_set=target_adaptor.name_explicitly_set, - union_membership=union_membership, - description_of_origin=target_adaptor.description_of_origin, + target_type, + target_adaptor, + parameterized_fields, + union_membership, ), ) for parameterized_address, parameterized_fields in expanded_parametrizations @@ -388,19 +418,13 @@ def _target_parametrizations( return _TargetParametrization(None, generated) else: # The target was not parametrized. - target = target_type( - target_adaptor.kwargs, + target = _create_target( address, - name_explicitly_set=target_adaptor.name_explicitly_set, - union_membership=union_membership, - description_of_origin=target_adaptor.description_of_origin, + target_type, + target_adaptor, + target_adaptor.kwargs, + union_membership, ) - for field_type in target.field_types: - if ( - field_type.deprecated_alias is not None - and field_type.deprecated_alias in target_adaptor.kwargs - ): - warn_deprecated_field_type(field_type) return _TargetParametrization(target, FrozenDict()) @@ -422,10 +446,20 @@ def _parametrized_target_generators_with_templates( *target_type._find_moved_plugin_fields(union_membership), ) for field_type in copied_fields: - field_value = generator_fields.get(field_type.alias, None) - if field_value is not None: - template_fields[field_type.alias] = field_value + for alias in (field_type.deprecated_alias, field_type.alias): + if alias is None: + continue + # Any deprecated field use will be checked on the generator target. + field_value = generator_fields.get(alias, None) + if field_value is not None: + template_fields[alias] = field_value for field_type in moved_fields: + # We must check for deprecated field usage here before passing the value to the generator. + if field_type.deprecated_alias is not None: + field_value = generator_fields.pop(field_type.deprecated_alias, None) + if field_value is not None: + warn_deprecated_field_type(field_type) + template_fields[field_type.deprecated_alias] = field_value field_value = generator_fields.pop(field_type.alias, None) if field_value is not None: template_fields[field_type.alias] = field_value @@ -459,12 +493,13 @@ def _parametrized_target_generators_with_templates( ) return [ ( - target_type( - generator_fields, + _create_target( address, + target_type, + target_adaptor, + generator_fields, + union_membership, name_explicitly_set=target_adaptor.name is not None, - union_membership=union_membership, - description_of_origin=target_adaptor.description_of_origin, ), template, )
diff --git a/src/python/pants/engine/internals/graph_test.py b/src/python/pants/engine/internals/graph_test.py --- a/src/python/pants/engine/internals/graph_test.py +++ b/src/python/pants/engine/internals/graph_test.py @@ -13,6 +13,7 @@ import pytest +from pants.base.deprecated import warn_or_error from pants.base.specs import Specs from pants.base.specs_parser import SpecsParser from pants.engine.addresses import Address, Addresses, AddressInput, UnparsedAddressInputs @@ -27,6 +28,7 @@ _DependencyMapping, _DependencyMappingRequest, _TargetParametrizations, + warn_deprecated_field_type, ) from pants.engine.internals.native_engine import AddressParseException from pants.engine.internals.parametrize import Parametrize, _TargetParametrizationsRequest @@ -73,6 +75,7 @@ ) from pants.engine.unions import UnionMembership, UnionRule from pants.testutil.rule_runner import QueryRule, RuleRunner, engine_error +from pants.util.docutil import bin_name from pants.util.ordered_set import FrozenOrderedSet @@ -114,7 +117,8 @@ def resolve_field_default_factory( class MockMultipleSourcesField(MultipleSourcesField): - pass + deprecated_alias = "deprecated_sources" + deprecated_alias_removal_version = "9.9.9.dev0" class MockPluginField(StringField): @@ -146,7 +150,7 @@ class MockTargetGenerator(TargetFilesGenerator): core_fields = (MockMultipleSourcesField, OverridesField) generated_target_cls = MockGeneratedTarget copied_fields = () - moved_fields = (Dependencies, Tags, ResolveField) + moved_fields = (MockDependencies, Tags, ResolveField) @pytest.fixture @@ -702,6 +706,32 @@ def test_deprecated_field_name(transitive_targets_rule_runner: RuleRunner, caplo assert "Instead, use `dependencies`" in caplog.text +def test_deprecated_field_name_on_generator_issue_20627( + transitive_targets_rule_runner: RuleRunner, caplog +) -> None: + warn_deprecated_field_type.forget(MockDependencies) # type: ignore[attr-defined] + warn_or_error.forget( # type: ignore[attr-defined] + removal_version=MockDependencies.deprecated_alias_removal_version, + entity=f"the field name {MockDependencies.deprecated_alias}", + hint=( + f"Instead, use `{MockDependencies.alias}`, which behaves the same. Run `{bin_name()} " + "update-build-files` to automatically fix your BUILD files." + ), + ) + transitive_targets_rule_runner.write_files( + { + "f1.txt": "", + "BUILD": "generator(name='t', deprecated_sources=['f1.txt'], deprecated_field=[])", + } + ) + transitive_targets_rule_runner.get_target( + Address("", target_name="t", relative_file_path="f1.txt") + ) + assert len(caplog.records) == 2 + assert "Instead, use `sources`" in caplog.text + assert "Instead, use `dependencies`" in caplog.text + + def test_resolve_deprecated_target_name(transitive_targets_rule_runner: RuleRunner, caplog) -> None: transitive_targets_rule_runner.write_files({"BUILD": "deprecated_target(name='t')"}) transitive_targets_rule_runner.get_target(Address("", target_name="t"))
Deprecated fields not preserved for target generators **Describe the bug** When a target field has a deprecated alias, it is not propagated to the generated target when using the deprecated alias, nor is there a warning about using the deprecated name for the field. **Pants version** `main` **OS** Any **Additional info** As found by @krishnan-chandra and identified by @kaos in https://github.com/pantsbuild/pants/pull/20626#discussion_r1505851913
2024-02-28T14:26:30
pantsbuild/pants
20,633
pantsbuild__pants-20633
[ "20632" ]
c15e54e5c8100a7d8638589bc6f675a95e7c49e9
diff --git a/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py b/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py --- a/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py +++ b/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py @@ -28,7 +28,22 @@ class ParsedDockerfileInfo: _address_regexp = re.compile( r""" - (?://)?[^:# ]*:[^:#!@?/\= ]+(?:\#[^:#!@?= ]+)?$ + # Optionally root:ed. + (?://)? + # Optional path. + [^:# ]* + # Optional target name. + (?::[^:#!@?/\= ]+)? + # Optional generated name. + (?:\#[^:#!@?= ]+)? + # Optional parametrizations. + (?:@ + # key=value + [^=: ]+=[^,: ]* + # Optional additional `,key=value`s + (?:,[^=: ]+=[^,: ]*)* + )? + $ """, re.VERBOSE, )
diff --git a/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py b/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py --- a/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py +++ b/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py @@ -206,3 +206,39 @@ def test_generate_lockfile_without_python_backend() -> None: "--resolve=dockerfile-parser", ] ).assert_success() + + +def test_baseimage_dep_inference(rule_runner: RuleRunner) -> None: + # We use a single run to grab all information, rather than parametrizing the test to save on + # rule invocations. + base_image_tags = dict( + BASE_IMAGE_1=":sibling", + BASE_IMAGE_2=":sibling@a=42,b=c", + BASE_IMAGE_3="else/where:weird#name@with=param", + BASE_IMAGE_4="//src/common:name@parametrized=foo-bar.1", + BASE_IMAGE_5="should/allow/default-target-name", + ) + + rule_runner.write_files( + { + "test/BUILD": "docker_image()", + "test/Dockerfile": "\n".join( + dedent( + f"""\ + ARG {arg}="{tag}" + FROM ${arg} + """ + ) + for arg, tag in base_image_tags.items() + ) + + dedent( + """\ + ARG DECOY="this is not a target address" + FROM $DECOY + """ + ), + } + ) + addr = Address("test") + info = rule_runner.request(DockerfileInfo, [DockerfileInfoRequest(addr)]) + assert info.from_image_build_args.to_dict() == base_image_tags
Docker: base image build arg detection does not support parametrized targets **Describe the bug** If the base image is parametrized, the dependency inference does not pick it up. **Pants version** `2.19.0` **OS** Any. **Additional info** [Reported](https://chat.pantsbuild.org/t/16633559/i-have-a-structure-where-i-have-a-set-of-containers-that-are#0e224a89-4839-45a4-91c5-bd9c8fa88c27) by @rbuckland
2024-03-01T10:49:46
pantsbuild/pants
20,638
pantsbuild__pants-20638
[ "20591" ]
af1b5c7cc6f8f539be353b5f950c9d4c36a49138
diff --git a/src/python/pants/backend/python/lint/black/rules.py b/src/python/pants/backend/python/lint/black/rules.py --- a/src/python/pants/backend/python/lint/black/rules.py +++ b/src/python/pants/backend/python/lint/black/rules.py @@ -57,6 +57,10 @@ async def _run_black( ), input_digest=input_digest, output_files=request.files, + # Note - the cache directory is not used by Pants, + # and we pass through a temporary directory to neutralize + # Black's caching behavior in favor of Pants' caching. + extra_env={"BLACK_CACHE_DIR": "__pants_black_cache"}, concurrency_available=len(request.files), description=f"Run Black on {pluralize(len(request.files), 'file')}.", level=LogLevel.DEBUG,
Black writes to shared `$XDG_CACHE_DIR/black` cache directory **Describe the bug** Black has its own global caching mechanism, to avoid reformatting files that have already been formatted. - https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#black-cache-dir - https://black.readthedocs.io/en/stable/usage_and_configuration/file_collection_and_discovery.html#ignoring-unmodified-files Pants doesn't currently seem to consider this, it seems like we should either: 1. explicitly support Black writing to a global one, by passing through the `XDG_CACHE_DIR` and/or `BLACK_CACHE_DIR` env vars automatically(?) 2. writing it to a Pants-managed named/append-only cache 3. disabling it entirely, and just rely on Pants' process level caching Reproducer: ```shell cd $(mktemp -d) default_cache_dir=~/Library/Caches/black # or ~/.cache/black, or something else # WARNING: this is mutates your disk! Check before running clear_global_cache() { echo "clearing '$default_cache_dir'" rm -rf "$default_cache_dir" } cat > pants.toml <<EOF [GLOBAL] pants_version = "2.19.0" backend_packages = [ "pants.backend.python", "pants.backend.python.lint.black", ] [python] interpreter_constraints = ["==3.*"] EOF echo 'python_sources(name="src")' > BUILD echo 'a' > file.py # This bug relates to when black is actually executed, so let's get the Pants caches out of the way export PANTS_PANTSD=false PANTS_LOCAL_CACHE=false # BUG 1: writes to cache with default settings clear_global_cache pants fmt :: tree "$default_cache_dir" # BUG 2: writes to cache even with (attempted) override tmp_cache_dir="temp-cache" clear_global_cache BLACK_CACHE_DIR="$tmp_cache_dir" pants fmt :: tree "$default_cache_dir" tree "$tmp_cache_dir" ``` This sets up pants to run black in two configurations, starting with an empty global/default black cache each time. In both configurations, that global cache is written to: 1. default settings 2. with an explicit override via `BLACK_CACHE_DIR` **Pants version** 2.19.0 **OS** macOS **Additional info** N/A
This cache seems to use a few "all-encompassing" pickle files, that get loaded and then updated with any new files (see https://black.readthedocs.io/en/stable/usage_and_configuration/file_collection_and_discovery.html#ignoring-unmodified-files)... it appears that the writes after an update are at least (attempted) to be done atomically (https://github.com/psf/black/blob/d1d4fc58d3b744db35ac832cddf1d076ba5f5e7f/src/black/cache.py#L138-L148). I think this likely means that concurrent executions: - may overwriting on each other's updates - won't totally corrupt the file itself (For instance: process A formats `a.py` and adds that to the pickle, while B formats `b.py` and adds that to the pickle. Depending on the order of the reads and writes, the resulting file will still be a sensible pickle, without torn writes or other corruption, but might have info on `a.py` and not `b.py`, `b.py` and not `a.py`, or both.) Given Pants' caching, I'd be inclined to disable the cache entirely. It doesn't look like there's an option for this, but we could always set `BLACK_CACHE_DIR` to point to a local path within the sandbox, that isn't persisted after execution. Thoughts? I'm happy to take this on - and I agree that the best option is probably to disable/neutralize Black's caching since it might conflict with Pants and we have a potential race condition when Black is run in parallel.
2024-03-04T03:14:48
pantsbuild/pants
20,649
pantsbuild__pants-20649
[ "20595" ]
65de37e3d9ada721e38b079188de57e8cce241ba
diff --git a/src/python/pants/engine/internals/graph.py b/src/python/pants/engine/internals/graph.py --- a/src/python/pants/engine/internals/graph.py +++ b/src/python/pants/engine/internals/graph.py @@ -27,7 +27,8 @@ from pants.engine.environment import ChosenLocalEnvironmentName, EnvironmentName from pants.engine.fs import EMPTY_SNAPSHOT, GlobMatchErrorBehavior, PathGlobs, Paths, Snapshot from pants.engine.internals import native_engine -from pants.engine.internals.mapper import AddressFamilies +from pants.engine.internals.build_files import AddressFamilyDir +from pants.engine.internals.mapper import AddressFamilies, AddressFamily from pants.engine.internals.native_engine import AddressParseException from pants.engine.internals.parametrize import Parametrize, _TargetParametrization from pants.engine.internals.parametrize import ( # noqa: F401 @@ -255,6 +256,91 @@ async def resolve_all_generator_target_requests( ) +async def _parametrized_target_generators_with_templates( + address: Address, + target_adaptor: TargetAdaptor, + target_type: type[TargetGenerator], + generator_fields: dict[str, Any], + union_membership: UnionMembership, +) -> list[tuple[TargetGenerator, dict[str, Any]]]: + # Pre-load field values from defaults for the target type being generated. + if hasattr(target_type, "generated_target_cls"): + family = await Get(AddressFamily, AddressFamilyDir(address.spec_path)) + template_fields = dict(family.defaults.get(target_type.generated_target_cls.alias, {})) + else: + template_fields = {} + + # Split out the `propagated_fields` before construction. + copied_fields = ( + *target_type.copied_fields, + *target_type._find_copied_plugin_fields(union_membership), + ) + moved_fields = ( + *target_type.moved_fields, + *target_type._find_moved_plugin_fields(union_membership), + ) + for field_type in copied_fields: + for alias in (field_type.deprecated_alias, field_type.alias): + if alias is None: + continue + # Any deprecated field use will be checked on the generator target. + field_value = generator_fields.get(alias, None) + if field_value is not None: + template_fields[alias] = field_value + for field_type in moved_fields: + # We must check for deprecated field usage here before passing the value to the generator. + if field_type.deprecated_alias is not None: + field_value = generator_fields.pop(field_type.deprecated_alias, None) + if field_value is not None: + warn_deprecated_field_type(field_type) + template_fields[field_type.deprecated_alias] = field_value + field_value = generator_fields.pop(field_type.alias, None) + if field_value is not None: + template_fields[field_type.alias] = field_value + + # Move parametrize groups over to `template_fields` in order to expand them. + parametrize_group_field_names = [ + name + for name, field in generator_fields.items() + if isinstance(field, Parametrize) and field.is_group + ] + for field_name in parametrize_group_field_names: + template_fields[field_name] = generator_fields.pop(field_name) + + field_type_aliases = target_type._get_field_aliases_to_field_types( + target_type.class_field_types(union_membership) + ).keys() + generator_fields_parametrized = { + name + for name, field in generator_fields.items() + if isinstance(field, Parametrize) and name in field_type_aliases + } + if generator_fields_parametrized: + noun = pluralize(len(generator_fields_parametrized), "field", include_count=False) + generator_fields_parametrized_text = ", ".join( + repr(f) for f in generator_fields_parametrized + ) + raise InvalidFieldException( + f"Only fields which will be moved to generated targets may be parametrized, " + f"so target generator {address} (with type {target_type.alias}) cannot " + f"parametrize the {generator_fields_parametrized_text} {noun}." + ) + return [ + ( + _create_target( + address, + target_type, + target_adaptor, + generator_fields, + union_membership, + name_explicitly_set=target_adaptor.name is not None, + ), + template, + ) + for address, template in Parametrize.expand(address, template_fields) + ] + + async def _target_generator_overrides( target_generator: TargetGenerator, unmatched_build_file_globs: UnmatchedBuildFileGlobs ) -> dict[str, dict[str, Any]]: @@ -296,7 +382,7 @@ async def resolve_generator_target_requests( if not generate_request: return ResolvedTargetGeneratorRequests() generator_fields = dict(target_adaptor.kwargs) - generators = _parametrized_target_generators_with_templates( + generators = await _parametrized_target_generators_with_templates( req.address, target_adaptor, target_type, @@ -428,85 +514,6 @@ def _target_parametrizations( return _TargetParametrization(target, FrozenDict()) -def _parametrized_target_generators_with_templates( - address: Address, - target_adaptor: TargetAdaptor, - target_type: type[TargetGenerator], - generator_fields: dict[str, Any], - union_membership: UnionMembership, -) -> list[tuple[TargetGenerator, dict[str, Any]]]: - # Split out the `propagated_fields` before construction. - template_fields = {} - copied_fields = ( - *target_type.copied_fields, - *target_type._find_copied_plugin_fields(union_membership), - ) - moved_fields = ( - *target_type.moved_fields, - *target_type._find_moved_plugin_fields(union_membership), - ) - for field_type in copied_fields: - for alias in (field_type.deprecated_alias, field_type.alias): - if alias is None: - continue - # Any deprecated field use will be checked on the generator target. - field_value = generator_fields.get(alias, None) - if field_value is not None: - template_fields[alias] = field_value - for field_type in moved_fields: - # We must check for deprecated field usage here before passing the value to the generator. - if field_type.deprecated_alias is not None: - field_value = generator_fields.pop(field_type.deprecated_alias, None) - if field_value is not None: - warn_deprecated_field_type(field_type) - template_fields[field_type.deprecated_alias] = field_value - field_value = generator_fields.pop(field_type.alias, None) - if field_value is not None: - template_fields[field_type.alias] = field_value - - # Move parametrize groups over to `template_fields` in order to expand them. - parametrize_group_field_names = [ - name - for name, field in generator_fields.items() - if isinstance(field, Parametrize) and field.is_group - ] - for field_name in parametrize_group_field_names: - template_fields[field_name] = generator_fields.pop(field_name) - - field_type_aliases = target_type._get_field_aliases_to_field_types( - target_type.class_field_types(union_membership) - ).keys() - generator_fields_parametrized = { - name - for name, field in generator_fields.items() - if isinstance(field, Parametrize) and name in field_type_aliases - } - if generator_fields_parametrized: - noun = pluralize(len(generator_fields_parametrized), "field", include_count=False) - generator_fields_parametrized_text = ", ".join( - repr(f) for f in generator_fields_parametrized - ) - raise InvalidFieldException( - f"Only fields which will be moved to generated targets may be parametrized, " - f"so target generator {address} (with type {target_type.alias}) cannot " - f"parametrize the {generator_fields_parametrized_text} {noun}." - ) - return [ - ( - _create_target( - address, - target_type, - target_adaptor, - generator_fields, - union_membership, - name_explicitly_set=target_adaptor.name is not None, - ), - template, - ) - for address, template in Parametrize.expand(address, template_fields) - ] - - @rule(_masked_types=[EnvironmentName]) async def resolve_target( request: WrappedTargetRequest, diff --git a/src/python/pants/engine/target.py b/src/python/pants/engine/target.py --- a/src/python/pants/engine/target.py +++ b/src/python/pants/engine/target.py @@ -1015,6 +1015,13 @@ class TargetGenerator(Target): """ # The generated Target class. + # + # If this is not provided, consider checking for the default values that applies to the target + # types being generated manually. The applicable defaults are available on the `AddressFamily` + # which you can get using: + # + # family = await Get(AddressFamily, AddressFamilyDir(address.spec_path)) + # target_defaults = family.defaults.get(MyTarget.alias, {}) generated_target_cls: ClassVar[type[Target]] # Fields which have their values copied from the generator Target to the generated Target.
diff --git a/src/python/pants/engine/internals/build_files_test.py b/src/python/pants/engine/internals/build_files_test.py --- a/src/python/pants/engine/internals/build_files_test.py +++ b/src/python/pants/engine/internals/build_files_test.py @@ -40,10 +40,13 @@ from pants.engine.target import ( Dependencies, MultipleSourcesField, + OverridesField, RegisteredTargetTypes, + SingleSourceField, StringField, Tags, Target, + TargetFilesGenerator, ) from pants.engine.unions import UnionMembership from pants.init.bootstrap_scheduler import BootstrapStatus @@ -357,6 +360,23 @@ class MockTgt(Target): core_fields = (MockDepsField, MockMultipleSourcesField, Tags, ResolveField) +class MockSingleSourceField(SingleSourceField): + pass + + +class MockGeneratedTarget(Target): + alias = "generated" + core_fields = (MockDepsField, Tags, MockSingleSourceField, ResolveField) + + +class MockTargetGenerator(TargetFilesGenerator): + alias = "generator" + core_fields = (MockMultipleSourcesField, OverridesField) + generated_target_cls = MockGeneratedTarget + copied_fields = () + moved_fields = (MockDepsField, Tags, ResolveField) + + def test_resolve_address() -> None: rule_runner = RuleRunner( rules=[QueryRule(Address, [AddressInput]), QueryRule(MaybeAddress, [AddressInput])] @@ -407,7 +427,7 @@ def assert_is_expected(address_input: AddressInput, expected: Address) -> None: def target_adaptor_rule_runner() -> RuleRunner: return RuleRunner( rules=[QueryRule(TargetAdaptor, (TargetAdaptorRequest,))], - target_types=[MockTgt], + target_types=[MockTgt, MockGeneratedTarget, MockTargetGenerator], objects={"parametrize": Parametrize}, ) @@ -500,6 +520,35 @@ def test_target_adaptor_defaults_applied(target_adaptor_rule_runner: RuleRunner) assert target_adaptor.kwargs["tags"] == ["24"] +def test_generated_target_defaults(target_adaptor_rule_runner: RuleRunner) -> None: + target_adaptor_rule_runner.write_files( + { + "BUILD": dedent( + """\ + __defaults__({generated: dict(resolve="mock")}, all=dict(tags=["24"])) + generated(name="explicit", tags=["42"], source="e.txt") + generator(name='gen', sources=["g*.txt"]) + """ + ), + "e.txt": "", + "g1.txt": "", + "g2.txt": "", + } + ) + + explicit_target = target_adaptor_rule_runner.get_target(Address("", target_name="explicit")) + assert explicit_target.address.target_name == "explicit" + assert explicit_target.get(ResolveField).value == "mock" + assert explicit_target.get(Tags).value == ("42",) + + implicit_target = target_adaptor_rule_runner.get_target( + Address("", target_name="gen", relative_file_path="g1.txt") + ) + assert str(implicit_target.address) == "//g1.txt:gen" + assert implicit_target.get(ResolveField).value == "mock" + assert implicit_target.get(Tags).value == ("24",) + + def test_inherit_defaults(target_adaptor_rule_runner: RuleRunner) -> None: target_adaptor_rule_runner.write_files( {
`__defaults__` should apply also for generated targets **Describe the bug** ```python # BUILD __defaults__({python_source: dict(...)}) python_sources() ``` The `python_sources` target will generate a `python_source` target for each source file, but none of them will apply the specified default field values from the `__defaults__` declaration. (This is why we see/suggest using patterns like `__defaults__({(python_sources, python_source): ...})`.) **Pants version** `main` **OS** Any **Additional info** This is due to the `__defaults__` being applied to the `TargetAdaptor` during BUILD file parsing only, so the defaults in this case would have to target the `python_sources` generator, and not the generated targets to apply. This is not very intuitive and should be fixed. One possible idea is to have pants provide the applicable defaults when calling the generator, and it will be up to the generator to apply those defaults to the targets it creates, as it deems fit.
2024-03-07T09:33:40
pantsbuild/pants
20,653
pantsbuild__pants-20653
[ "20651" ]
413277cf3315306f3b2eec2cd3763c8c3c985cc3
diff --git a/src/python/pants/backend/python/util_rules/pex_cli.py b/src/python/pants/backend/python/util_rules/pex_cli.py --- a/src/python/pants/backend/python/util_rules/pex_cli.py +++ b/src/python/pants/backend/python/util_rules/pex_cli.py @@ -35,8 +35,8 @@ class PexCli(TemplatedExternalTool): name = "pex" help = "The PEX (Python EXecutable) tool (https://github.com/pantsbuild/pex)." - default_version = "v2.1.148" - default_url_template = "https://github.com/pantsbuild/pex/releases/download/{version}/pex" + default_version = "v2.2.1" + default_url_template = "https://github.com/pex-tool/pex/releases/download/{version}/pex" version_constraints = ">=2.1.135,<3.0" @classproperty @@ -46,8 +46,8 @@ def default_known_versions(cls): ( cls.default_version, plat, - "5b1dee5a89fff25747753e917f96b8707ea62eed404d037d5f8cf8f2e80a13b7", - "4197604", + "e38e7052282f1855606880333a8f8c8a09458fabc5b5e5fb6c48ce11a4564a34", + "4113219", ) ) for plat in ["macos_arm64", "macos_x86_64", "linux_x86_64", "linux_arm64"]
Backport #20587 to 2.19.x to fix `Exec format error` when running Pants on Linux **Describe the bug** When running the command `pants` several of my coworkers have ran into `Exec format error`. This is because the shebang in the `nce/path/.../bin/pants` is longer than the 128 character limit imposed by linux and gets cutoff. The 2.1.154 release of Pex includes a work around for this. However Pants 2.19.x currently uses [v2.1.148](https://github.com/pantsbuild/pants/blob/2.19.x/src/python/pants/backend/python/util_rules/pex_cli.py#L38). During the `Pants Build Pex` step of the release, Pants packages itself as a pex, however it uses pex v2.1.148. This produces potentially broken Pants Pexs on linux if your home directory is sufficiently long. I believe if we cherry picked the work done in #20587 it would solve the problem. **Pants version** 2.19 **OS** Both **Additional info**
2024-03-07T21:29:22
pantsbuild/pants
20,657
pantsbuild__pants-20657
[ "20632" ]
636003afb9dd082ee824990a0605f31c6549f7d5
diff --git a/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py b/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py --- a/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py +++ b/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py @@ -28,7 +28,22 @@ class ParsedDockerfileInfo: _address_regexp = re.compile( r""" - (?://)?[^:# ]*:[^:#!@?/\= ]+(?:\#[^:#!@?= ]+)?$ + # Optionally root:ed. + (?://)? + # Optional path. + [^:# ]* + # Optional target name. + (?::[^:#!@?/\= ]+)? + # Optional generated name. + (?:\#[^:#!@?= ]+)? + # Optional parametrizations. + (?:@ + # key=value + [^=: ]+=[^,: ]* + # Optional additional `,key=value`s + (?:,[^=: ]+=[^,: ]*)* + )? + $ """, re.VERBOSE, )
diff --git a/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py b/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py --- a/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py +++ b/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py @@ -206,3 +206,39 @@ def test_generate_lockfile_without_python_backend() -> None: "--resolve=dockerfile-parser", ] ).assert_success() + + +def test_baseimage_dep_inference(rule_runner: RuleRunner) -> None: + # We use a single run to grab all information, rather than parametrizing the test to save on + # rule invocations. + base_image_tags = dict( + BASE_IMAGE_1=":sibling", + BASE_IMAGE_2=":sibling@a=42,b=c", + BASE_IMAGE_3="else/where:weird#name@with=param", + BASE_IMAGE_4="//src/common:name@parametrized=foo-bar.1", + BASE_IMAGE_5="should/allow/default-target-name", + ) + + rule_runner.write_files( + { + "test/BUILD": "docker_image()", + "test/Dockerfile": "\n".join( + dedent( + f"""\ + ARG {arg}="{tag}" + FROM ${arg} + """ + ) + for arg, tag in base_image_tags.items() + ) + + dedent( + """\ + ARG DECOY="this is not a target address" + FROM $DECOY + """ + ), + } + ) + addr = Address("test") + info = rule_runner.request(DockerfileInfo, [DockerfileInfoRequest(addr)]) + assert info.from_image_build_args.to_dict() == base_image_tags
Docker: base image build arg detection does not support parametrized targets **Describe the bug** If the base image is parametrized, the dependency inference does not pick it up. **Pants version** `2.19.0` **OS** Any. **Additional info** [Reported](https://chat.pantsbuild.org/t/16633559/i-have-a-structure-where-i-have-a-set-of-containers-that-are#0e224a89-4839-45a4-91c5-bd9c8fa88c27) by @rbuckland
2024-03-08T08:48:50
pantsbuild/pants
20,658
pantsbuild__pants-20658
[ "20632" ]
3299a321a79e2a6b0a1db27b0d101deaf854f7d2
diff --git a/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py b/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py --- a/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py +++ b/src/python/pants/backend/docker/subsystems/dockerfile_wrapper_script.py @@ -28,7 +28,22 @@ class ParsedDockerfileInfo: _address_regexp = re.compile( r""" - (?://)?[^:# ]*:[^:#!@?/\= ]+(?:\#[^:#!@?= ]+)?$ + # Optionally root:ed. + (?://)? + # Optional path. + [^:# ]* + # Optional target name. + (?::[^:#!@?/\= ]+)? + # Optional generated name. + (?:\#[^:#!@?= ]+)? + # Optional parametrizations. + (?:@ + # key=value + [^=: ]+=[^,: ]* + # Optional additional `,key=value`s + (?:,[^=: ]+=[^,: ]*)* + )? + $ """, re.VERBOSE, )
diff --git a/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py b/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py --- a/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py +++ b/src/python/pants/backend/docker/subsystems/dockerfile_parser_test.py @@ -206,3 +206,39 @@ def test_generate_lockfile_without_python_backend() -> None: "--resolve=dockerfile-parser", ] ).assert_success() + + +def test_baseimage_dep_inference(rule_runner: RuleRunner) -> None: + # We use a single run to grab all information, rather than parametrizing the test to save on + # rule invocations. + base_image_tags = dict( + BASE_IMAGE_1=":sibling", + BASE_IMAGE_2=":sibling@a=42,b=c", + BASE_IMAGE_3="else/where:weird#name@with=param", + BASE_IMAGE_4="//src/common:name@parametrized=foo-bar.1", + BASE_IMAGE_5="should/allow/default-target-name", + ) + + rule_runner.write_files( + { + "test/BUILD": "docker_image()", + "test/Dockerfile": "\n".join( + dedent( + f"""\ + ARG {arg}="{tag}" + FROM ${arg} + """ + ) + for arg, tag in base_image_tags.items() + ) + + dedent( + """\ + ARG DECOY="this is not a target address" + FROM $DECOY + """ + ), + } + ) + addr = Address("test") + info = rule_runner.request(DockerfileInfo, [DockerfileInfoRequest(addr)]) + assert info.from_image_build_args.to_dict() == base_image_tags
Docker: base image build arg detection does not support parametrized targets **Describe the bug** If the base image is parametrized, the dependency inference does not pick it up. **Pants version** `2.19.0` **OS** Any. **Additional info** [Reported](https://chat.pantsbuild.org/t/16633559/i-have-a-structure-where-i-have-a-set-of-containers-that-are#0e224a89-4839-45a4-91c5-bd9c8fa88c27) by @rbuckland
2024-03-08T08:48:53
pantsbuild/pants
20,670
pantsbuild__pants-20670
[ "15062" ]
668f024c3c8d42c0e1731dfe1b18f8609d5afe48
diff --git a/src/python/pants/backend/python/util_rules/pex.py b/src/python/pants/backend/python/util_rules/pex.py --- a/src/python/pants/backend/python/util_rules/pex.py +++ b/src/python/pants/backend/python/util_rules/pex.py @@ -705,6 +705,12 @@ async def build_pex( if request.pex_path: argv.extend(["--pex-path", ":".join(pex.name for pex in request.pex_path)]) + if request.internal_only: + # An internal-only runs on a single machine, and pre-installing wheels is wasted work in + # that case (see https://github.com/pex-tool/pex/issues/2292#issuecomment-1854582647 for + # analysis). + argv.append("--no-pre-install-wheels") + argv.append(f"--sources-directory={source_dir_name}") sources_digest_as_subdir = await Get( Digest, AddPrefix(request.sources or EMPTY_DIGEST, source_dir_name) @@ -1157,6 +1163,9 @@ async def setup_pex_process(request: PexProcess, pex_environment: PexEnvironment complete_pex_env = pex_environment.in_sandbox(working_directory=request.working_directory) argv = complete_pex_env.create_argv(pex.name, *request.argv) env = { + # Set this in case this PEX was built with --no-pre-install-wheels, and thus parallelising + # the install on cold boot is handy. + "PEX_MAX_INSTALL_JOBS": str(request.concurrency_available), **complete_pex_env.environment_dict(python=pex.python), **request.extra_env, } @@ -1196,7 +1205,7 @@ class VenvPexProcess: level: LogLevel input_digest: Digest | None working_directory: str | None - extra_env: FrozenDict[str, str] | None + extra_env: FrozenDict[str, str] output_files: tuple[str, ...] | None output_directories: tuple[str, ...] | None timeout_seconds: int | None @@ -1229,7 +1238,7 @@ def __init__( object.__setattr__(self, "level", level) object.__setattr__(self, "input_digest", input_digest) object.__setattr__(self, "working_directory", working_directory) - object.__setattr__(self, "extra_env", FrozenDict(extra_env) if extra_env else None) + object.__setattr__(self, "extra_env", FrozenDict(extra_env or {})) object.__setattr__(self, "output_files", tuple(output_files) if output_files else None) object.__setattr__( self, "output_directories", tuple(output_directories) if output_directories else None @@ -1252,6 +1261,12 @@ async def setup_venv_pex_process( else venv_pex.pex.argv0 ) argv = (pex_bin, *request.argv) + env = { + # Set this in case this PEX was built with --no-pre-install-wheels, and thus parallelising + # the install on cold boot is handy. + "PEX_MAX_INSTALL_JOBS": str(request.concurrency_available), + **request.extra_env, + } input_digest = ( await Get(Digest, MergeDigests((venv_pex.digest, request.input_digest))) if request.input_digest @@ -1270,7 +1285,7 @@ async def setup_venv_pex_process( level=request.level, input_digest=input_digest, working_directory=request.working_directory, - env=request.extra_env, + env=env, output_files=request.output_files, output_directories=request.output_directories, append_only_caches=append_only_caches, diff --git a/src/python/pants/backend/python/util_rules/pex_cli.py b/src/python/pants/backend/python/util_rules/pex_cli.py --- a/src/python/pants/backend/python/util_rules/pex_cli.py +++ b/src/python/pants/backend/python/util_rules/pex_cli.py @@ -40,7 +40,7 @@ class PexCli(TemplatedExternalTool): default_version = "v2.3.0" default_url_template = "https://github.com/pex-tool/pex/releases/download/{version}/pex" - version_constraints = ">=2.1.161,<3.0" + version_constraints = ">=2.3.0,<3.0" @classproperty def default_known_versions(cls):
diff --git a/src/python/pants/backend/python/goals/publish_test.py b/src/python/pants/backend/python/goals/publish_test.py --- a/src/python/pants/backend/python/goals/publish_test.py +++ b/src/python/pants/backend/python/goals/publish_test.py @@ -136,7 +136,13 @@ def test_twine_upload(rule_runner, packages) -> None: "my-package-0.1.0.tar.gz", "my_package-0.1.0-py3-none-any.whl", ), - env=FrozenDict({"TWINE_USERNAME": "whoareyou", "TWINE_PASSWORD": "secret"}), + env=FrozenDict( + { + "TWINE_USERNAME": "whoareyou", + "TWINE_PASSWORD": "secret", + "PEX_MAX_INSTALL_JOBS": "0", + } + ), ), ) assert_package( @@ -156,7 +162,7 @@ def test_twine_upload(rule_runner, packages) -> None: "my-package-0.1.0.tar.gz", "my_package-0.1.0-py3-none-any.whl", ), - env=FrozenDict({"TWINE_USERNAME": "whoami"}), + env=FrozenDict({"TWINE_USERNAME": "whoami", "PEX_MAX_INSTALL_JOBS": "0"}), ), )
Benchmark various defaults for PEX compression for internal PEXes Pants uses lots of PEXes "internally", which are never exported for users to consume. Since these are implementation details, we have free-rein to choose an internal-default [PEX compression level](https://github.com/pantsbuild/pex/pull/1705)... and some values can make a considerable difference in performance. To experiment/adjust for "internal only", logic similar to the logic for PEX's `layout` setting could be added, which set a default compression value for internal use: https://github.com/pantsbuild/pants/blob/902d3acb84c1b64c53c05e882200e4d578884c03/src/python/pants/backend/python/util_rules/pex.py#L196-L198
Are there internal PEX that aren't `PACKED` (grepping for `layout=`, `PexLayout.` and `internal_only=` suggests no)? If all of them are packed, will lowering the compression level do anything? Yes. A packed layout consists of N + 1 zips. 1 PEX `.bootstrap` code zip and 1 per installed wheel contained in the PEX under `.deps/`. By default these N+1 are compressed, but turning off compression turns off their compression just as it does for a single zip zipapp layout. Has anyone tried seeing whether PEX files might start up a little faster too if they're uncompressed? All PEX files are ~uncompressed (unzipped). Whether `--venv` or normal (zipapp), and regardless of `--layout`, A PEX file is extracted in one way or another on 1st run and forever more just re-directs to the extracted location. The re-direct overhead is ~O(50ms) except when using `--sh-boot` which takes it down to ~1ms. Oh yes! Thanks! To underscore - the benchmark here is about PEX creation time then, not run time. With https://github.com/pantsbuild/pex/releases/tag/v2.1.154, potentially we could be considering using `--no-pre-install-wheels` for internal PEXes, and maybe `--max-install-jobs`. Quoting https://github.com/pantsbuild/pex/issues/2292#issuecomment-1854582647, for perf results with PyTorch (i.e. large): Status quo | With --no-pre-install-wheels | --no-pre-install-wheels | savings -- | -- | -- | -- Cold build and run 1st local machine | 188.51s | 29.80s | 84% faster Cold run 1st remote machine | 26.74s | 29.60s | 11% slower Cold run 1st remote machine parallel | 12.79s | 14.06s | 10% slower Size (bytes) | 2679282217 | 2678537958 | 0.02% smaller (#20347 updates to pex 2.1.155 by default, but doesn't touch `version_constraints`, so if we actually start using that flag internally we'll need to either bump the constraints or make it conditional on version.)
2024-03-14T10:47:12
pantsbuild/pants
20,715
pantsbuild__pants-20715
[ "20703" ]
a84f5e0b0572c9fa3d21bef7e7ff8281fbb16f2d
diff --git a/src/python/pants/core/goals/export.py b/src/python/pants/core/goals/export.py --- a/src/python/pants/core/goals/export.py +++ b/src/python/pants/core/goals/export.py @@ -110,7 +110,9 @@ class ExportSubsystem(GoalSubsystem): Export Pants data for use in other tools, such as IDEs. :::caution Exporting tools requires creating a custom lockfile for them + Follow [the instructions for creating tool lockfiles](../../docs/python/overview/lockfiles#lockfiles-for-tools) + ::: """ )
"export" goal docs have unclosed call out **Describe the bug** The warning callout about "exporting tools requires ..." seems to be unclosed: - https://www.pantsbuild.org/2.18/reference/goals/export - https://www.pantsbuild.org/2.19/reference/goals/export - https://www.pantsbuild.org/2.20/reference/goals/export ![image](https://github.com/pantsbuild/pants/assets/1203825/5cfc04ee-27a7-49ba-a695-80d601aeace6) **Pants version** 2.18 onwards **OS** macOS **Additional info** Introduced in #20604
2024-03-24T06:04:40
pantsbuild/pants
20,716
pantsbuild__pants-20716
[ "20704" ]
a84f5e0b0572c9fa3d21bef7e7ff8281fbb16f2d
diff --git a/src/python/pants/backend/python/util_rules/pex_environment.py b/src/python/pants/backend/python/util_rules/pex_environment.py --- a/src/python/pants/backend/python/util_rules/pex_environment.py +++ b/src/python/pants/backend/python/util_rules/pex_environment.py @@ -89,8 +89,8 @@ def iter_path_entries(): Note: Pants uses Pex internally in some ways that trigger some warnings at the moment, so enabling this may result in warnings not related to your code. See - <https://github.com/pantsbuild/pants/issues/20577> and - <https://github.com/pantsbuild/pants/issues/20586>. + [#20577](https://github.com/pantsbuild/pants/issues/20577) and + [#20586](https://github.com/pantsbuild/pants/issues/20586). """ ), )
`[pex].emit_warnings` docs show `&#x3E;` literally instead of `>` **Describe the bug** https://www.pantsbuild.org/2.20/reference/subsystems/pex#emit_warnings ![image](https://github.com/pantsbuild/pants/assets/1203825/3c7f7152-3f56-4d74-9e49-fe5ad4d3e7ca) **Pants version** 2.20 **OS** N/A **Additional info**
2024-03-24T06:06:26
pantsbuild/pants
20,719
pantsbuild__pants-20719
[ "20703" ]
d58024787a7928e8f3f8dcc5f03d9afc0b90a19a
diff --git a/src/python/pants/core/goals/export.py b/src/python/pants/core/goals/export.py --- a/src/python/pants/core/goals/export.py +++ b/src/python/pants/core/goals/export.py @@ -110,7 +110,9 @@ class ExportSubsystem(GoalSubsystem): Export Pants data for use in other tools, such as IDEs. :::caution Exporting tools requires creating a custom lockfile for them + Follow [the instructions for creating tool lockfiles](../../docs/python/overview/lockfiles#lockfiles-for-tools) + ::: """ )
"export" goal docs have unclosed call out **Describe the bug** The warning callout about "exporting tools requires ..." seems to be unclosed: - https://www.pantsbuild.org/2.18/reference/goals/export - https://www.pantsbuild.org/2.19/reference/goals/export - https://www.pantsbuild.org/2.20/reference/goals/export ![image](https://github.com/pantsbuild/pants/assets/1203825/5cfc04ee-27a7-49ba-a695-80d601aeace6) **Pants version** 2.18 onwards **OS** macOS **Additional info** Introduced in #20604
2024-03-24T21:37:54
pantsbuild/pants
20,720
pantsbuild__pants-20720
[ "20703" ]
38bd40d919712aff392ef1f0d5a99f307ad6642b
diff --git a/src/python/pants/core/goals/export.py b/src/python/pants/core/goals/export.py --- a/src/python/pants/core/goals/export.py +++ b/src/python/pants/core/goals/export.py @@ -110,7 +110,9 @@ class ExportSubsystem(GoalSubsystem): Export Pants data for use in other tools, such as IDEs. :::caution Exporting tools requires creating a custom lockfile for them + Follow [the instructions for creating tool lockfiles](../../docs/python/overview/lockfiles#lockfiles-for-tools) + ::: """ )
"export" goal docs have unclosed call out **Describe the bug** The warning callout about "exporting tools requires ..." seems to be unclosed: - https://www.pantsbuild.org/2.18/reference/goals/export - https://www.pantsbuild.org/2.19/reference/goals/export - https://www.pantsbuild.org/2.20/reference/goals/export ![image](https://github.com/pantsbuild/pants/assets/1203825/5cfc04ee-27a7-49ba-a695-80d601aeace6) **Pants version** 2.18 onwards **OS** macOS **Additional info** Introduced in #20604
2024-03-24T21:37:56
pantsbuild/pants
20,721
pantsbuild__pants-20721
[ "20704" ]
38bd40d919712aff392ef1f0d5a99f307ad6642b
diff --git a/src/python/pants/backend/python/util_rules/pex_environment.py b/src/python/pants/backend/python/util_rules/pex_environment.py --- a/src/python/pants/backend/python/util_rules/pex_environment.py +++ b/src/python/pants/backend/python/util_rules/pex_environment.py @@ -89,8 +89,8 @@ def iter_path_entries(): Note: Pants uses Pex internally in some ways that trigger some warnings at the moment, so enabling this may result in warnings not related to your code. See - <https://github.com/pantsbuild/pants/issues/20577> and - <https://github.com/pantsbuild/pants/issues/20586>. + [#20577](https://github.com/pantsbuild/pants/issues/20577) and + [#20586](https://github.com/pantsbuild/pants/issues/20586). """ ), )
`[pex].emit_warnings` docs show `&#x3E;` literally instead of `>` **Describe the bug** https://www.pantsbuild.org/2.20/reference/subsystems/pex#emit_warnings ![image](https://github.com/pantsbuild/pants/assets/1203825/3c7f7152-3f56-4d74-9e49-fe5ad4d3e7ca) **Pants version** 2.20 **OS** N/A **Additional info**
2024-03-24T21:38:07
pantsbuild/pants
20,768
pantsbuild__pants-20768
[ "20739" ]
deb3014b23da8920a65be50239edecf744b55226
diff --git a/src/python/pants/engine/internals/parametrize.py b/src/python/pants/engine/internals/parametrize.py --- a/src/python/pants/engine/internals/parametrize.py +++ b/src/python/pants/engine/internals/parametrize.py @@ -427,12 +427,20 @@ def remaining_fields_match(candidate: Target) -> bool: ): return parametrization.original_target - # Else, see whether any of the generated targets match. - for candidate in parametrization.parametrization.values(): - if address.is_parametrized_subset_of(candidate.address) and remaining_fields_match( - candidate - ): - return candidate + consumer_parametrize_group = consumer.address.parameters.get("parametrize") + + def matching_parametrize_group(candidate: Target) -> bool: + return candidate.address.parameters.get("parametrize") == consumer_parametrize_group + + for candidate in sorted( + self.parametrizations.values(), key=matching_parametrize_group, reverse=True + ): + # Else, see whether any of the generated targets match, preferring a matching + # parametrize group when available. + if address.is_parametrized_subset_of(candidate.address) and remaining_fields_match( + candidate + ): + return candidate raise ValueError( f"The explicit dependency `{address}` of the target at `{consumer.address}` does "
diff --git a/src/python/pants/engine/internals/graph_test.py b/src/python/pants/engine/internals/graph_test.py --- a/src/python/pants/engine/internals/graph_test.py +++ b/src/python/pants/engine/internals/graph_test.py @@ -1657,6 +1657,55 @@ def test_parametrize_group_on_target_generator_20418( ) +def test_parametrize_explicit_dependencies_20739( + generated_targets_rule_runner: RuleRunner, +) -> None: + assert_generated( + generated_targets_rule_runner, + Address("demo", target_name="tst"), + dedent( + """\ + generator( + name='src', + sources=['src1.ext'], + **parametrize('b1', resolve='a'), + **parametrize('b2', resolve='b'), + ) + generator( + name='tst', + sources=['tst1.ext'], + dependencies=['./src1.ext:src'], + **parametrize('b1', resolve='a'), + **parametrize('b2', resolve='b'), + ) + """ + ), + ["src1.ext", "tst1.ext"], + expected_dependencies={ + "demo/src1.ext:src@parametrize=b1": set(), + "demo/src1.ext:src@parametrize=b2": set(), + "demo/tst1.ext:tst@parametrize=b1": { + "demo/src1.ext:src@parametrize=b1", + }, + "demo/tst1.ext:tst@parametrize=b2": { + "demo/src1.ext:src@parametrize=b2", + }, + "demo:src@parametrize=b1": { + "demo/src1.ext:src@parametrize=b1", + }, + "demo:src@parametrize=b2": { + "demo/src1.ext:src@parametrize=b2", + }, + "demo:tst@parametrize=b1": { + "demo/tst1.ext:tst@parametrize=b1", + }, + "demo:tst@parametrize=b2": { + "demo/tst1.ext:tst@parametrize=b2", + }, + }, + ) + + # ----------------------------------------------------------------------------------------------- # Test `SourcesField`. Also see `engine/target_test.py`. # -----------------------------------------------------------------------------------------------
Parametrized `python_tests` and `python_sources` in same package not lining up when using explicit `dependencies` **Describe the bug** I have a `python_source` target in the same directory as a `python_test` target. Both are parametrized for multiple resolves/environments/interpreter constraints. The `python_test` target in question does not import the `python_source` target but instead calls it via the `subprocess` module, so I have the `python_source` target as an explicit dependency of the `python_test` one. This is causing an error because the `python_test` target is grabbing the first parametrization as the dependency instead of the matching one. `pants peek` output below: ```json { "address": "my/python/tests/test_the_thing.py@parametrize=py311", "target_type": "python_test", "batch_compatibility_tag": null, "dependencies": [ "my/inferred_dep/__init__.py@parametrize=py311", "my/python/tests/__init__.py:sources_for_tests@parametrize=py38", "my/python/tests/source_for_test.py:sources_for_tests@parametrize=py38" ], "dependencies_raw": [ ":sources_for_tests" ], "description": null, "environment": "py311-test", "extra_env_vars": null, "interpreter_constraints": [ "==3.11.*" ], "resolve": "py311", "run_goal_use_sandbox": null, "runtime_package_dependencies": null, "skip_black": false, "skip_docformatter": false, "skip_isort": false, "skip_mypy": true, "skip_ruff": true, "skip_tests": false, "source_raw": "test_the_thing.py", "sources": [ "my/python/tests/test_the_thing.py" ], "sources_fingerprint": "b1274e36d37387cc0fca9f18cd77e456483663e6ac869ec1ecce9aaa502a8d83", "tags": null, "timeout": null, "xdist_concurrency": null } ``` **Pants version** 2.19.1 **OS** Intel Mac
Sorry for the trouble; can you create a reduced example as a demonstration? I understand the issue here.. will see if I can come up with a fix for it. @ndellosa95 Can you share the relevant parts of your BUILD files for this (redacted as needed), just to make sure I test the right thing? Thanks :) Or, if you can confirm that this test matches what you have.. ```python assert_generated( generated_targets_rule_runner, Address("demo", target_name="tst"), dedent( """\ generator( name='src', sources=['src1.ext'], **parametrize('b1', resolve='a'), **parametrize('b2', resolve='b'), ) generator( name='tst', sources=['tst1.ext'], dependencies=['./src1.ext:src'], **parametrize('b1', resolve='a'), **parametrize('b2', resolve='b'), ) """ ), ["src1.ext", "tst1.ext"], expected_dependencies={ "demo/src1.ext:src@parametrize=b1": set(), "demo/src1.ext:src@parametrize=b2": set(), "demo/tst1.ext:tst@parametrize=b1": { "demo/src1.ext:src@parametrize=b1", }, "demo/tst1.ext:tst@parametrize=b2": { "demo/src1.ext:src@parametrize=b2", }, "demo:src@parametrize=b1": { "demo/src1.ext:src@parametrize=b1", }, "demo:src@parametrize=b2": { "demo/src1.ext:src@parametrize=b2", }, "demo:tst@parametrize=b1": { "demo/tst1.ext:tsr@parametrize=b1", }, "demo:tst@parametrize=b2": { "demo/tst1.ext:tst@parametrize=b2", }, }, ) ``` which does fail with a missmatched parametrization for the explicitly provided dependency: ``` E 'demo/tst1.ext:tst@parametriz 'demo/tst1.ext:tst@parametriz E e=b2': set([ e=b2': set([ E 'demo/src1.ext:src@parametr 'demo/src1.ext:src@parametr E ize=b1', ize=b2', E ]), ]), ```
2024-04-08T11:29:21
pantsbuild/pants
20,769
pantsbuild__pants-20769
[ "20733" ]
deb3014b23da8920a65be50239edecf744b55226
diff --git a/src/python/pants/backend/visibility/rule_types.py b/src/python/pants/backend/visibility/rule_types.py --- a/src/python/pants/backend/visibility/rule_types.py +++ b/src/python/pants/backend/visibility/rule_types.py @@ -68,20 +68,25 @@ class VisibilityRule: @classmethod def parse( cls, - rule: str, + rule: str | dict, relpath: str, ) -> VisibilityRule: - if not isinstance(rule, str): - raise ValueError(f"expected a path pattern string but got: {rule!r}") - if rule.startswith("!"): - action = DependencyRuleAction.DENY - pattern = rule[1:] - elif rule.startswith("?"): - action = DependencyRuleAction.WARN - pattern = rule[1:] - else: - action = DependencyRuleAction.ALLOW + pattern: str | dict + if isinstance(rule, str): + if rule.startswith("!"): + action = DependencyRuleAction.DENY + pattern = rule[1:] + elif rule.startswith("?"): + action = DependencyRuleAction.WARN + pattern = rule[1:] + else: + action = DependencyRuleAction.ALLOW + pattern = rule + elif isinstance(rule, dict): + action = DependencyRuleAction(rule.get("action", "allow")) pattern = rule + else: + raise ValueError(f"invalid visibility rule: {rule!r}") return cls(action, TargetGlob.parse(pattern, relpath)) def match(self, address: Address, adaptor: TargetAdaptor, relpath: str) -> bool: @@ -153,7 +158,7 @@ def parse(cls, build_file: str, arg: Any) -> VisibilityRuleSet: relpath = os.path.dirname(build_file) try: selectors = cast("Iterator[str | dict]", flatten(arg[0], str, dict)) - rules = cast("Iterator[str]", flatten(arg[1:], str)) + rules = cast("Iterator[str | dict]", flatten(arg[1:], str, dict)) return cls( build_file, tuple(TargetGlob.parse(selector, relpath) for selector in selectors), @@ -173,8 +178,8 @@ def peek(self) -> tuple[str, ...]: return tuple(map(str, self.rules)) @staticmethod - def _noop_rule(rule: str) -> bool: - return not rule or rule.startswith("#") + def _noop_rule(rule: str | dict) -> bool: + return not rule or isinstance(rule, str) and rule.startswith("#") def match(self, address: Address, adaptor: TargetAdaptor, relpath: str) -> bool: return any(selector.match(address, adaptor, relpath) for selector in self.selectors)
diff --git a/src/python/pants/backend/visibility/rule_types_test.py b/src/python/pants/backend/visibility/rule_types_test.py --- a/src/python/pants/backend/visibility/rule_types_test.py +++ b/src/python/pants/backend/visibility/rule_types_test.py @@ -45,7 +45,7 @@ def parse_address(raw: str, description_of_origin: str = repr("test"), **kwargs) return parsed.dir_to_address() if "." not in raw else parsed.file_to_address() -def parse_rule(rule: str, relpath: str = "test/path") -> VisibilityRule: +def parse_rule(rule: str | dict, relpath: str = "test/path") -> VisibilityRule: return VisibilityRule.parse(rule, relpath) @@ -158,6 +158,7 @@ def test_flatten(expected, xs) -> None: (True, "<target>", "src/a", ""), (False, "<target>[src/b]", "src/a", ""), (False, "<file>", "src/a", ""), + (True, {"path": "src/a"}, "src/a", ""), ], ) def test_visibility_rule(expected: bool, spec: str, path: str, relpath: str) -> None: @@ -206,6 +207,23 @@ def test_visibility_rule(expected: bool, spec: str, path: str, relpath: str) -> ), ("<target>", "src/*", "src/a:lib"), ), + ( + VisibilityRuleSet( + build_file="test/path/BUILD", + selectors=(TargetGlob.parse("<target>", ""),), + rules=( + parse_rule("!src/*"), + parse_rule("?src/a:lib"), + parse_rule("(this, is, ok)"), + ), + ), + ( + "<target>", + {"action": "deny", "path": "src/*"}, + {"action": "warn", "path": "src/a", "name": "lib"}, + {"tags": ["this", "is", "ok"]}, + ), + ), ], ) def test_visibility_rule_set_parse(expected: VisibilityRuleSet, arg: Any) -> None:
Visibility rules doesn't support dict formated rules **Is your feature request related to a problem? Please describe.** The current visibility rules are splitted into `selectors` or `visibility rules`. As documented, selector can either be string glob or dictionnary with explicit attribute naming (eg. `{"tags": ["core"]}` or `(core)`). However, `visibility rules` documentation example are only glob strings. It appears that visibility rules also support attributes matching by using the special syntax `<type>[path](tag)`. Looking at the code, they actually share the same matching logic for parsing and comparaison. However the `__dependencies_rule__` function define `visibility rules` as `str`, therefor passing attribute dictionnary (`{"tags": ["core"]}`) is not supported. Is there any reason for this limitation? **Describe the solution you'd like** It seems to me that we could just accept `dict` for visibility rules and everything should work as expected.
Good observation. And no, there is no reason for this, merely (recent) legacy that it initially wasn't using the same but was refactored to streamline the parsing/processing of the patterns, so this is now possible.
2024-04-08T12:27:34
pantsbuild/pants
20,778
pantsbuild__pants-20778
[ "20739" ]
3b13b89d7a7119de1e47c4fc388d92b6b94ae0a3
diff --git a/src/python/pants/engine/internals/parametrize.py b/src/python/pants/engine/internals/parametrize.py --- a/src/python/pants/engine/internals/parametrize.py +++ b/src/python/pants/engine/internals/parametrize.py @@ -427,12 +427,20 @@ def remaining_fields_match(candidate: Target) -> bool: ): return parametrization.original_target - # Else, see whether any of the generated targets match. - for candidate in parametrization.parametrization.values(): - if address.is_parametrized_subset_of(candidate.address) and remaining_fields_match( - candidate - ): - return candidate + consumer_parametrize_group = consumer.address.parameters.get("parametrize") + + def matching_parametrize_group(candidate: Target) -> bool: + return candidate.address.parameters.get("parametrize") == consumer_parametrize_group + + for candidate in sorted( + self.parametrizations.values(), key=matching_parametrize_group, reverse=True + ): + # Else, see whether any of the generated targets match, preferring a matching + # parametrize group when available. + if address.is_parametrized_subset_of(candidate.address) and remaining_fields_match( + candidate + ): + return candidate raise ValueError( f"The explicit dependency `{address}` of the target at `{consumer.address}` does "
diff --git a/src/python/pants/engine/internals/graph_test.py b/src/python/pants/engine/internals/graph_test.py --- a/src/python/pants/engine/internals/graph_test.py +++ b/src/python/pants/engine/internals/graph_test.py @@ -1627,6 +1627,55 @@ def test_parametrize_group_on_target_generator_20418( ) +def test_parametrize_explicit_dependencies_20739( + generated_targets_rule_runner: RuleRunner, +) -> None: + assert_generated( + generated_targets_rule_runner, + Address("demo", target_name="tst"), + dedent( + """\ + generator( + name='src', + sources=['src1.ext'], + **parametrize('b1', resolve='a'), + **parametrize('b2', resolve='b'), + ) + generator( + name='tst', + sources=['tst1.ext'], + dependencies=['./src1.ext:src'], + **parametrize('b1', resolve='a'), + **parametrize('b2', resolve='b'), + ) + """ + ), + ["src1.ext", "tst1.ext"], + expected_dependencies={ + "demo/src1.ext:src@parametrize=b1": set(), + "demo/src1.ext:src@parametrize=b2": set(), + "demo/tst1.ext:tst@parametrize=b1": { + "demo/src1.ext:src@parametrize=b1", + }, + "demo/tst1.ext:tst@parametrize=b2": { + "demo/src1.ext:src@parametrize=b2", + }, + "demo:src@parametrize=b1": { + "demo/src1.ext:src@parametrize=b1", + }, + "demo:src@parametrize=b2": { + "demo/src1.ext:src@parametrize=b2", + }, + "demo:tst@parametrize=b1": { + "demo/tst1.ext:tst@parametrize=b1", + }, + "demo:tst@parametrize=b2": { + "demo/tst1.ext:tst@parametrize=b2", + }, + }, + ) + + # ----------------------------------------------------------------------------------------------- # Test `SourcesField`. Also see `engine/target_test.py`. # -----------------------------------------------------------------------------------------------
Parametrized `python_tests` and `python_sources` in same package not lining up when using explicit `dependencies` **Describe the bug** I have a `python_source` target in the same directory as a `python_test` target. Both are parametrized for multiple resolves/environments/interpreter constraints. The `python_test` target in question does not import the `python_source` target but instead calls it via the `subprocess` module, so I have the `python_source` target as an explicit dependency of the `python_test` one. This is causing an error because the `python_test` target is grabbing the first parametrization as the dependency instead of the matching one. `pants peek` output below: ```json { "address": "my/python/tests/test_the_thing.py@parametrize=py311", "target_type": "python_test", "batch_compatibility_tag": null, "dependencies": [ "my/inferred_dep/__init__.py@parametrize=py311", "my/python/tests/__init__.py:sources_for_tests@parametrize=py38", "my/python/tests/source_for_test.py:sources_for_tests@parametrize=py38" ], "dependencies_raw": [ ":sources_for_tests" ], "description": null, "environment": "py311-test", "extra_env_vars": null, "interpreter_constraints": [ "==3.11.*" ], "resolve": "py311", "run_goal_use_sandbox": null, "runtime_package_dependencies": null, "skip_black": false, "skip_docformatter": false, "skip_isort": false, "skip_mypy": true, "skip_ruff": true, "skip_tests": false, "source_raw": "test_the_thing.py", "sources": [ "my/python/tests/test_the_thing.py" ], "sources_fingerprint": "b1274e36d37387cc0fca9f18cd77e456483663e6ac869ec1ecce9aaa502a8d83", "tags": null, "timeout": null, "xdist_concurrency": null } ``` **Pants version** 2.19.1 **OS** Intel Mac
Sorry for the trouble; can you create a reduced example as a demonstration? I understand the issue here.. will see if I can come up with a fix for it. @ndellosa95 Can you share the relevant parts of your BUILD files for this (redacted as needed), just to make sure I test the right thing? Thanks :) Or, if you can confirm that this test matches what you have.. ```python assert_generated( generated_targets_rule_runner, Address("demo", target_name="tst"), dedent( """\ generator( name='src', sources=['src1.ext'], **parametrize('b1', resolve='a'), **parametrize('b2', resolve='b'), ) generator( name='tst', sources=['tst1.ext'], dependencies=['./src1.ext:src'], **parametrize('b1', resolve='a'), **parametrize('b2', resolve='b'), ) """ ), ["src1.ext", "tst1.ext"], expected_dependencies={ "demo/src1.ext:src@parametrize=b1": set(), "demo/src1.ext:src@parametrize=b2": set(), "demo/tst1.ext:tst@parametrize=b1": { "demo/src1.ext:src@parametrize=b1", }, "demo/tst1.ext:tst@parametrize=b2": { "demo/src1.ext:src@parametrize=b2", }, "demo:src@parametrize=b1": { "demo/src1.ext:src@parametrize=b1", }, "demo:src@parametrize=b2": { "demo/src1.ext:src@parametrize=b2", }, "demo:tst@parametrize=b1": { "demo/tst1.ext:tsr@parametrize=b1", }, "demo:tst@parametrize=b2": { "demo/tst1.ext:tst@parametrize=b2", }, }, ) ``` which does fail with a missmatched parametrization for the explicitly provided dependency: ``` E 'demo/tst1.ext:tst@parametriz 'demo/tst1.ext:tst@parametriz E e=b2': set([ e=b2': set([ E 'demo/src1.ext:src@parametr 'demo/src1.ext:src@parametr E ize=b1', ize=b2', E ]), ]), ``` > Or, if you can confirm that this test matches what you have.. > > ```python > assert_generated( > generated_targets_rule_runner, > Address("demo", target_name="tst"), > dedent( > """\ > generator( > name='src', > sources=['src1.ext'], > **parametrize('b1', resolve='a'), > **parametrize('b2', resolve='b'), > ) > generator( > name='tst', > sources=['tst1.ext'], > dependencies=['./src1.ext:src'], > **parametrize('b1', resolve='a'), > **parametrize('b2', resolve='b'), > ) > """ > ), > ["src1.ext", "tst1.ext"], > expected_dependencies={ > "demo/src1.ext:src@parametrize=b1": set(), > "demo/src1.ext:src@parametrize=b2": set(), > "demo/tst1.ext:tst@parametrize=b1": { > "demo/src1.ext:src@parametrize=b1", > }, > "demo/tst1.ext:tst@parametrize=b2": { > "demo/src1.ext:src@parametrize=b2", > }, > "demo:src@parametrize=b1": { > "demo/src1.ext:src@parametrize=b1", > }, > "demo:src@parametrize=b2": { > "demo/src1.ext:src@parametrize=b2", > }, > "demo:tst@parametrize=b1": { > "demo/tst1.ext:tsr@parametrize=b1", > }, > "demo:tst@parametrize=b2": { > "demo/tst1.ext:tst@parametrize=b2", > }, > }, > ) > ``` > > which does fail with a missmatched parametrization for the explicitly provided dependency: > > ``` > E 'demo/tst1.ext:tst@parametriz 'demo/tst1.ext:tst@parametriz > E e=b2': set([ e=b2': set([ > E 'demo/src1.ext:src@parametr 'demo/src1.ext:src@parametr > E ize=b1', ize=b2', > E ]), ]), > ``` Yes, it always selects the first target in the parametrization.
2024-04-12T07:21:04
pantsbuild/pants
20,779
pantsbuild__pants-20779
[ "20739" ]
7850bcbd5b11e7a0de3aada26dd4c9ca329ffef3
diff --git a/src/python/pants/engine/internals/parametrize.py b/src/python/pants/engine/internals/parametrize.py --- a/src/python/pants/engine/internals/parametrize.py +++ b/src/python/pants/engine/internals/parametrize.py @@ -427,12 +427,20 @@ def remaining_fields_match(candidate: Target) -> bool: ): return parametrization.original_target - # Else, see whether any of the generated targets match. - for candidate in parametrization.parametrization.values(): - if address.is_parametrized_subset_of(candidate.address) and remaining_fields_match( - candidate - ): - return candidate + consumer_parametrize_group = consumer.address.parameters.get("parametrize") + + def matching_parametrize_group(candidate: Target) -> bool: + return candidate.address.parameters.get("parametrize") == consumer_parametrize_group + + for candidate in sorted( + self.parametrizations.values(), key=matching_parametrize_group, reverse=True + ): + # Else, see whether any of the generated targets match, preferring a matching + # parametrize group when available. + if address.is_parametrized_subset_of(candidate.address) and remaining_fields_match( + candidate + ): + return candidate raise ValueError( f"The explicit dependency `{address}` of the target at `{consumer.address}` does "
diff --git a/src/python/pants/engine/internals/graph_test.py b/src/python/pants/engine/internals/graph_test.py --- a/src/python/pants/engine/internals/graph_test.py +++ b/src/python/pants/engine/internals/graph_test.py @@ -1627,6 +1627,55 @@ def test_parametrize_group_on_target_generator_20418( ) +def test_parametrize_explicit_dependencies_20739( + generated_targets_rule_runner: RuleRunner, +) -> None: + assert_generated( + generated_targets_rule_runner, + Address("demo", target_name="tst"), + dedent( + """\ + generator( + name='src', + sources=['src1.ext'], + **parametrize('b1', resolve='a'), + **parametrize('b2', resolve='b'), + ) + generator( + name='tst', + sources=['tst1.ext'], + dependencies=['./src1.ext:src'], + **parametrize('b1', resolve='a'), + **parametrize('b2', resolve='b'), + ) + """ + ), + ["src1.ext", "tst1.ext"], + expected_dependencies={ + "demo/src1.ext:src@parametrize=b1": set(), + "demo/src1.ext:src@parametrize=b2": set(), + "demo/tst1.ext:tst@parametrize=b1": { + "demo/src1.ext:src@parametrize=b1", + }, + "demo/tst1.ext:tst@parametrize=b2": { + "demo/src1.ext:src@parametrize=b2", + }, + "demo:src@parametrize=b1": { + "demo/src1.ext:src@parametrize=b1", + }, + "demo:src@parametrize=b2": { + "demo/src1.ext:src@parametrize=b2", + }, + "demo:tst@parametrize=b1": { + "demo/tst1.ext:tst@parametrize=b1", + }, + "demo:tst@parametrize=b2": { + "demo/tst1.ext:tst@parametrize=b2", + }, + }, + ) + + # ----------------------------------------------------------------------------------------------- # Test `SourcesField`. Also see `engine/target_test.py`. # -----------------------------------------------------------------------------------------------
Parametrized `python_tests` and `python_sources` in same package not lining up when using explicit `dependencies` **Describe the bug** I have a `python_source` target in the same directory as a `python_test` target. Both are parametrized for multiple resolves/environments/interpreter constraints. The `python_test` target in question does not import the `python_source` target but instead calls it via the `subprocess` module, so I have the `python_source` target as an explicit dependency of the `python_test` one. This is causing an error because the `python_test` target is grabbing the first parametrization as the dependency instead of the matching one. `pants peek` output below: ```json { "address": "my/python/tests/test_the_thing.py@parametrize=py311", "target_type": "python_test", "batch_compatibility_tag": null, "dependencies": [ "my/inferred_dep/__init__.py@parametrize=py311", "my/python/tests/__init__.py:sources_for_tests@parametrize=py38", "my/python/tests/source_for_test.py:sources_for_tests@parametrize=py38" ], "dependencies_raw": [ ":sources_for_tests" ], "description": null, "environment": "py311-test", "extra_env_vars": null, "interpreter_constraints": [ "==3.11.*" ], "resolve": "py311", "run_goal_use_sandbox": null, "runtime_package_dependencies": null, "skip_black": false, "skip_docformatter": false, "skip_isort": false, "skip_mypy": true, "skip_ruff": true, "skip_tests": false, "source_raw": "test_the_thing.py", "sources": [ "my/python/tests/test_the_thing.py" ], "sources_fingerprint": "b1274e36d37387cc0fca9f18cd77e456483663e6ac869ec1ecce9aaa502a8d83", "tags": null, "timeout": null, "xdist_concurrency": null } ``` **Pants version** 2.19.1 **OS** Intel Mac
Sorry for the trouble; can you create a reduced example as a demonstration? I understand the issue here.. will see if I can come up with a fix for it. @ndellosa95 Can you share the relevant parts of your BUILD files for this (redacted as needed), just to make sure I test the right thing? Thanks :) Or, if you can confirm that this test matches what you have.. ```python assert_generated( generated_targets_rule_runner, Address("demo", target_name="tst"), dedent( """\ generator( name='src', sources=['src1.ext'], **parametrize('b1', resolve='a'), **parametrize('b2', resolve='b'), ) generator( name='tst', sources=['tst1.ext'], dependencies=['./src1.ext:src'], **parametrize('b1', resolve='a'), **parametrize('b2', resolve='b'), ) """ ), ["src1.ext", "tst1.ext"], expected_dependencies={ "demo/src1.ext:src@parametrize=b1": set(), "demo/src1.ext:src@parametrize=b2": set(), "demo/tst1.ext:tst@parametrize=b1": { "demo/src1.ext:src@parametrize=b1", }, "demo/tst1.ext:tst@parametrize=b2": { "demo/src1.ext:src@parametrize=b2", }, "demo:src@parametrize=b1": { "demo/src1.ext:src@parametrize=b1", }, "demo:src@parametrize=b2": { "demo/src1.ext:src@parametrize=b2", }, "demo:tst@parametrize=b1": { "demo/tst1.ext:tsr@parametrize=b1", }, "demo:tst@parametrize=b2": { "demo/tst1.ext:tst@parametrize=b2", }, }, ) ``` which does fail with a missmatched parametrization for the explicitly provided dependency: ``` E 'demo/tst1.ext:tst@parametriz 'demo/tst1.ext:tst@parametriz E e=b2': set([ e=b2': set([ E 'demo/src1.ext:src@parametr 'demo/src1.ext:src@parametr E ize=b1', ize=b2', E ]), ]), ``` > Or, if you can confirm that this test matches what you have.. > > ```python > assert_generated( > generated_targets_rule_runner, > Address("demo", target_name="tst"), > dedent( > """\ > generator( > name='src', > sources=['src1.ext'], > **parametrize('b1', resolve='a'), > **parametrize('b2', resolve='b'), > ) > generator( > name='tst', > sources=['tst1.ext'], > dependencies=['./src1.ext:src'], > **parametrize('b1', resolve='a'), > **parametrize('b2', resolve='b'), > ) > """ > ), > ["src1.ext", "tst1.ext"], > expected_dependencies={ > "demo/src1.ext:src@parametrize=b1": set(), > "demo/src1.ext:src@parametrize=b2": set(), > "demo/tst1.ext:tst@parametrize=b1": { > "demo/src1.ext:src@parametrize=b1", > }, > "demo/tst1.ext:tst@parametrize=b2": { > "demo/src1.ext:src@parametrize=b2", > }, > "demo:src@parametrize=b1": { > "demo/src1.ext:src@parametrize=b1", > }, > "demo:src@parametrize=b2": { > "demo/src1.ext:src@parametrize=b2", > }, > "demo:tst@parametrize=b1": { > "demo/tst1.ext:tsr@parametrize=b1", > }, > "demo:tst@parametrize=b2": { > "demo/tst1.ext:tst@parametrize=b2", > }, > }, > ) > ``` > > which does fail with a missmatched parametrization for the explicitly provided dependency: > > ``` > E 'demo/tst1.ext:tst@parametriz 'demo/tst1.ext:tst@parametriz > E e=b2': set([ e=b2': set([ > E 'demo/src1.ext:src@parametr 'demo/src1.ext:src@parametr > E ize=b1', ize=b2', > E ]), ]), > ``` Yes, it always selects the first target in the parametrization.
2024-04-12T07:21:08
pantsbuild/pants
20,802
pantsbuild__pants-20802
[ "20794" ]
794d0d456781e1121f82b24d1b0829e3b99ddcfb
diff --git a/src/python/pants/jvm/target_types.py b/src/python/pants/jvm/target_types.py --- a/src/python/pants/jvm/target_types.py +++ b/src/python/pants/jvm/target_types.py @@ -309,6 +309,8 @@ def to_coord_str(self) -> str: result = self.group if self.artifact: result += f":{self.artifact}" + else: + result += ":*" return result
diff --git a/src/python/pants/jvm/resolve/coursier_fetch_integration_test.py b/src/python/pants/jvm/resolve/coursier_fetch_integration_test.py --- a/src/python/pants/jvm/resolve/coursier_fetch_integration_test.py +++ b/src/python/pants/jvm/resolve/coursier_fetch_integration_test.py @@ -18,7 +18,11 @@ from pants.jvm.resolve.coordinate import Coordinate, Coordinates from pants.jvm.resolve.coursier_fetch import CoursierLockfileEntry, CoursierResolvedLockfile from pants.jvm.resolve.coursier_fetch import rules as coursier_fetch_rules -from pants.jvm.target_types import JvmArtifactJarSourceField, JvmArtifactTarget +from pants.jvm.target_types import ( + JvmArtifactExclusion, + JvmArtifactJarSourceField, + JvmArtifactTarget, +) from pants.jvm.testutil import maybe_skip_jdk_test from pants.jvm.util_rules import ExtractFileDigest from pants.jvm.util_rules import rules as util_rules @@ -662,6 +666,25 @@ def test_transitive_excludes(rule_runner: RuleRunner) -> None: assert not any(i for i in entries if i.coord.artifact == "jackson-core") +@maybe_skip_jdk_test +def test_transitive_group_only_excludes(rule_runner: RuleRunner) -> None: + group_only_excludes = JvmArtifactExclusion(group="com.fasterxml.jackson.core", artifact=None) + + requirement = ArtifactRequirement( + coordinate=Coordinate( + group="com.fasterxml.jackson.module", + artifact="jackson-module-jaxb-annotations", + version="2.17.1", + ), + excludes=frozenset([group_only_excludes.to_coord_str()]), + ) + + resolve = rule_runner.request(CoursierResolvedLockfile, [ArtifactRequirements([requirement])]) + + entries = resolve.entries + assert not any(i for i in entries if i.coord.group == "com.fasterxml.jackson.core") + + @maybe_skip_jdk_test def test_missing_entry_for_transitive_dependency(rule_runner: RuleRunner) -> None: requirement = ArtifactRequirement(
jvm_exclude with Group Only Fails Parsing by Coursier **Describe the bug** Running `pants generate-lockfiles` when a `jvm_artifact` contains a `jvm_exclude` that only specifies a group will fail with a "Failed to parse [group-name]" message from Coursier. This is contrary to the documentation for `jvm_exclude` which states "`jvm_exclude`: Exclude the given `artifact` and `group`, or all artifacts from the given `group`." **Pants version** 2.20.0rc2 **OS** MacOS **Additional info** Example Repo https://github.com/NGustafson/pants-examples/blob/main/3rdparty/jvm/BUILD This repo has a single jvm_artifact with nothing else configured. Attempting to run `pants generate-lockfiles` will cause this error: ``` pants generate-lockfiles [ERROR] 1 Exception encountered: Engine traceback: in `generate-lockfiles` goal ProcessExecutionFailure: Process 'Running `coursier fetch` against 1 requirement: org.slf4j:slf4j-log4j12:2.0.12' failed with exit code 1. stdout: stderr: + coursier_exe=__coursier/./cs-aarch64-apple-darwin + shift + json_output_file=coursier_report.json + shift ++ pwd + working_dir=/private/var/folders/cm/gmrdwxcn7tv_cct4dzg38w91kjyl1q/T/pants-sandbox-aM4FVB + __coursier/./cs-aarch64-apple-darwin fetch -r=https://maven-central.storage-download.googleapis.com/maven2 -r=https://repo1.maven.org/maven2 --no-default --json-output-file=coursier_report.json org.slf4j:slf4j-log4j12:2.0.12 --local-exclude-file PANTS_RESOLVE_EXCLUDES Failed to parse org.slf4j Failed to parse org.slf4j ```
Thanks for filing an issue with a reproducer and sorry for the trouble! I did an initial triage to check priority/regression: it looks like this behaviour has existed since 2.18.0.dev0 (`PANTS_VERSION=2.18.0.dev0 pants generate-lockfiles`), which seems to be the first release that had this `jvm_exclude` https://github.com/pantsbuild/pants/pull/19128, so not a regression. @NGustafson is this something you might have a chance at trying to fix? @alonsodomin is something you can provide hints or guidance about? @huonw Thanks for checking! Yes I'd like to try fixing this. It seems like Coursier supports group-only excludes if you set the artifact to `*`. Something like `--exclude 'org.slf4j:*'`. But this Pants syntax causes a different error `jvm_exclude(group="org.slf4j", artifact="*")`, so I'm going to try getting that to work first. sorry for the trouble, it's true that initial implementation was wrong. This should be easy to fix, the point in which the exclusion is transformed into a coordinate string is in here: https://github.com/pantsbuild/pants/blob/b7b0e9ca349bc15c619c62c4ef9ba7787bf2b9d9/src/python/pants/jvm/target_types.py#L308
2024-04-17T12:15:36
pantsbuild/pants
20,901
pantsbuild__pants-20901
[ "20722" ]
4012d9eff25e6913a32623863f2b646c27fa7e10
diff --git a/src/python/pants/backend/python/subsystems/python_tool_base.py b/src/python/pants/backend/python/subsystems/python_tool_base.py --- a/src/python/pants/backend/python/subsystems/python_tool_base.py +++ b/src/python/pants/backend/python/subsystems/python_tool_base.py @@ -3,9 +3,14 @@ from __future__ import annotations +import importlib.resources +import json import logging import os -from typing import ClassVar, Iterable, Sequence +from dataclasses import dataclass +from functools import cache +from typing import ClassVar, Iterable, Optional, Sequence +from urllib.parse import urlparse from pants.backend.python.target_types import ConsoleScript, EntryPoint, MainSpecification from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints @@ -18,6 +23,7 @@ Lockfile, PexRequirements, Resolve, + strip_comments_from_pex_json_lockfile, ) from pants.core.goals.resolves import ExportableTool from pants.engine.fs import Digest @@ -27,11 +33,18 @@ from pants.option.subsystem import Subsystem from pants.util.docutil import doc_url, git_url from pants.util.meta import classproperty +from pants.util.pip_requirement import PipRequirement from pants.util.strutil import softwrap logger = logging.getLogger(__name__) +@dataclass(frozen=True) +class _PackageNameAndVersion: + name: str + version: str + + class PythonToolRequirementsBase(Subsystem, ExportableTool): """Base class for subsystems that configure a set of requirements for a python tool.""" @@ -42,6 +55,7 @@ class PythonToolRequirementsBase(Subsystem, ExportableTool): # Subclasses may set to override the value computed from default_version and # default_extra_requirements. + # The primary package used in the subsystem must always be the first requirement. # TODO: Once we get rid of those options, subclasses must set this to loose # requirements that reflect any minimum capabilities Pants assumes about the tool. default_requirements: Sequence[str] = [] @@ -51,15 +65,20 @@ class PythonToolRequirementsBase(Subsystem, ExportableTool): default_lockfile_resource: ClassVar[tuple[str, str] | None] = None - install_from_resolve = StrOption( - advanced=True, - default=None, - help=lambda cls: softwrap( + @classmethod + def _install_from_resolve_help(cls) -> str: + package_and_version = cls._default_package_name_and_version() + version_clause = ( + f", which uses `{package_and_version.name}` version {package_and_version.version}" + if package_and_version + else "" + ) + return softwrap( f"""\ If specified, install the tool using the lockfile for this named resolve. This resolve must be defined in `[python].resolves`, as described in - {doc_url("docs/python/overview/third-party-dependencies#user-lockfiles")}. + {doc_url("docs/python/overview/lockfiles#lockfiles-for-tools")}. The resolve's entire lockfile will be installed, unless specific requirements are listed via the `requirements` option, in which case only those requirements @@ -67,13 +86,18 @@ class PythonToolRequirementsBase(Subsystem, ExportableTool): outputs when the resolve incurs changes to unrelated requirements. If unspecified, and the `lockfile` option is unset, the tool will be installed - using the default lockfile shipped with Pants. + using the default lockfile shipped with Pants{version_clause}. If unspecified, and the `lockfile` option is set, the tool will use the custom `{cls.options_scope}` "tool lockfile" generated from the `version` and `extra_requirements` options. But note that this mechanism is deprecated. """ - ), + ) + + install_from_resolve = StrOption( + advanced=True, + default=None, + help=lambda cls: cls._install_from_resolve_help(), ) requirements = StrListOption( @@ -169,6 +193,42 @@ def pex_requirements_for_default_lockfile(cls): resolve_name=cls.options_scope, ) + @classmethod + @cache + def _default_package_name_and_version(cls) -> Optional[_PackageNameAndVersion]: + if cls.default_lockfile_resource is None: + return None + + lockfile = cls.pex_requirements_for_default_lockfile() + parts = urlparse(lockfile.url) + # urlparse retains the leading / in URLs with a netloc. + lockfile_path = parts.path[1:] if parts.path.startswith("/") else parts.path + if parts.scheme in {"", "file"}: + with open(lockfile_path, "rb") as fp: + lock_bytes = fp.read() + elif parts.scheme == "resource": + # The "netloc" in our made-up "resource://" scheme is the package. + lock_bytes = importlib.resources.read_binary(parts.netloc, lockfile_path) + else: + raise ValueError( + f"Unsupported scheme {parts.scheme} for lockfile URL: {lockfile.url} " + f"(origin: {lockfile.url_description_of_origin})" + ) + + stripped_lock_bytes = strip_comments_from_pex_json_lockfile(lock_bytes) + lockfile_contents = json.loads(stripped_lock_bytes) + # The first requirement must contain the primary package for this tool, otherwise + # this will pick up the wrong requirement. + first_default_requirement = PipRequirement.parse(cls.default_requirements[0]) + return next( + _PackageNameAndVersion( + name=first_default_requirement.project_name, version=requirement["version"] + ) + for resolve in lockfile_contents["locked_resolves"] + for requirement in resolve["locked_requirements"] + if requirement["project_name"] == first_default_requirement.project_name + ) + def pex_requirements( self, *, diff --git a/src/python/pants/option/scope.py b/src/python/pants/option/scope.py --- a/src/python/pants/option/scope.py +++ b/src/python/pants/option/scope.py @@ -41,7 +41,7 @@ class ScopeInfo: @property def description(self) -> str: - return cast(str, getattr(self.subsystem_cls, "help")) + return cast(str, self._subsystem_cls_attr("help")) @property def deprecated_scope(self) -> Optional[str]:
Show the default version of built-in (Python) tools in docs somewhere **Describe the bug** Currently the default version of a Python tool built-in to Pants (like black) doesn't seem to be shown in the documentation anywhere, it's just implied by the lockfile, which is hidden: e.g. https://www.pantsbuild.org/2.19/reference/subsystems/black (Compare a JVM tool like `openapi-generator` which has a default value for the version field: https://www.pantsbuild.org/2.19/reference/subsystems/openapi-generator#version) This leads to confusion when newer releases of a tool change behaviour, deprecate options or even introduce new ones (like #20707) and a user can't tell why their configuration isn't working when run with Pants. Suggestion: have `PythonToolRequirementsBase` dynamically argument the subsystem's help text by reading the lockfile. For instance, for the page above, adding the second paragraph in: > The Black Python code formatter (https://black.readthedocs.io/). > > This version of Pants uses Black 23.3.0 by default. Use [a dedicated lockfile](https://www.pantsbuild.org/2.19/docs/python/overview/lockfiles#lockfiles-for-tools) and [the `install_from_resolve` option](https://www.pantsbuild.org/2.19/reference/subsystems/black#install_from_resolve) to control this. This could potentially also be applied to the `install_from_resolve` and/or `requirements` fields. **Pants version** 2.19 **OS** N/A **Additional info** N/A
Happy to take this one! Assigned to myself
2024-05-10T01:53:55
pantsbuild/pants
20,903
pantsbuild__pants-20903
[ "20893" ]
a3eaf7007fcb2d878edd9f08d922799289567c25
diff --git a/src/python/pants/backend/python/goals/export.py b/src/python/pants/backend/python/goals/export.py --- a/src/python/pants/backend/python/goals/export.py +++ b/src/python/pants/backend/python/goals/export.py @@ -84,16 +84,16 @@ class ExportPluginOptions: help=softwrap( """ When exporting a mutable virtualenv for a resolve, do PEP-660 editable installs - of all 'python_distribution' targets that own code in the exported resolve. + of all `python_distribution` targets that own code in the exported resolve. - If a resolve name is not in this list, 'python_distribution' targets will not + If a resolve name is not in this list, `python_distribution` targets will not be installed in the virtualenv. This defaults to an empty list for backwards compatibility and to prevent unnecessary work to generate and install the PEP-660 editable wheels. - This only applies when '[python].enable_resolves' is true and when exporting a - 'mutable_virtualenv' ('symlinked_immutable_virtualenv' exports are not "full" - virtualenvs because they must not be edited, and do not include 'pip'). + This only applies when `[python].enable_resolves` is true and when exporting a + `mutable_virtualenv` (`symlinked_immutable_virtualenv` exports are not "full" + virtualenvs because they must not be edited, and do not include `pip`). """ ), advanced=True, @@ -107,16 +107,16 @@ class ExportPluginOptions: modify console script shebang lines to make them "hermetic". The shebang of hermetic console scripts uses the python args: `-sE`: - - `-s` skips inclusion of the user site-packages directoy, - - `-E` ignores all `PYTHON*` env vars like `PYTHONPATH`. + - `-s` skips inclusion of the user site-packages directory, + - `-E` ignores all `PYTHON*` env vars like `PYTHONPATH`. Set this to false if you need non-hermetic scripts with simple python shebangs that respect vars like `PYTHONPATH`, to, for example, allow IDEs like PyCharm to inject its debugger, coverage, or other IDE-specific libs when running a script. - This only applies when when exporting a 'mutable_virtualenv' - ('symlinked_immutable_virtualenv' exports are not "full" + This only applies when when exporting a `mutable_virtualenv` + (`symlinked_immutable_virtualenv` exports are not "full" virtualenvs because they are used internally by pants itself. Pants requires hermetic scripts to provide its reproduciblity guarantee, fine-grained caching, and other features).
`export` goal `py_hermetic_scripts` option docs have misrendered list **Describe the bug** There's a minor formatting defect in the docs for https://www.pantsbuild.org/2.21/reference/goals/export#py_hermetic_scripts ![image](https://github.com/pantsbuild/pants/assets/1203825/2dd8aedb-36f5-42b6-a23c-d93b8900bb5b) The `- -E` is intended to be a new list item. https://github.com/pantsbuild/pants/blob/2505e54f2d8dde4f509caa7749de5ab8ae1de450/src/python/pants/backend/python/goals/export.py#L110-L111 (While we're at it, we could potentially also switch `` 'mutable_virtualenv' ('symlinked_immutable_virtualenv' `` to use backticks and thus get code-formatting?) **Pants version** 2.21 **OS** N/A **Additional info** N/A
2024-05-10T06:57:38
pantsbuild/pants
20,904
pantsbuild__pants-20904
[ "20893" ]
54a36ea05358eddd13a841f2c00dc1f4a1519a0c
diff --git a/src/python/pants/backend/python/goals/export.py b/src/python/pants/backend/python/goals/export.py --- a/src/python/pants/backend/python/goals/export.py +++ b/src/python/pants/backend/python/goals/export.py @@ -84,16 +84,16 @@ class ExportPluginOptions: help=softwrap( """ When exporting a mutable virtualenv for a resolve, do PEP-660 editable installs - of all 'python_distribution' targets that own code in the exported resolve. + of all `python_distribution` targets that own code in the exported resolve. - If a resolve name is not in this list, 'python_distribution' targets will not + If a resolve name is not in this list, `python_distribution` targets will not be installed in the virtualenv. This defaults to an empty list for backwards compatibility and to prevent unnecessary work to generate and install the PEP-660 editable wheels. - This only applies when '[python].enable_resolves' is true and when exporting a - 'mutable_virtualenv' ('symlinked_immutable_virtualenv' exports are not "full" - virtualenvs because they must not be edited, and do not include 'pip'). + This only applies when `[python].enable_resolves` is true and when exporting a + `mutable_virtualenv` (`symlinked_immutable_virtualenv` exports are not "full" + virtualenvs because they must not be edited, and do not include `pip`). """ ), advanced=True, @@ -107,16 +107,16 @@ class ExportPluginOptions: modify console script shebang lines to make them "hermetic". The shebang of hermetic console scripts uses the python args: `-sE`: - - `-s` skips inclusion of the user site-packages directoy, - - `-E` ignores all `PYTHON*` env vars like `PYTHONPATH`. + - `-s` skips inclusion of the user site-packages directory, + - `-E` ignores all `PYTHON*` env vars like `PYTHONPATH`. Set this to false if you need non-hermetic scripts with simple python shebangs that respect vars like `PYTHONPATH`, to, for example, allow IDEs like PyCharm to inject its debugger, coverage, or other IDE-specific libs when running a script. - This only applies when when exporting a 'mutable_virtualenv' - ('symlinked_immutable_virtualenv' exports are not "full" + This only applies when when exporting a `mutable_virtualenv` + (`symlinked_immutable_virtualenv` exports are not "full" virtualenvs because they are used internally by pants itself. Pants requires hermetic scripts to provide its reproduciblity guarantee, fine-grained caching, and other features).
`export` goal `py_hermetic_scripts` option docs have misrendered list **Describe the bug** There's a minor formatting defect in the docs for https://www.pantsbuild.org/2.21/reference/goals/export#py_hermetic_scripts ![image](https://github.com/pantsbuild/pants/assets/1203825/2dd8aedb-36f5-42b6-a23c-d93b8900bb5b) The `- -E` is intended to be a new list item. https://github.com/pantsbuild/pants/blob/2505e54f2d8dde4f509caa7749de5ab8ae1de450/src/python/pants/backend/python/goals/export.py#L110-L111 (While we're at it, we could potentially also switch `` 'mutable_virtualenv' ('symlinked_immutable_virtualenv' `` to use backticks and thus get code-formatting?) **Pants version** 2.21 **OS** N/A **Additional info** N/A
2024-05-10T08:31:27
pantsbuild/pants
20,958
pantsbuild__pants-20958
[ "20947" ]
a4032b8bedd5517b563e813496c28210efc9c128
diff --git a/src/python/pants/engine/target.py b/src/python/pants/engine/target.py --- a/src/python/pants/engine/target.py +++ b/src/python/pants/engine/target.py @@ -2190,23 +2190,19 @@ def path_globs(self, unmatched_build_file_globs: UnmatchedBuildFileGlobs) -> Pat [self.default] if self.default and isinstance(self.default, str) else self.default ) - # Match any if we use default globs, else match all. - conjunction = ( - GlobExpansionConjunction.all_match - if not default_globs or (set(self.globs) != set(default_globs)) - else GlobExpansionConjunction.any_match - ) + using_default_globs = default_globs and (set(self.globs) == set(default_globs)) or False + # Use fields default error behavior if defined, if we use default globs else the provided # error behavior. error_behavior = ( unmatched_build_file_globs.error_behavior - if conjunction == GlobExpansionConjunction.all_match - or self.default_glob_match_error_behavior is None + if not using_default_globs or self.default_glob_match_error_behavior is None else self.default_glob_match_error_behavior ) + return PathGlobs( (self._prefix_glob_with_address(glob) for glob in self.globs), - conjunction=conjunction, + conjunction=GlobExpansionConjunction.any_match, glob_match_error_behavior=error_behavior, description_of_origin=( f"{self.address}'s `{self.alias}` field"
diff --git a/src/python/pants/engine/target_test.py b/src/python/pants/engine/target_test.py --- a/src/python/pants/engine/target_test.py +++ b/src/python/pants/engine/target_test.py @@ -1061,7 +1061,7 @@ class GenSources(GenerateSourcesRequest): "test/b", ), glob_match_error_behavior=GlobMatchErrorBehavior.warn, - conjunction=GlobExpansionConjunction.all_match, + conjunction=GlobExpansionConjunction.any_match, description_of_origin="test:test's `sources` field", ), id="provided value warns on glob match error", @@ -1108,7 +1108,7 @@ class TestMultipleSourcesField(MultipleSourcesField): expected_path_globs( globs=("test/other_file",), glob_match_error_behavior=GlobMatchErrorBehavior.warn, - conjunction=GlobExpansionConjunction.all_match, + conjunction=GlobExpansionConjunction.any_match, description_of_origin="test:test's `source` field", ), id="provided value warns on glob match error", @@ -1119,7 +1119,7 @@ class TestMultipleSourcesField(MultipleSourcesField): expected_path_globs( globs=("test/life",), glob_match_error_behavior=GlobMatchErrorBehavior.warn, - conjunction=GlobExpansionConjunction.all_match, + conjunction=GlobExpansionConjunction.any_match, description_of_origin="test:test's `source` field", ), id="default glob conjunction", diff --git a/tests/python/pants_test/integration/graph_integration_test.py b/tests/python/pants_test/integration/graph_integration_test.py --- a/tests/python/pants_test/integration/graph_integration_test.py +++ b/tests/python/pants_test/integration/graph_integration_test.py @@ -15,7 +15,6 @@ _SOURCES_TARGET_BASE = "testprojects/src/python/sources" _ERR_TARGETS = { - "testprojects/src/python/sources:some-missing-some-not": 'Unmatched glob from testprojects/src/python/sources:some-missing-some-not\'s `sources` field: "testprojects/src/python/sources/*.rs"', "testprojects/src/python/sources:missing-sources": 'Unmatched glob from testprojects/src/python/sources:missing-sources\'s `sources` field: "testprojects/src/python/sources/*.scala", excludes: ["testprojects/src/python/sources/*Spec.scala", "testprojects/src/python/sources/*Suite.scala", "testprojects/src/python/sources/*Test.scala"]', }
Values from `__defaults__` are not treated the same as builtin field defaults. > There is one downside with the current implementation for this, and that is that Pants will now treat the "default" glob for the `sources` field as "user provided", and as such err out for any globs that don't match any files. > > This is a pain if used in `__defaults__` to adjust the default sources glob for some target (say I want to have all `factories.py` files owned by `python_test_utils` rather than `python_sources` by default, but that file is not going to exist for all targets but [unmatched_build_file_globs](https://www.pantsbuild.org/v2.16/docs/reference-global#unmatched_build_file_globs) is a global option only..) _Originally posted by @kaos in https://github.com/pantsbuild/pants/issues/17614#issuecomment-1548085565_ ---- The context here is, that source globs provided as field values will err if they match _no_ files, where as source globs from the field default value does not. However, the values provided by `__defaults__` is treated the same as if they were provided directly on the target as a regular value.
Honestly I think we should just relax that error message, and not do anything special if a user-specified glob matches no files. That is, assume users are not dummies... That seems like by far the easiest solution, and I never liked that error. After all, `__defaults__` are provided by users, and so sometimes an empty glob might indicate a real mistake they made there? Other times it wouldn't, as in your example. How do we decide when it's necessary to babysit the user's globs? I subit that we should never do this. An empty set is a set. Hmm.. interesting. Yea, maybe this is the only case where we treat a default value as being different from a user provided value. And could be a sign that we shouldn't do that. Agree this adds quite a bit of complexity to maintain, so I'm +1 to change this. (I guess even better would be if there was in the syntax so you could specify if you want all or any of the globs to match..) Thanks for considering! I just overall think Pants is too intrusive and that we try to babysit the user in arbitrary and inconsistent ways, and probably shouldn't. The likelihood that a user specifies a glob at all is low, the likelihood that it unintentionally fails to match anything is even lower, and even when that happens, the user will figure it out and fix their glob? I mean, "my glob doesn't match anything but it should" is just one of a variety of bad glob errors, and we don't (and can't) detect most of them (such as "my glob matches the wrong things"). And on the other hand there is a cost to all this code. So I say let's keep it simple.
2024-05-27T08:57:25
pantsbuild/pants
20,984
pantsbuild__pants-20984
[ "20977" ]
18a01f7c321508a891c8f09a544b9532c4c35fa8
diff --git a/src/python/pants/backend/python/framework/stevedore/target_types.py b/src/python/pants/backend/python/framework/stevedore/target_types.py --- a/src/python/pants/backend/python/framework/stevedore/target_types.py +++ b/src/python/pants/backend/python/framework/stevedore/target_types.py @@ -11,20 +11,22 @@ class StevedoreNamespace(str): - f"""Tag a namespace in entry_points as a stevedore namespace. + """Tag a namespace in entry_points as a stevedore namespace. This is required for the entry_point to be visible to dep inference based on the `stevedore_namespaces` field. For example: - {PythonDistribution.alias}( - ... - entry_points={{ - stevedore_namespace("a.b.c"): {{ - "plugin_name": "some.entry:point", - }}, - }}, - ) + ```python + python_distribution( + ... + entry_points={ + stevedore_namespace("a.b.c"): { + "plugin_name": "some.entry:point", + }, + }, + ) + ``` """ alias = "stevedore_namespace"
`stevedore_namespace` documentation shows `str`'s doc string **Describe the bug** The `stevedore_namespace` BUILD file symbol has a doc-string, but it isn't shown in `pants help-all`. It instead shows what looks like the doc string for `str`. https://github.com/pantsbuild/pants/blob/ec86d19cd954cd49a9562880a7c0dbc45632778c/src/python/pants/backend/python/framework/stevedore/target_types.py#L13-L30 To reproduce, enable the stevedore backend and look at `help` or `help-all`: ```shell PANTS_VERSION=2.22.0.dev3 pants --backend-packages=pants.backend.experimental.python.framework.stevedore help stevedore_namespace ``` ``` `stevedore_namespace` BUILD file symbol --------------------------------------- str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. ``` ```shell PANTS_VERSION=2.22.0.dev3 pants --backend-packages=pants.backend.experimental.python.framework.stevedore help-all | \ jq .name_to_build_file_info.stevedore_namespace ``` ```json { "documentation": "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'.", "is_target": false, "name": "stevedore_namespace", "signature": null } ``` **Pants version** Seems to be visible in 2.16 through to the currently latest. **OS** both **Additional info** - Will appear in online docs too after https://github.com/pantsbuild/pantsbuild.org/pull/216 - Relevant issues: - https://github.com/pantsbuild/pants/discussions/18117 - https://github.com/pantsbuild/pants/issues/14832
2024-05-31T12:19:00
pantsbuild/pants
21,003
pantsbuild__pants-21003
[ "20938" ]
cc5577ed867400cb003da75aa1a9d44812ecf940
diff --git a/src/python/pants_release/generate_github_workflows.py b/src/python/pants_release/generate_github_workflows.py --- a/src/python/pants_release/generate_github_workflows.py +++ b/src/python/pants_release/generate_github_workflows.py @@ -37,11 +37,12 @@ class Platform(Enum): LINUX_X86_64 = "Linux-x86_64" LINUX_ARM64 = "Linux-ARM64" MACOS10_15_X86_64 = "macOS10-15-x86_64" - MACOS11_X86_64 = "macOS11-x86_64" + # the oldest version of macOS supported by GitHub self-hosted runners + MACOS12_X86_64 = "macOS12-x86_64" MACOS11_ARM64 = "macOS11-ARM64" -GITHUB_HOSTED = {Platform.LINUX_X86_64, Platform.MACOS11_X86_64} +GITHUB_HOSTED = {Platform.LINUX_X86_64, Platform.MACOS12_X86_64} SELF_HOSTED = {Platform.LINUX_ARM64, Platform.MACOS10_15_X86_64, Platform.MACOS11_ARM64} CARGO_AUDIT_IGNORED_ADVISORY_IDS = ( "RUSTSEC-2020-0128", # returns a false positive on the cache crate, which is a local crate not a 3rd party crate @@ -400,8 +401,8 @@ def runs_on(self) -> list[str]: # any platform-specific labels, so we don't run on future GH-hosted # platforms without realizing it. ret = ["self-hosted"] if self.platform in SELF_HOSTED else [] - if self.platform == Platform.MACOS11_X86_64: - ret += ["macos-11"] + if self.platform == Platform.MACOS12_X86_64: + ret += ["macos-12"] elif self.platform == Platform.MACOS11_ARM64: ret += ["macOS-11-ARM64"] elif self.platform == Platform.MACOS10_15_X86_64: @@ -416,7 +417,7 @@ def runs_on(self) -> list[str]: def platform_env(self): ret = {} - if self.platform in {Platform.MACOS10_15_X86_64, Platform.MACOS11_X86_64}: + if self.platform in {Platform.MACOS10_15_X86_64, Platform.MACOS12_X86_64}: # Works around bad `-arch arm64` flag embedded in Xcode 12.x Python interpreters on # intel machines. See: https://github.com/giampaolo/psutil/issues/1832 ret["ARCHFLAGS"] = "-arch x86_64" @@ -809,8 +810,8 @@ def linux_arm64_test_jobs() -> Jobs: return jobs -def macos11_x86_64_test_jobs() -> Jobs: - helper = Helper(Platform.MACOS11_X86_64) +def macos12_x86_64_test_jobs() -> Jobs: + helper = Helper(Platform.MACOS12_X86_64) jobs = { helper.job_name("bootstrap_pants"): bootstrap_jobs( helper, @@ -1003,7 +1004,7 @@ def test_workflow_jobs() -> Jobs: } jobs.update(**linux_x86_64_test_jobs()) jobs.update(**linux_arm64_test_jobs()) - jobs.update(**macos11_x86_64_test_jobs()) + jobs.update(**macos12_x86_64_test_jobs()) jobs.update(**build_wheels_jobs()) jobs.update( {
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -202,16 +202,16 @@ jobs: ./cargo doc' timeout-minutes: 60 - bootstrap_pants_macos11_x86_64: + bootstrap_pants_macos12_x86_64: env: PANTS_REMOTE_CACHE_READ: 'false' PANTS_REMOTE_CACHE_WRITE: 'false' if: (github.repository_owner == 'pantsbuild') && (needs.classify_changes.outputs.docs_only != 'true') - name: Bootstrap Pants, test Rust (macOS11-x86_64) + name: Bootstrap Pants, test Rust (macOS12-x86_64) needs: - classify_changes runs-on: - - macos-11 + - macos-12 steps: - name: Check out code uses: actions/checkout@v3 @@ -231,7 +231,7 @@ jobs: - name: Cache Rust toolchain uses: actions/cache@v3 with: - key: macOS11-x86_64-rustup-${{ hashFiles('src/rust/engine/rust-toolchain') }}-v2 + key: macOS12-x86_64-rustup-${{ hashFiles('src/rust/engine/rust-toolchain') }}-v2 path: '~/.rustup/toolchains/1.78.0-* ~/.rustup/update-hashes @@ -252,7 +252,7 @@ jobs: - name: Cache native engine uses: actions/cache@v3 with: - key: macOS11-x86_64-engine-${{ steps.get-engine-hash.outputs.hash }}-v1 + key: macOS12-x86_64-engine-${{ steps.get-engine-hash.outputs.hash }}-v1 path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so @@ -277,12 +277,12 @@ jobs: name: Upload pants.log uses: actions/upload-artifact@v3 with: - name: logs-bootstrap-macOS11-x86_64 + name: logs-bootstrap-macOS12-x86_64 path: .pants.d/workdir/*.log - name: Upload native binaries uses: actions/upload-artifact@v3 with: - name: native_binaries.${{ matrix.python-version }}.macOS11-x86_64 + name: native_binaries.${{ matrix.python-version }}.macOS12-x86_64 path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so @@ -683,7 +683,7 @@ jobs: - check_release_notes - bootstrap_pants_linux_arm64 - bootstrap_pants_linux_x86_64 - - bootstrap_pants_macos11_x86_64 + - bootstrap_pants_macos12_x86_64 - build_wheels_linux_arm64 - build_wheels_linux_x86_64 - build_wheels_macos10_15_x86_64 @@ -703,7 +703,7 @@ jobs: - test_python_linux_x86_64_7 - test_python_linux_x86_64_8 - test_python_linux_x86_64_9 - - test_python_macos11_x86_64 + - test_python_macos12_x86_64 outputs: merge_ok: ${{ steps.set_merge_ok.outputs.merge_ok }} runs-on: @@ -1675,16 +1675,16 @@ jobs: name: logs-python-test-9_10-Linux-x86_64 path: .pants.d/workdir/*.log timeout-minutes: 90 - test_python_macos11_x86_64: + test_python_macos12_x86_64: env: ARCHFLAGS: -arch x86_64 if: (github.repository_owner == 'pantsbuild') && (needs.classify_changes.outputs.docs_only != 'true') - name: Test Python (macOS11-x86_64) + name: Test Python (macOS12-x86_64) needs: - - bootstrap_pants_macos11_x86_64 + - bootstrap_pants_macos12_x86_64 - classify_changes runs-on: - - macos-11 + - macos-12 steps: - name: Check out code uses: actions/checkout@v3 @@ -1704,7 +1704,7 @@ jobs: - name: Download native binaries uses: actions/download-artifact@v3 with: - name: native_binaries.${{ matrix.python-version }}.macOS11-x86_64 + name: native_binaries.${{ matrix.python-version }}.macOS12-x86_64 path: src/python/pants - name: Make native-client runnable run: chmod +x src/python/pants/bin/native_client @@ -1718,7 +1718,7 @@ jobs: AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} if: always() name: Upload test reports - run: 'export S3_DST=s3://logs.pantsbuild.org/test/reports/macOS11-x86_64/$(git show --no-patch --format=%cd --date=format:%Y-%m-%d)/${GITHUB_REF_NAME//\//_}/${GITHUB_RUN_ID}/${GITHUB_RUN_ATTEMPT}/${GITHUB_JOB} + run: 'export S3_DST=s3://logs.pantsbuild.org/test/reports/macOS12-x86_64/$(git show --no-patch --format=%cd --date=format:%Y-%m-%d)/${GITHUB_REF_NAME//\//_}/${GITHUB_RUN_ID}/${GITHUB_RUN_ATTEMPT}/${GITHUB_JOB} echo "Uploading test reports to ${S3_DST}" @@ -1730,7 +1730,7 @@ jobs: name: Upload pants.log uses: actions/upload-artifact@v3 with: - name: logs-python-test-macOS11-x86_64 + name: logs-python-test-macOS12-x86_64 path: .pants.d/workdir/*.log timeout-minutes: 90 name: Pull Request CI
GitHub-hosted `macos-11` runners are deprecated and will be removed on 2024-06-28 **Describe the bug** We have various jobs that run on `macos-11` runners, but these are deprecated and need to be switched to `macos-12` or newer: https://github.blog/changelog/2024-05-20-actions-upcoming-changes-to-github-hosted-macos-runners/ **Pants version** All versions that still have CI run on macOS (i.e. 2.19) **OS** macOS **Additional info** N/A
2024-06-04T22:14:45
mindee/doctr
12
mindee__doctr-12
[ "11" ]
634c160ded784024a90f0d5a9925bafe5e2441e6
diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,92 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +import sphinx_rtd_theme + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) +import doctr + +# -- Project information ----------------------------------------------------- + +master_doc = 'index' +project = 'doctr' +copyright = '2021, Mindee' +author = 'François-Guillaume Fernandez, Charles Gaillard, Mohamed Biaz' + +# The full version, including alpha/beta/rc tags +version = doctr.__version__ +release = doctr.__version__ + '-git' + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.napoleon', + 'sphinx.ext.viewcode', + 'sphinx.ext.autosummary', + 'sphinx.ext.doctest', + 'sphinx.ext.intersphinx', + 'sphinx.ext.todo', + 'sphinx.ext.coverage', + 'sphinx.ext.mathjax' +] + +napoleon_use_ivar = True + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' +highlight_language = 'python3' + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' +html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +html_theme_options = { + 'collapse_navigation': False, + 'display_version': True, + 'logo_only': False, +} + + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = [] + +html_context = { + 'css_files': [ + 'https://fonts.googleapis.com/css?family=Lato', + ], +}
[docs] Add documentation building dependencies Some basic documentation with proper installation and usage installations would be greatly beneficial to the library. This would be the privileged mean of communication with non-developer audiences. Having it being automatically built using something similar to sphinx would be efficient considering all docstring will have a compatible format.
2021-01-12T16:47:17
mindee/doctr
30
mindee__doctr-30
[ "1" ]
1905d273b29a86ed2e83b5ec7380f6b77831c3a9
diff --git a/doctr/documents/reader.py b/doctr/documents/reader.py --- a/doctr/documents/reader.py +++ b/doctr/documents/reader.py @@ -8,7 +8,36 @@ import cv2 from typing import List, Tuple, Optional, Any -__all__ = ['read_pdf'] +__all__ = ['read_pdf', 'read_img'] + + +def read_img( + file_path: str, + output_size: Optional[Tuple[int, int]] = None, + rgb_output: bool = True, +) -> np.ndarray: + """Read an image file into numpy format + + Example:: + >>> from doctr.documents import read_img + >>> page = read_img("path/to/your/doc.jpg") + + Args: + file_path: the path to the image file + output_size: the expected output size of each page in format H x W + rgb_output: whether the output ndarray channel order should be RGB instead of BGR. + Returns: + the page decoded as numpy ndarray of shape H x W x 3 + """ + + img = cv2.imread(file_path, cv2.IMREAD_COLOR) + # Resizing + if isinstance(output_size, tuple): + img = cv2.resize(img, output_size[::-1], interpolation=cv2.INTER_LINEAR) + # Switch the channel order + if rgb_output: + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + return img def read_pdf(file_path: str, **kwargs: Any) -> List[np.ndarray]:
diff --git a/test/test_documents.py b/test/test_documents.py --- a/test/test_documents.py +++ b/test/test_documents.py @@ -213,3 +213,30 @@ def test_read_pdf(mock_pdf): # 1 doc of 8 pages assert(len(doc_tensors) == 8) assert all(isinstance(page, np.ndarray) for page in doc_tensors) + assert all(page.dtype == np.uint8 for page in doc_tensors) + + +def test_read_img(tmpdir_factory): + + url = 'https://upload.wikimedia.org/wikipedia/commons/5/55/Grace_Hopper.jpg' + file = BytesIO(requests.get(url).content) + tmp_path = str(tmpdir_factory.mktemp("data").join("mock_img_file.jpg")) + with open(tmp_path, 'wb') as f: + f.write(file.getbuffer()) + + page = documents.reader.read_img(tmp_path) + + # Data type + assert isinstance(page, np.ndarray) + assert page.dtype == np.uint8 + # Shape + assert page.shape == (606, 517, 3) + + # RGB + bgr_page = documents.reader.read_img(tmp_path, rgb_output=False) + assert np.all(page == bgr_page[..., ::-1]) + + # Resize + target_size = (200, 150) + resized_page = documents.reader.read_img(tmp_path, target_size) + assert resized_page.shape[:2] == target_size
[documents] Add basic document reader For documents to be analyzed, we first need to add a utility for document reading (PDF mostly). The following specs would be nice to have: - inherit for a shared reader class ("DocumentReader" for instance) - to be located in the `doctr.documents.reader` module The following formats should be handled: - [x] PDF (#8, #25): this resource would be nice to check: https://github.com/pymupdf/PyMuPDF - [x] PNG (#30) - [x] JPG (#30) cc @charlesmindee
2021-01-20T17:38:58
mindee/doctr
33
mindee__doctr-33
[ "31" ]
fb19153703a7143e8b78cbc8db12eae85b55b4c4
diff --git a/doctr/models/__init__.py b/doctr/models/__init__.py --- a/doctr/models/__init__.py +++ b/doctr/models/__init__.py @@ -1,3 +1,4 @@ from .preprocessor import * from .detection import * +from .recognition import * from . import utils diff --git a/doctr/models/recognition/__init__.py b/doctr/models/recognition/__init__.py new file mode 100644 --- /dev/null +++ b/doctr/models/recognition/__init__.py @@ -0,0 +1 @@ +from ._utils import * diff --git a/doctr/models/recognition/_utils.py b/doctr/models/recognition/_utils.py new file mode 100644 --- /dev/null +++ b/doctr/models/recognition/_utils.py @@ -0,0 +1,34 @@ +# Copyright (C) 2021, Mindee. + +# This program is licensed under the Apache License version 2. +# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. + +import numpy as np +from typing import List + +__all__ = ['extract_crops'] + + +def extract_crops(img: np.ndarray, boxes: np.ndarray) -> List[np.ndarray]: + """Created cropped images from list of bounding boxes + + Args: + img: input image + boxes: bounding boxes of shape (N, 4) where N is the number of boxes, and the relative + coordinates (xmin, ymin, xmax, ymax) + + Returns: + list of cropped images + """ + if boxes.shape[1] != 4: + raise AssertionError("boxes are expected to be relative and in order (xmin, ymin, xmax, ymax)") + + # Project relative coordinates + _boxes = boxes.copy() + _boxes[:, [0, 2]] *= img.shape[1] + _boxes[:, [1, 3]] *= img.shape[0] + _boxes = _boxes.round().astype(int) + # Add last index + _boxes[2:] += 1 + + return [img[box[1]: box[3], box[0]: box[2]] for box in _boxes]
diff --git a/test/test_models.py b/test/test_models.py --- a/test/test_models.py +++ b/test/test_models.py @@ -96,3 +96,20 @@ def test_dbmodel(): assert len(dboutput_train) == 3 # batch size assert all(out.numpy().shape == (8, 640, 640, 1) for out in dboutput_train) + + +def test_extract_crops(mock_pdf): # noqa: F811 + doc_img = read_pdf(mock_pdf)[0] + num_crops = 2 + boxes = np.array([[idx / num_crops, idx / num_crops, (idx + 1) / num_crops, (idx + 1) / num_crops] + for idx in range(num_crops)], dtype=np.float32) + croped_imgs = models.recognition.extract_crops(doc_img, boxes) + + # Number of crops + assert len(croped_imgs) == num_crops + # Data type and shape + assert all(isinstance(crop, np.ndarray) for crop in croped_imgs) + assert all(crop.ndim == 3 for crop in croped_imgs) + + # Identity + assert np.all(doc_img == models.recognition.extract_crops(doc_img, np.array([[0, 0, 1, 1]]))[0])
Write a conversion function from Image + bounding boxes to cropped images The detection block is currently returning a list of bounding boxes, while the recognition block is actually using cropped images. The recognition pre-processing needs to handle this. **Input** - images: Numpy-style encoded images (already read) - bounding boxes: list of tensor of predictions of size N*4 (xmin, ymin, xmax, ymax) **Output** - cropped images: N cropped images
2021-01-21T16:56:28
mindee/doctr
52
mindee__doctr-52
[ "40" ]
ec113bfbc282c76e19ae55b911639e051c894ba0
diff --git a/doctr/documents/elements.py b/doctr/documents/elements.py --- a/doctr/documents/elements.py +++ b/doctr/documents/elements.py @@ -165,14 +165,14 @@ def __init__( blocks: List[Block], page_idx: int, dimensions: Tuple[int, int], - orientation: Dict[str, Any], - language: Dict[str, Any], + orientation: Optional[Dict[str, Any]] = None, + language: Optional[Dict[str, Any]] = None, ) -> None: super().__init__(blocks=blocks) self.page_idx = page_idx self.dimensions = dimensions - self.orientation = orientation - self.language = language + self.orientation = orientation if isinstance(orientation, dict) else dict(value=None, confidence=None) + self.language = language if isinstance(language, dict) else dict(value=None, confidence=None) def render(self, block_break: str = '\n\n') -> str: """Renders the full text of the element""" diff --git a/doctr/models/core.py b/doctr/models/core.py --- a/doctr/models/core.py +++ b/doctr/models/core.py @@ -11,6 +11,7 @@ from .detection import DetectionPredictor from .recognition import RecognitionPredictor from ._utils import extract_crops +from ..documents.elements import Word, Line, Block, Page, Document __all__ = ['OCRPredictor'] @@ -32,10 +33,61 @@ def __init__( self.det_predictor = det_predictor self.reco_predictor = reco_predictor + @staticmethod + def _build_blocks(boxes: np.ndarray, char_sequences: List[str]) -> List[Block]: + """Gather independent words in structured blocks + + Args: + boxes: bounding boxes of all detected words of the page, of shape (N, 4) + char_sequences: list of all detected words of the page, of shape N + + Returns: + list of block elements + """ + + if boxes.shape[0] != len(char_sequences): + raise ValueError(f"Incompatible argument lengths: {boxes.shape[0]}, {len(char_sequences)}") + + # Sort bounding boxes from top to bottom, left to right + idxs = (boxes[:, 0] + boxes[:, 1] * (boxes[:, 2] - boxes[:, 0])).argsort() + # Try to arrange them in lines + lines = [] + words: List[int] = [] + for idx in idxs: + + if len(words) == 0: + words = [idx] + continue + # Check horizontal gaps + horz_gap = boxes[idx, 0] - boxes[words[-1], 0] < 0.5 * (boxes[words[-1], 2] - boxes[words[-1], 0]) + # Check vertical gaps + vert_gap = abs(boxes[idx, 3] - boxes[words[-1], 3]) > 0.5 * (boxes[words[-1], 3] - boxes[words[-1], 1]) + + if horz_gap or vert_gap: + lines.append(words) + words.clear() + + words.append(idx) + + if len(words) > 0: + lines.append(words) + + blocks = [ + Block([Line( + [Word( + char_sequences[idx], + boxes[idx, 4], + ((boxes[idx, 0], boxes[idx, 1]), (boxes[idx, 2], boxes[idx, 3])) + ) for idx in line] + )]) for line in lines + ] + + return blocks + def __call__( self, documents: List[List[np.ndarray]], - ) -> List[List[List[Dict[str, Any]]]]: + ) -> List[Document]: pages = [page for doc in documents for page in doc] @@ -52,15 +104,21 @@ def __call__( page_idx, crop_idx = 0, 0 results = [] for doc_idx, nb_pages in enumerate(num_pages): - doc = [] + _pages = [] for page_boxes in boxes[page_idx: page_idx + nb_pages]: - page = [] - for _idx in range(num_crops[page_idx]): - page.append(dict(box=page_boxes[_idx], text=char_sequences[crop_idx + _idx])) - + # Assemble all detected words into structured blocks + _pages.append( + Page( + self._build_blocks( + page_boxes[:num_crops[page_idx]], + char_sequences[crop_idx: crop_idx + num_crops[page_idx]] + ), + page_idx, + pages[page_idx].shape[:2], + ) + ) crop_idx += num_crops[page_idx] page_idx += 1 - doc.append(page) - results.append(doc) + results.append(Document(_pages)) return results
diff --git a/test/test_models.py b/test/test_models.py --- a/test/test_models.py +++ b/test/test_models.py @@ -15,7 +15,7 @@ from tensorflow.keras import layers, Sequential -from doctr.documents import read_pdf +from doctr.documents import read_pdf, Document, Page, Block, Line, Word from test_documents import mock_pdf from doctr import models @@ -262,11 +262,10 @@ def test_ocrpredictor(mock_pdf, mock_mapping, test_detectionpredictor, test_reco out = predictor(docs) assert len(out) == num_docs + # Document + assert all(isinstance(doc, Document) for doc in out) # The input PDF has 8 pages - assert all(len(doc) == 8 for doc in out) - # Structure of page - assert all(isinstance(page, list) for doc in out for page in doc) - assert all(isinstance(elt, dict) for doc in out for page in doc for elt in page) + assert all(len(doc.pages) == 8 for doc in out) def test_sar_decoder(mock_mapping):
[models] Add full OCR module Design an object that will wrap all DL model components and be responsible for localizing and identifying all text elements in documents. **Inputs** - a collection of documents, where each document is a list of pages, themselves expressed as numpy-encoded images. **Outputs** - a collection of `Document` objects The following components will be required: - [x] DetectionPredictor (#39) - [x] RecognitionPredictor (#39) - [x] OCRPredictor (#39) - [x] ElementExporter (#16, #26, #40)
2021-02-01T17:59:58
mindee/doctr
81
mindee__doctr-81
[ "28" ]
078b613fc1b052f93a58e3a22f34465ec9632b53
diff --git a/scripts/collect_env.py b/scripts/collect_env.py new file mode 100644 --- /dev/null +++ b/scripts/collect_env.py @@ -0,0 +1,316 @@ +# Copyright (C) 2021, Mindee. + +# This program is licensed under the Apache License version 2. +# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. + +""" +Based on https://github.com/pytorch/pytorch/blob/master/torch/utils/collect_env.py +This script outputs relevant system environment info +Run it with `python collect_env.py`. +""" + +from __future__ import absolute_import, division, print_function, unicode_literals +import locale +import re +import subprocess +import sys +import os +from collections import namedtuple + +os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' + +try: + import doctr + DOCTR_AVAILABLE = True +except (ImportError, NameError, AttributeError): + DOCTR_AVAILABLE = False + +try: + import tensorflow as tf + TF_AVAILABLE = True +except (ImportError, NameError, AttributeError): + TF_AVAILABLE = False + +PY3 = sys.version_info >= (3, 0) + + +# System Environment Information +SystemEnv = namedtuple('SystemEnv', [ + 'doctr_version', + 'tf_version', + 'os', + 'python_version', + 'is_cuda_available', + 'cuda_runtime_version', + 'nvidia_driver_version', + 'nvidia_gpu_models', + 'cudnn_version', +]) + + +def run(command): + """Returns (return-code, stdout, stderr)""" + p = subprocess.Popen(command, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, shell=True) + output, err = p.communicate() + rc = p.returncode + if PY3: + enc = locale.getpreferredencoding() + output = output.decode(enc) + err = err.decode(enc) + return rc, output.strip(), err.strip() + + +def run_and_read_all(run_lambda, command): + """Runs command using run_lambda; reads and returns entire output if rc is 0""" + rc, out, _ = run_lambda(command) + if rc != 0: + return None + return out + + +def run_and_parse_first_match(run_lambda, command, regex): + """Runs command using run_lambda, returns the first regex match if it exists""" + rc, out, _ = run_lambda(command) + if rc != 0: + return None + match = re.search(regex, out) + if match is None: + return None + return match.group(1) + + +def get_nvidia_driver_version(run_lambda): + if get_platform() == 'darwin': + cmd = 'kextstat | grep -i cuda' + return run_and_parse_first_match(run_lambda, cmd, + r'com[.]nvidia[.]CUDA [(](.*?)[)]') + smi = get_nvidia_smi() + return run_and_parse_first_match(run_lambda, smi, r'Driver Version: (.*?) ') + + +def get_gpu_info(run_lambda): + if get_platform() == 'darwin': + if TF_AVAILABLE and any(tf.config.list_physical_devices('GPU')): + return tf.config.list_physical_devices('GPU')[0].name + return None + smi = get_nvidia_smi() + uuid_regex = re.compile(r' \(UUID: .+?\)') + rc, out, _ = run_lambda(smi + ' -L') + if rc != 0: + return None + # Anonymize GPUs by removing their UUID + return re.sub(uuid_regex, '', out) + + +def get_running_cuda_version(run_lambda): + return run_and_parse_first_match(run_lambda, 'nvcc --version', r'release .+ V(.*)') + + +def get_cudnn_version(run_lambda): + """This will return a list of libcudnn.so; it's hard to tell which one is being used""" + if get_platform() == 'win32': + cudnn_cmd = 'where /R "%CUDA_PATH%\\bin" cudnn*.dll' + elif get_platform() == 'darwin': + # CUDA libraries and drivers can be found in /usr/local/cuda/. See + # https://docs.nvidia.com/cuda/cuda-installation-guide-mac-os-x/index.html#install + # https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html#installmac + # Use CUDNN_LIBRARY when cudnn library is installed elsewhere. + cudnn_cmd = 'ls /usr/local/cuda/lib/libcudnn*' + else: + cudnn_cmd = 'ldconfig -p | grep libcudnn | rev | cut -d" " -f1 | rev' + rc, out, _ = run_lambda(cudnn_cmd) + # find will return 1 if there are permission errors or if not found + if len(out) == 0 or (rc != 1 and rc != 0): + lib = os.environ.get('CUDNN_LIBRARY') + if lib is not None and os.path.isfile(lib): + return os.path.realpath(l) + return None + files = set() + for fn in out.split('\n'): + fn = os.path.realpath(fn) # eliminate symbolic links + if os.path.isfile(fn): + files.add(fn) + if not files: + return None + # Alphabetize the result because the order is non-deterministic otherwise + files = list(sorted(files)) + if len(files) == 1: + return files[0] + result = '\n'.join(files) + return 'Probably one of the following:\n{}'.format(result) + + +def get_nvidia_smi(): + # Note: nvidia-smi is currently available only on Windows and Linux + smi = 'nvidia-smi' + if get_platform() == 'win32': + smi = '"C:\\Program Files\\NVIDIA Corporation\\NVSMI\\%s"' % smi + return smi + + +def get_platform(): + if sys.platform.startswith('linux'): + return 'linux' + elif sys.platform.startswith('win32'): + return 'win32' + elif sys.platform.startswith('cygwin'): + return 'cygwin' + elif sys.platform.startswith('darwin'): + return 'darwin' + else: + return sys.platform + + +def get_mac_version(run_lambda): + return run_and_parse_first_match(run_lambda, 'sw_vers -productVersion', r'(.*)') + + +def get_windows_version(run_lambda): + return run_and_read_all(run_lambda, 'wmic os get Caption | findstr /v Caption') + + +def get_lsb_version(run_lambda): + return run_and_parse_first_match(run_lambda, 'lsb_release -a', r'Description:\t(.*)') + + +def check_release_file(run_lambda): + return run_and_parse_first_match(run_lambda, 'cat /etc/*-release', + r'PRETTY_NAME="(.*)"') + + +def get_os(run_lambda): + platform = get_platform() + + if platform == 'win32' or platform == 'cygwin': + return get_windows_version(run_lambda) + + if platform == 'darwin': + version = get_mac_version(run_lambda) + if version is None: + return None + return 'Mac OSX {}'.format(version) + + if platform == 'linux': + # Ubuntu/Debian based + desc = get_lsb_version(run_lambda) + if desc is not None: + return desc + + # Try reading /etc/*-release + desc = check_release_file(run_lambda) + if desc is not None: + return desc + + return platform + + # Unknown platform + return platform + + +def get_env_info(): + run_lambda = run + + if DOCTR_AVAILABLE: + doctr_str = doctr.__version__ + else: + doctr_str = 'N/A' + + if TF_AVAILABLE: + tf_str = tf.__version__ + cuda_available_str = any(tf.config.list_physical_devices('GPU')) + else: + tf_str = cuda_available_str = 'N/A' + + return SystemEnv( + doctr_version=doctr_str, + tf_version=tf_str, + python_version='{}.{}'.format(sys.version_info[0], sys.version_info[1]), + is_cuda_available=cuda_available_str, + cuda_runtime_version=get_running_cuda_version(run_lambda), + nvidia_gpu_models=get_gpu_info(run_lambda), + nvidia_driver_version=get_nvidia_driver_version(run_lambda), + cudnn_version=get_cudnn_version(run_lambda), + os=get_os(run_lambda), + ) + + +env_info_fmt = """ +DocTR version: {doctr_version} +TensorFlow version: {tf_version} +OS: {os} +Python version: {python_version} +Is CUDA available: {is_cuda_available} +CUDA runtime version: {cuda_runtime_version} +GPU models and configuration: {nvidia_gpu_models} +Nvidia driver version: {nvidia_driver_version} +cuDNN version: {cudnn_version} +""".strip() + + +def pretty_str(envinfo): + def replace_nones(dct, replacement='Could not collect'): + for key in dct.keys(): + if dct[key] is not None: + continue + dct[key] = replacement + return dct + + def replace_bools(dct, true='Yes', false='No'): + for key in dct.keys(): + if dct[key] is True: + dct[key] = true + elif dct[key] is False: + dct[key] = false + return dct + + def maybe_start_on_next_line(string): + # If `string` is multiline, prepend a \n to it. + if string is not None and len(string.split('\n')) > 1: + return '\n{}\n'.format(string) + return string + + mutable_dict = envinfo._asdict() + + # If nvidia_gpu_models is multiline, start on the next line + mutable_dict['nvidia_gpu_models'] = \ + maybe_start_on_next_line(envinfo.nvidia_gpu_models) + + # If the machine doesn't have CUDA, report some fields as 'No CUDA' + dynamic_cuda_fields = [ + 'cuda_runtime_version', + 'nvidia_gpu_models', + 'nvidia_driver_version', + ] + all_cuda_fields = dynamic_cuda_fields + ['cudnn_version'] + all_dynamic_cuda_fields_missing = all( + mutable_dict[field] is None for field in dynamic_cuda_fields) + if TF_AVAILABLE and not any(tf.config.list_physical_devices('GPU')) and all_dynamic_cuda_fields_missing: + for field in all_cuda_fields: + mutable_dict[field] = 'No CUDA' + + # Replace True with Yes, False with No + mutable_dict = replace_bools(mutable_dict) + + # Replace all None objects with 'Could not collect' + mutable_dict = replace_nones(mutable_dict) + + return env_info_fmt.format(**mutable_dict) + + +def get_pretty_env_info(): + """Collects environment information for debugging purposes + Returns: + str: environment information + """ + return pretty_str(get_env_info()) + + +def main(): + print("Collecting environment information...\n") + output = get_pretty_env_info() + print(output) + + +if __name__ == '__main__': + main()
[scripts] Add a script for environment collection To be able to systematically identify sources of reported issues, each bug report should come with a description of the user's environment. A script would be required to collect among others: - Python version - Tensorflow version - NVIDIA driver version - CUDA version The user would only have to paste the result in the PR description.
2021-02-10T17:06:04
mindee/doctr
82
mindee__doctr-82
[ "57" ]
e9bfd3e13b4811dc9a4a29102d5ead3b97938f48
diff --git a/doctr/utils/visualization.py b/doctr/utils/visualization.py --- a/doctr/utils/visualization.py +++ b/doctr/utils/visualization.py @@ -7,78 +7,36 @@ import matplotlib.patches as patches import mplcursors import numpy as np -from typing import Union, Tuple, List +from typing import Tuple, List, Dict, Any -from ..documents import Page, Block, Line, Word, Artefact +from ._typing import BoundingBox __all__ = ['visualize_page'] -def draw_word( - word: Word, +def create_patch( + geometry: BoundingBox, + label: str, page_dimensions: Tuple[int, int], - word_color: Tuple[int, int, int], - alpha: float = 0.3 -) -> patches.Patch: - """Create a matplotlib patch (rectangle) bounding the word - - Args: - word: Word object to bound - page_dimensions: dimensions of the Page - word_color: color to draw box - alpha: opacity parameter to fill the boxes, 0 = transparent - - Returns: - a rectangular Patch - """ - h, w = page_dimensions - (xmin, ymin), (xmax, ymax) = word.geometry - xmin, xmax = xmin * w, xmax * w - ymin, ymax = ymin * h, ymax * h - rect = patches.Rectangle( - (xmin, ymin), - xmax - xmin, - ymax - ymin, - fill=True, - linewidth=2, - edgecolor=word_color, - facecolor=(*word_color, alpha), - label=f"{word.value} (confidence: {word.confidence:.2%})" - ) - return rect - - -def draw_element( - element: Union[Artefact, Line, Block], - page_dimensions: Tuple[int, int], - element_color: Tuple[int, int, int], + color: Tuple[int, int, int], alpha: float = 0.3, - force_label: bool = True, + linewidth: int = 2, ) -> patches.Patch: """Create a matplotlib patch (rectangle) bounding the element Args: - element: Element (Artefact, Line, Block) to bound + geometry: bounding box of the element + label: label to display when hovered page_dimensions: dimensions of the Page - element_color: color to draw box + color: color to draw box alpha: opacity parameter to fill the boxes, 0 = transparent - force_label: wether to give a label to the patch or not if element = block or line + linewidth: line width Returns: a rectangular Patch """ - if isinstance(element, Artefact): - value = "type: {type}, confidence {score}".format(type=element.type, score=element.confidence) - elif force_label: - if isinstance(element, Line): - value = "line" - elif isinstance(element, Block): - value = "block" - else: - value = None - h, w = page_dimensions - (xmin, ymin), (xmax, ymax) = element.geometry + (xmin, ymin), (xmax, ymax) = geometry xmin, xmax = xmin * w, xmax * w ymin, ymax = ymin * h, ymax * h rect = patches.Rectangle( @@ -86,50 +44,57 @@ def draw_element( xmax - xmin, ymax - ymin, fill=True, - linewidth=1, - edgecolor=(*element_color, alpha), - facecolor=(*element_color, alpha), - label=value + linewidth=linewidth, + edgecolor=(*color, alpha), + facecolor=(*color, alpha), + label=label ) return rect def visualize_page( - page: Page, + page: Dict[str, Any], image: np.ndarray, words_only: bool = True, ) -> None: """Visualize a full page with predicted blocks, lines and words Args: - page: a Page of a Document - image: np array of the page, needs to have the same shape than page.dimensions + page: the exported Page of a Document + image: np array of the page, needs to have the same shape than page['dimensions'] + words_only: whether only words should be displayed """ # Display the image _, ax = plt.subplots() ax.imshow(image) # hide both axis - ax.get_xaxis().set_visible(False) - ax.get_yaxis().set_visible(False) + ax.axis('off') artists: List[patches.Patch] = [] # instantiate an empty list of patches (to be drawn on the page) - for block in page.blocks: + for block in page['blocks']: if not words_only: - rect = draw_element(block, page_dimensions=page.dimensions, element_color=(0, 1, 0)) + rect = create_patch(block['geometry'], 'block', page['dimensions'], (0, 1, 0), linewidth=1) # add patch on figure ax.add_patch(rect) # add patch to cursor's artists artists.append(rect) - for line in block.lines: + for line in block['lines']: if not words_only: - rect = draw_element(line, page_dimensions=page.dimensions, element_color=(1, 0, 0)) + rect = create_patch(line['geometry'], 'line', page['dimensions'], (1, 0, 0), linewidth=1) + ax.add_patch(rect) + artists.append(rect) + + for word in line['words']: + rect = create_patch(word['geometry'], f"{word['value']} (confidence: {word['confidence']:.2%})", + page['dimensions'], (0, 0, 1)) ax.add_patch(rect) artists.append(rect) - for word in line.words: - rect = draw_word(word, page_dimensions=page.dimensions, word_color=(0, 0, 1)) + if not words_only: + for artefact in block['artefacts']: + rect = create_patch(artefact['geometry'], 'artefact', page['dimensions'], (0.5, 0.5, 0.5), linewidth=1) ax.add_patch(rect) artists.append(rect)
diff --git a/test/test_utils_visualization.py b/test/test_utils_visualization.py --- a/test/test_utils_visualization.py +++ b/test/test_utils_visualization.py @@ -7,7 +7,6 @@ def test_visualize_page(): pages = _mock_pages() - images = [np.ones((300, 200, 3)), np.ones((500, 1000, 3))] - for image, page in zip(images, pages): - visualization.visualize_page(page, image, words_only=False) - plt.show(block=False) + image = np.ones((300, 200, 3)) + visualization.visualize_page(pages[0].export(), image, words_only=False) + plt.show(block=False)
[utils] Move doctr dependences out of doctr.utils The `doctr.utils.visualization` introduces a dependency of other modules, which might be troublesome later. Several options are at our disposal: - sterilize these imports, and implement the specific version in the modules of the former dependency - use exported dictionary versions of element to plot (typing would then not require the imports of doctr.documents) Any other suggestion is welcome!
2021-02-11T10:59:51
mindee/doctr
107
mindee__doctr-107
[ "71" ]
2c1d7470bb597008306be9df5dabccdddbd0f538
diff --git a/doctr/models/recognition/sar.py b/doctr/models/recognition/sar.py --- a/doctr/models/recognition/sar.py +++ b/doctr/models/recognition/sar.py @@ -89,7 +89,6 @@ class SARDecoder(layers.Layer, NestedObject): attention_units: number of hidden attention units num_decoder_layers: number of LSTM layers to stack - """ def __init__( self, @@ -98,7 +97,7 @@ def __init__( vocab_size: int, embedding_units: int, attention_units: int, - num_decoder_layers: int = 2 + num_decoder_layers: int = 2, ) -> None: super().__init__() @@ -115,6 +114,7 @@ def call( self, features: tf.Tensor, holistic: tf.Tensor, + labels: Optional[tf.sparse.SparseTensor] = None, **kwargs: Any, ) -> tf.Tensor: @@ -128,7 +128,7 @@ def call( # Initialize with the index of virtual START symbol (placed after <eos>) symbol = tf.fill(features.shape[0], self.vocab_size + 1) logits_list = [] - for _ in range(self.max_length + 1): # keep 1 step for <eos> + for t in range(self.max_length + 1): # keep 1 step for <eos> # one-hot symbol with depth vocab_size + 1 # embeded_symbol: shape (N, embedding_units) embeded_symbol = self.embed(tf.one_hot(symbol, depth=self.vocab_size + 1), **kwargs) @@ -141,7 +141,13 @@ def call( # shape (N, rnn_units + 1) -> (N, vocab_size + 1) logits = self.output_dense(logits, **kwargs) # update symbol with predicted logits for t+1 step - symbol = tf.argmax(logits, axis=-1) + if kwargs.get('training'): + dense_labels = tf.sparse.to_dense( + labels, default_value=self.vocab_size + ) + symbol = dense_labels[:, t] + else: + symbol = tf.argmax(logits, axis=-1) logits_list.append(logits) outputs = tf.stack(logits_list, axis=1) # shape (N, max_length + 1, vocab_size + 1) @@ -196,13 +202,19 @@ def __init__( def call( self, x: tf.Tensor, + labels: Optional[tf.sparse.SparseTensor] = None, **kwargs: Any, ) -> tf.Tensor: features = self.feat_extractor(x, **kwargs) pooled_features = tf.reduce_max(features, axis=1) # vertical max pooling encoded = self.encoder(pooled_features, **kwargs) - decoded = self.decoder(features, encoded, **kwargs) + if kwargs.get('training'): + if labels is None: + raise ValueError('Need to provide labels during training for teacher forcing') + decoded = self.decoder(features, encoded, labels, **kwargs) + else: + decoded = self.decoder(features, encoded, **kwargs) return decoded
diff --git a/test/test_models_recognition.py b/test/test_models_recognition.py --- a/test/test_models_recognition.py +++ b/test/test_models_recognition.py @@ -52,6 +52,25 @@ def test_recognition_models(arch_name, input_shape, output_size): assert out.numpy().shape == (batch_size, *output_size) +def test_sar_training(): + batch_size = 4 + input_shape = (64, 256, 3) + output_size = (41, 119) + reco_model = recognition.sar_vgg16_bn(input_shape=input_shape) + input_tensor = tf.random.uniform(shape=[batch_size, *input_shape], minval=0, maxval=1) + # input_labels: sparse_tensor of shape batch_size x max_len, encoding the labels + # filled with integers (classes of the characters at each timestep) + indices = [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2], [2, 0], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4]] + values = tf.random.uniform(shape=[11], minval=0, maxval=118, dtype=tf.dtypes.int64) + input_labels = tf.sparse.reorder( + tf.sparse.SparseTensor(indices=indices, values=values, dense_shape=[batch_size, 41]) + ) + out = reco_model(input_tensor, labels=input_labels, training=True) + assert isinstance(out, tf.Tensor) + assert isinstance(reco_model, tf.keras.Model) + assert out.numpy().shape == (batch_size, *output_size) + + @pytest.mark.parametrize( "post_processor, input_shape", [
[Models] Add SAR teacher forçing during training (decoder) Teacher forçing (feeding the LSTM decoder of SAR with ground-truth characters during training) is not implemented, and it should really improve performances
Could you elaborate on the part of the paper where this is mentioned please? :pray: "All the LSTM inputs are represented by one-hot vectors, followed by a linear ransformationΨ(). During training, the inputs of decoder LSTMs are replaced by the ground-truth character sequence"
2021-03-02T10:41:43
mindee/doctr
123
mindee__doctr-123
[ "56" ]
018d44a479dc41ea2f5470b696cb53ba2631b1ab
diff --git a/docs/source/conf.py b/docs/source/conf.py --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -73,7 +73,7 @@ # html_theme_options = { 'collapse_navigation': False, - 'display_version': True, + 'display_version': False, 'logo_only': False, }
[docs] Enable documentation of multiple versions at once As of now, the documentation that would be deployed publicly is only the latest version. The better alternative would be: - having the latest version by default - having the documentation of each release accessible as well using a displayed selector Hugginface transformers did the following: https://github.com/huggingface/transformers/blob/master/.circleci/deploy.sh
2021-03-09T15:35:19
mindee/doctr
139
mindee__doctr-139
[ "134" ]
cecaf8f8610bcfff87528b5f47bb277cee0fc9f4
diff --git a/doctr/models/detection/differentiable_binarization.py b/doctr/models/detection/differentiable_binarization.py --- a/doctr/models/detection/differentiable_binarization.py +++ b/doctr/models/detection/differentiable_binarization.py @@ -102,7 +102,18 @@ def polygon_to_box( distance = poly.area * self.unclip_ratio / poly.length # compute distance to expand polygon offset = pyclipper.PyclipperOffset() offset.AddPath(points, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON) - expanded_points = np.asarray(offset.Execute(distance)) # expand polygon + _points = offset.Execute(distance) + # Take biggest stack of points + idx = 0 + if len(_points) > 1: + max_size = 0 + for _idx, p in enumerate(_points): + if len(p) > max_size: + idx = _idx + max_size = len(p) + # We ensure that _points can be correctly casted to a ndarray + _points = [_points[idx]] + expanded_points = np.asarray(_points) # expand polygon if len(expanded_points) < 1: return None x, y, w, h = cv2.boundingRect(expanded_points) # compute a 4-points box from expanded polygon
diff --git a/test/test_models_detection.py b/test/test_models_detection.py --- a/test/test_models_detection.py +++ b/test/test_models_detection.py @@ -48,6 +48,35 @@ def test_dbpostprocessor(): assert all(np.all(np.logical_and(sample[:4] >= 0, sample[:4] <= 1)) for sample in out) # Repr assert repr(postprocessor) == 'DBPostProcessor(box_thresh=0.1, max_candidates=1000)' + # Edge case when the expanded points of the polygon has two lists + issue_points = np.array([ + [869, 561], + [923, 581], + [925, 595], + [915, 583], + [889, 583], + [905, 593], + [882, 601], + [901, 595], + [904, 604], + [876, 608], + [915, 614], + [911, 605], + [925, 601], + [930, 616], + [911, 617], + [900, 636], + [931, 637], + [904, 649], + [932, 649], + [932, 628], + [918, 627], + [934, 624], + [935, 573], + [909, 569], + [934, 562]], dtype=np.int32) + out = postprocessor.polygon_to_box(issue_points) + assert isinstance(out, tuple) and len(out) == 4 def test_db_resnet50_training_mode():
TypeError: Expected Ptr<cv::UMat> for argument 'array' when using read_pdf() Can't execute read_pdf() function. See the pdf file sent over slack to reproduce. python 3.6.9 ``` VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray return array(a, dtype, copy=False, order=order) Traceback (most recent call last): File "/home/jonathan/mindee/dev/client_tests//test_classifier/main.py", line 17, in <module> result = model([doc]) File "/home/jonathan/mindee/dev/client_tests//test_classifier/doctr/doctr/models/core.py", line 51, in __call__ boxes = self.det_predictor(pages, **kwargs) File "/home/jonathan/mindee/dev/client_tests//test_classifier/doctr/doctr/models/detection/core.py", line 140, in __call__ out = [self.post_processor(batch) for batch in out] File "/home/jonathan/mindee/dev/client_tests//test_classifier/doctr/doctr/models/detection/core.py", line 140, in <listcomp> out = [self.post_processor(batch) for batch in out] File "/home/jonathan/mindee/dev/client_tests//test_classifier/doctr/doctr/models/detection/differentiable_binarization.py", line 173, in __call__ boxes = self.bitmap_to_boxes(pred=p_, bitmap=bitmap_) File "/home/jonathan/mindee/dev/client_tests//test_classifier/doctr/doctr/models/detection/differentiable_binarization.py", line 140, in bitmap_to_boxes _box = self.polygon_to_box(points) File "/home/jonathan/mindee/dev/client_tests//test_classifier/doctr/doctr/models/detection/differentiable_binarization.py", line 106, in polygon_to_box x, y, w, h = cv2.boundingRect(expanded_points) # compute a 4-points box from expanded polygon TypeError: Expected Ptr<cv::UMat> for argument 'array' ```
@jonathanMindee Thanks for reporting this! Would you mind specifying a minimal version of the script you used that raised this error please? Sure, I used the sample code in the README.md ```python from doctr.documents import read_pdf, read_img from doctr.models import ocr_db_crnn model = ocr_db_crnn(pretrained=True) # PDF doc = read_pdf("path/to/your/doc.pdf") result = model([doc]) ``` Strange, I'm not able to reproduce the error, even with the sample pdf. Could you run our diagnostic script and report back the result? ``` wget https://raw.githubusercontent.com/mindee/doctr/main/scripts/collect_env.py # For security purposes, please check the contents of collect_env.py before running it. python collect_env.py ``` Collecting environment information... DocTR version: 0.1.1a0 TensorFlow version: 2.4.1 OS: Ubuntu 18.04.5 LTS Python version: 3.6 Is CUDA available: No CUDA runtime version: Could not collect GPU models and configuration: GPU 0: GeForce RTX 2080 Ti Nvidia driver version: 455.45.01 cuDNN version: Probably one of the following: /usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudnn.so.8.0.5 /usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.0.5 /usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.0.5 /usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.0.5 /usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.0.5 /usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.0.5 /usr/local/cuda-11.1/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.0.5
2021-03-13T17:39:28
mindee/doctr
172
mindee__doctr-172
[ "166" ]
dba14c7f729ced9e3d32b84c36d5a2e213d582a7
diff --git a/doctr/documents/reader.py b/doctr/documents/reader.py --- a/doctr/documents/reader.py +++ b/doctr/documents/reader.py @@ -7,13 +7,17 @@ import cv2 from pathlib import Path import fitz -from typing import List, Tuple, Optional, Any +from typing import List, Tuple, Optional, Any, Union, Sequence -__all__ = ['read_pdf', 'read_pdf_from_stream', 'read_img'] +__all__ = ['read_pdf', 'read_img', 'DocumentFile'] + + +AbstractPath = Union[str, Path] +AbstractFile = Union[AbstractPath, bytes] def read_img( - file_path: str, + file: AbstractFile, output_size: Optional[Tuple[int, int]] = None, rgb_output: bool = True, ) -> np.ndarray: @@ -24,17 +28,23 @@ def read_img( >>> page = read_img("path/to/your/doc.jpg") Args: - file_path: the path to the image file + file: the path to the image file output_size: the expected output size of each page in format H x W rgb_output: whether the output ndarray channel order should be RGB instead of BGR. Returns: the page decoded as numpy ndarray of shape H x W x 3 """ - if not Path(file_path).is_file(): - raise FileNotFoundError(f"unable to access {file_path}") + if isinstance(file, (str, Path)): + if not Path(file).is_file(): + raise FileNotFoundError(f"unable to access {file}") + img = cv2.imread(str(file), cv2.IMREAD_COLOR) + elif isinstance(file, bytes): + file = np.frombuffer(file, np.uint8) + img = cv2.imdecode(file, cv2.IMREAD_COLOR) + else: + raise TypeError("unsupported object type for argument 'file'") - img = cv2.imread(file_path, cv2.IMREAD_COLOR) # Validity check if img is None: raise ValueError("unable to read file.") @@ -47,7 +57,7 @@ def read_img( return img -def read_pdf(file_path: str, **kwargs: Any) -> List[np.ndarray]: +def read_pdf(file: AbstractFile, **kwargs: Any) -> List[np.ndarray]: """Read a PDF file and convert it into an image in numpy format Example:: @@ -55,30 +65,22 @@ def read_pdf(file_path: str, **kwargs: Any) -> List[np.ndarray]: >>> doc = read_pdf("path/to/your/doc.pdf") Args: - file_path: the path to the PDF file + file: the path to the PDF file Returns: the list of pages decoded as numpy ndarray of shape H x W x 3 """ - # Read pages with fitz and convert them to numpy ndarrays - return [convert_page_to_numpy(page, **kwargs) for page in fitz.open(file_path, filetype="pdf")] - - -def read_pdf_from_stream(stream: bytes, **kwargs: Any) -> List[np.ndarray]: - """Read a PDF stream and convert it into an image in numpy format + fitz_args = {} - Example:: - >>> from doctr.documents import read_pdf_from_stream - >>> with open("path/to/your/doc.pdf", 'rb') as f: doc = read_pdf_from_stream(f.read()) - - Args: - stream: serialized stream of the PDF content - Returns: - the list of pages decoded as numpy ndarray of shape H x W x 3 - """ + if isinstance(file, (str, Path)): + fitz_args['filename'] = file + elif isinstance(file, bytes): + fitz_args['stream'] = file + else: + raise TypeError("unsupported object type for argument 'file'") # Read pages with fitz and convert them to numpy ndarrays - return [convert_page_to_numpy(page, **kwargs) for page in fitz.open(stream=stream, filetype="pdf")] + return [convert_page_to_numpy(page, **kwargs) for page in fitz.open(**fitz_args, filetype="pdf")] def convert_page_to_numpy( @@ -114,3 +116,24 @@ def convert_page_to_numpy( img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img + + +class DocumentFile: + """Read a document from multiple extensions + + Example:: + >>> from doctr.documents import DocumentFile + >>> doc = DocumentFile.from_pdf("path/to/your/doc.pdf") + >>> doc = DocumentFile.from_images(["path/to/your/page1.png", "path/to/your/page2.png"]) + """ + + @classmethod + def from_pdf(cls, file: AbstractFile, **kwargs) -> List[np.ndarray]: + return read_pdf(file, **kwargs) + + @classmethod + def from_images(cls, files: Union[Sequence[AbstractFile], AbstractFile], **kwargs) -> List[np.ndarray]: + if isinstance(files, (str, Path, bytes)): + files = [files] + + return [read_img(file, **kwargs) for file in files] diff --git a/scripts/analyze.py b/scripts/analyze.py --- a/scripts/analyze.py +++ b/scripts/analyze.py @@ -5,7 +5,7 @@ import matplotlib.pyplot as plt from doctr.models import ocr_predictor -from doctr.documents import read_pdf +from doctr.documents import DocumentFile from doctr.utils.visualization import visualize_page @@ -13,7 +13,10 @@ def main(args): model = ocr_predictor(args.detection, args.recognition, pretrained=True) - doc = read_pdf(args.path) + if args.path.endswith(".pdf"): + doc = DocumentFile.from_pdf(args.path) + else: + doc = DocumentFile.from_images(args.path) out = model(doc) @@ -27,7 +30,7 @@ def parse_args(): parser = argparse.ArgumentParser(description='DocTR end-to-end analysis', formatter_class=argparse.ArgumentDefaultsHelpFormatter) - parser.add_argument('path', type=str, help='Path to the input PDF document') + parser.add_argument('path', type=str, help='Path to the input document (PDF or image)') parser.add_argument('--detection', type=str, default='db_resnet50', help='Text detection model to use for analysis') parser.add_argument('--recognition', type=str, default='crnn_vgg16_bn', diff --git a/scripts/evaluate.py b/scripts/evaluate.py --- a/scripts/evaluate.py +++ b/scripts/evaluate.py @@ -11,7 +11,6 @@ from doctr.utils.metrics import LocalizationConfusion, ExactMatch, OCRMetric from doctr.datasets import FUNSD -from doctr.documents import read_img from doctr.models import ocr_predictor, extract_crops
diff --git a/test/test_documents_reader.py b/test/test_documents_reader.py --- a/test/test_documents_reader.py +++ b/test/test_documents_reader.py @@ -23,24 +23,36 @@ def test_convert_page_to_numpy(mock_pdf): assert resized_page.shape == (396, 306, 3) -def _check_pdf_content(doc_tensors): +def _check_doc_content(doc_tensors, num_pages): # 1 doc of 8 pages - assert(len(doc_tensors) == 8) + assert(len(doc_tensors) == num_pages) assert all(isinstance(page, np.ndarray) for page in doc_tensors) assert all(page.dtype == np.uint8 for page in doc_tensors) -def test_read_pdf(mock_pdf): - doc_tensors = reader.read_pdf(mock_pdf) - _check_pdf_content(doc_tensors) +def test_read_pdf(mock_pdf, mock_pdf_stream): + for file in [mock_pdf, mock_pdf_stream]: + doc_tensors = reader.read_pdf(file) + _check_doc_content(doc_tensors, 8) + # Wrong input type + with pytest.raises(TypeError): + _ = reader.read_pdf(123) -def test_read_pdf_from_stream(mock_pdf_stream): - doc_tensors = reader.read_pdf_from_stream(mock_pdf_stream) - _check_pdf_content(doc_tensors) +def test_read_img(tmpdir_factory, mock_image_stream, mock_pdf): -def test_read_img(tmpdir_factory, mock_pdf): + # Wrong input type + with pytest.raises(TypeError): + _ = reader.read_img(123) + + # Non-existing file + with pytest.raises(FileNotFoundError): + reader.read_img("my_imaginary_file.jpg") + + # Invalid image + with pytest.raises(ValueError): + reader.read_img(str(mock_pdf)) url = 'https://upload.wikimedia.org/wikipedia/commons/5/55/Grace_Hopper.jpg' file = BytesIO(requests.get(url).content) @@ -65,9 +77,10 @@ def test_read_img(tmpdir_factory, mock_pdf): resized_page = reader.read_img(tmp_path, target_size) assert resized_page.shape[:2] == target_size - # Non-existing file - with pytest.raises(FileNotFoundError): - reader.read_img("my_imaginary_file.jpg") - # Invalid image - with pytest.raises(ValueError): - reader.read_img(str(mock_pdf)) + +def test_document_file(mock_pdf, mock_image_stream, mock_image_folder): + pages = reader.DocumentFile.from_pdf(mock_pdf) + _check_doc_content(pages, 8) + + pages = reader.DocumentFile.from_images(mock_image_stream) + _check_doc_content(pages, 1)
[documents] Harmonize file reading A package user has to import different functions to read a file depending on its extension, and reading mean (from path, from bytes). This needs serious refactoring. - [x] Handle reading means (#172) - [x] Handle extensions (#172)
2021-03-26T10:55:36
mindee/doctr
173
mindee__doctr-173
[ "167" ]
dba14c7f729ced9e3d32b84c36d5a2e213d582a7
diff --git a/doctr/utils/visualization.py b/doctr/utils/visualization.py --- a/doctr/utils/visualization.py +++ b/doctr/utils/visualization.py @@ -56,6 +56,7 @@ def visualize_page( page: Dict[str, Any], image: np.ndarray, words_only: bool = True, + scale: float = 10, ) -> None: """Visualize a full page with predicted blocks, lines and words @@ -74,9 +75,13 @@ def visualize_page( page: the exported Page of a Document image: np array of the page, needs to have the same shape than page['dimensions'] words_only: whether only words should be displayed + scale: figsize of the largest windows side """ + # Get proper scale and aspect ratio + h, w = image.shape[:2] + size = (scale * w / h, scale) if h > w else (scale, h / w * scale) + fig, ax = plt.subplots(figsize=size) # Display the image - _, ax = plt.subplots() ax.imshow(image) # hide both axis ax.axis('off') @@ -111,3 +116,4 @@ def visualize_page( # Create mlp Cursor to hover patches in artists mplcursors.Cursor(artists, hover=2).connect("add", lambda sel: sel.annotation.set_text(sel.artist.get_label())) + fig.tight_layout()
[docs] Add a visualization of the example script in the README While the readme specifies how you can use the example script, it does not show any visualization examples. We could easily add one to help users.
2021-03-26T11:42:08
mindee/doctr
219
mindee__doctr-219
[ "216" ]
f1c11264318a0245e1b32d5c8c683994065a981b
diff --git a/demo/app.py b/demo/app.py --- a/demo/app.py +++ b/demo/app.py @@ -74,7 +74,8 @@ def main(): # Forward the image to the model processed_batches = predictor.det_predictor.pre_processor(doc) - seg_map = predictor.det_predictor.model(processed_batches[0])[0] + seg_map = predictor.det_predictor.model(processed_batches[0])["proba_map"] + seg_map = tf.squeeze(seg_map, axis=[0, 3]) seg_map = cv2.resize(seg_map.numpy(), (doc[0].shape[1], doc[0].shape[0]), interpolation=cv2.INTER_LINEAR) # Plot the raw heatmap
Demo app error when analyzing my first document ## 🐛 Bug I tried to analyze a PNG and a PDF, got the same error. I try to change the model, didn't change anything. ## To Reproduce Steps to reproduce the behavior: 1. Upload a PNG 2. Click on analyze document <!-- If you have a code sample, error messages, stack traces, please provide it here as well --> ``` KeyError: 0 Traceback: File "/Users/thibautmorla/opt/anaconda3/lib/python3.8/site-packages/streamlit/script_runner.py", line 337, in _run_script exec(code, module.__dict__) File "/Users/thibautmorla/Downloads/doctr/demo/app.py", line 93, in <module> main() File "/Users/thibautmorla/Downloads/doctr/demo/app.py", line 77, in main seg_map = predictor.det_predictor.model(processed_batches[0])[0] ``` ## Additional context First image upload
Hi @Morluche ! Thanks for reporting this, would you mind sharing the doc or image that you used so that we can reproduce the error please ? :pray: <img width="396" alt="Capture d’écran 2021-03-01 à 11 21 43" src="https://user-images.githubusercontent.com/66415445/116097331-570c3100-a6aa-11eb-82b1-90606bcb748a.png"> [dropcontact_invoice_Azq8WZSSg3AUMHCT (1).pdf](https://github.com/mindee/doctr/files/6377755/dropcontact_invoice_Azq8WZSSg3AUMHCT.1.pdf)
2021-04-27T08:48:52
mindee/doctr
220
mindee__doctr-220
[ "218" ]
f45822abc32d07a55eeab49c33f40ca096c46c16
diff --git a/doctr/models/core.py b/doctr/models/core.py --- a/doctr/models/core.py +++ b/doctr/models/core.py @@ -71,7 +71,7 @@ def __init__( self, resolve_lines: bool = False, resolve_blocks: bool = False, - paragraph_break: float = 0.15 + paragraph_break: float = 0.035 ) -> None: self.resolve_lines = resolve_lines @@ -91,43 +91,82 @@ def _sort_boxes(boxes: np.ndarray) -> np.ndarray: Returns: indices of ordered boxes of shape (N,) """ + return (boxes[:, 0] + 2 * boxes[:, 3] / np.median(boxes[:, 3] - boxes[:, 1])).argsort() - return (boxes[:, 0] + boxes[:, 3] / np.median(boxes[:, 3] - boxes[:, 1])).argsort() + def _resolve_sub_lines(self, boxes: np.ndarray, words: List[int]) -> List[List[int]]: + """Split a line in sub_lines - def _resolve_lines(self, boxes: np.ndarray, idxs: np.ndarray) -> List[List[int]]: - """Uses ordered boxes to group them in lines + Args: + boxes: bounding boxes of shape (N, 4) + words: list of indexes for the words of the line + + Returns: + A list of (sub-)lines computed from the original line (words) + """ + lines = [] + # Sort words horizontally + words = [words[j] for j in np.argsort([boxes[i, 0] for i in words]).tolist()] + # Eventually split line horizontally + if len(words) < 2: + lines.append(words) + else: + sub_line = [words[0]] + for i in words[1:]: + horiz_break = True + + prev_box = boxes[sub_line[-1]] + # If distance between boxes is lower than paragraph break, same sub-line + if (boxes[i, 0] - prev_box[2]) < self.paragraph_break: + horiz_break = False + + if horiz_break: + lines.append(sub_line) + sub_line = [] + + sub_line.append(i) + lines.append(sub_line) + + return lines + + def _resolve_lines(self, boxes: np.ndarray) -> List[List[int]]: + """Order boxes to group them in lines Args: boxes: bounding boxes of shape (N, 4) - idxs: indices of ordered boxes of shape (N,) Returns: nested list of box indices """ + # Compute median for boxes heights + y_med = np.median(boxes[:, 3] - boxes[:, 1]) + # Sort boxes + idxs = (boxes[:, 0] + 2 * boxes[:, 3] / y_med).argsort() - # Try to arrange them in lines lines = [] - # Add the first word anyway - words: List[int] = [idxs[0]] + words = [idxs[0]] # Assign the top-left word to the first line + # Define a mean y-center for the line + y_center_sum = boxes[idxs[0]][[1, 3]].mean() + for idx in idxs[1:]: - line_break = True + vert_break = True - prev_box = boxes[words[-1]] - # Reduced vertical diff - if boxes[idx, 1] < prev_box[[1, 3]].mean(): - # Words horizontally ordered and close - if (boxes[idx, 0] - prev_box[2]) < self.paragraph_break: - line_break = False + # If y-center of the box is close enough to mean y-center of the line, same line + if abs(boxes[idx][[1, 3]].mean() - y_center_sum / len(words)) < y_med / 2: + vert_break = False - if line_break: - lines.append(words) + if vert_break: + # Compute sub-lines (horizontal split) + lines.extend(self._resolve_sub_lines(boxes, words)) words = [] + y_center_sum = 0 words.append(idx) + y_center_sum += boxes[idx][[1, 3]].mean() - # Use the remaining words to form the last line + # Use the remaining words to form the last(s) line(s) if len(words) > 0: - lines.append(words) + # Compute sub-lines (horizontal split) + lines.extend(self._resolve_sub_lines(boxes, words)) return lines @@ -148,15 +187,12 @@ def _build_blocks(self, boxes: np.ndarray, char_sequences: List[str]) -> List[Bl if boxes.shape[0] == 0: return [] - # Sort bounding boxes from top to bottom, left to right - idxs = self._sort_boxes(boxes[:, :4]) - # Decide whether we try to form lines if self.resolve_lines: - lines = self._resolve_lines(boxes[:, :4], idxs) + lines = self._resolve_lines(boxes[:, :4]) else: - # One line for all words - lines = [idxs] + # Sort bounding boxes, one line for all boxes + lines = [self._sort_boxes(boxes[:, :4])] # No automatic line grouping yet --> 1 block for all lines blocks = [
diff --git a/test/test_models.py b/test/test_models.py --- a/test/test_models.py +++ b/test/test_models.py @@ -67,7 +67,7 @@ def test_documentbuilder(): assert len(out.pages[0].blocks) == 0 # Repr - assert repr(doc_builder) == "DocumentBuilder(resolve_lines=True, paragraph_break=0.15)" + assert repr(doc_builder) == "DocumentBuilder(resolve_lines=True, paragraph_break=0.035)" @pytest.mark.parametrize( @@ -76,7 +76,7 @@ def test_documentbuilder(): [[[0, 0.5, 0.1, 0.6], [0, 0.3, 0.2, 0.4], [0, 0, 0.1, 0.1]], [2, 1, 0]], # vertical [[[0.7, 0.5, 0.85, 0.6], [0.2, 0.3, 0.4, 0.4], [0, 0, 0.1, 0.1]], [2, 1, 0]], # diagonal [[[0, 0.5, 0.1, 0.6], [0.15, 0.5, 0.25, 0.6], [0.5, 0.5, 0.6, 0.6]], [0, 1, 2]], # same line, 2p - [[[0, 0.5, 0.1, 0.6], [0.2, 0.48, 0.35, 0.58], [0.8, 0.52, 0.9, 0.63]], [0, 1, 2]], # ~same line + [[[0, 0.5, 0.1, 0.6], [0.2, 0.49, 0.35, 0.59], [0.8, 0.52, 0.9, 0.63]], [0, 1, 2]], # ~same line [[[0, 0.3, 0.4, 0.45], [0.5, 0.28, 0.75, 0.42], [0, 0.45, 0.1, 0.55]], [0, 1, 2]], # 2 lines [[[0, 0.3, 0.4, 0.35], [0.75, 0.28, 0.95, 0.42], [0, 0.45, 0.1, 0.55]], [0, 1, 2]], # 2 lines ], @@ -88,20 +88,20 @@ def test_sort_boxes(input_boxes, sorted_idxs): @pytest.mark.parametrize( - "input_boxes, sorted_idxs, lines", + "input_boxes, lines", [ - [[[0, 0.5, 0.1, 0.6], [0, 0.3, 0.2, 0.4], [0, 0, 0.1, 0.1]], [2, 1, 0], [[2], [1], [0]]], # vertical - [[[0.7, 0.5, 0.85, 0.6], [0.2, 0.3, 0.4, 0.4], [0, 0, 0.1, 0.1]], [2, 1, 0], [[2], [1], [0]]], # diagonal - [[[0, 0.5, 0.1, 0.6], [0.15, 0.5, 0.25, 0.6], [0.5, 0.5, 0.6, 0.6]], [0, 1, 2], [[0, 1], [2]]], # same line, 2p - [[[0, 0.5, 0.1, 0.6], [0.2, 0.48, 0.35, 0.58], [0.8, 0.52, 0.9, 0.63]], [0, 1, 2], [[0, 1], [2]]], # ~same line - [[[0, 0.3, 0.4, 0.45], [0.5, 0.28, 0.75, 0.42], [0, 0.45, 0.1, 0.55]], [0, 1, 2], [[0, 1], [2]]], # 2 lines - [[[0, 0.3, 0.4, 0.35], [0.75, 0.28, 0.95, 0.42], [0, 0.45, 0.1, 0.55]], [0, 1, 2], [[0], [1], [2]]], # 2 lines + [[[0, 0.5, 0.1, 0.6], [0, 0.3, 0.2, 0.4], [0, 0, 0.1, 0.1]], [[2], [1], [0]]], # vertical + [[[0.7, 0.5, 0.85, 0.6], [0.2, 0.3, 0.4, 0.4], [0, 0, 0.1, 0.1]], [[2], [1], [0]]], # diagonal + [[[0, 0.5, 0.14, 0.6], [0.15, 0.5, 0.25, 0.6], [0.5, 0.5, 0.6, 0.6]], [[0, 1], [2]]], # same line, 2p + [[[0, 0.5, 0.18, 0.6], [0.2, 0.48, 0.35, 0.58], [0.8, 0.52, 0.9, 0.63]], [[0, 1], [2]]], # ~same line + [[[0, 0.3, 0.48, 0.45], [0.5, 0.28, 0.75, 0.42], [0, 0.45, 0.1, 0.55]], [[0, 1], [2]]], # 2 lines + [[[0, 0.3, 0.4, 0.35], [0.75, 0.28, 0.95, 0.42], [0, 0.45, 0.1, 0.55]], [[0], [1], [2]]], # 2 lines ], ) -def test_resolve_lines(input_boxes, sorted_idxs, lines): +def test_resolve_lines(input_boxes, lines): doc_builder = models.DocumentBuilder() - assert doc_builder._resolve_lines(np.asarray(input_boxes), np.asarray(sorted_idxs)) == lines + assert doc_builder._resolve_lines(np.asarray(input_boxes)) == lines def test_ocrpredictor(mock_pdf, test_detectionpredictor, test_recognitionpredictor): # noqa: F811
[documents] improve line detection An OCR predictor must detect lines, and our current version is too weak: - many lines overlap - some lines stop in the middle of a dense block whereas other lines are kind of "bridging" between separated blocks. ![line11](https://user-images.githubusercontent.com/70526046/116210562-465bc980-a743-11eb-8806-80afa34863dd.png)
2021-04-27T15:45:47
mindee/doctr
237
mindee__doctr-237
[ "232" ]
7642d4bb0fca30def4d9af2c5d8a9d2d73713112
diff --git a/demo/app.py b/demo/app.py --- a/demo/app.py +++ b/demo/app.py @@ -48,7 +48,7 @@ def main(): uploaded_file = st.sidebar.file_uploader("Upload files", type=['pdf', 'png', 'jpeg', 'jpg']) if uploaded_file is not None: if uploaded_file.name.endswith('.pdf'): - doc = DocumentFile.from_pdf(uploaded_file.read()).as_images() + doc = DocumentFile.from_pdf(uploaded_file.read()).as_images(output_size=(1024, 1024)) else: doc = DocumentFile.from_images(uploaded_file.read()) cols[0].image(doc[0], "First page", use_column_width=True) diff --git a/doctr/documents/reader.py b/doctr/documents/reader.py --- a/doctr/documents/reader.py +++ b/doctr/documents/reader.py @@ -97,7 +97,8 @@ def convert_page_to_numpy( Args: page: the page of a file read with PyMuPDF - output_size: the expected output size of each page in format H x W + output_size: the expected output size of each page in format H x W. Default goes to 840 x 595 for A4 pdf, + if you want to increase the resolution while preserving the original A4 aspect ratio can pass (1024, 726) rgb_output: whether the output ndarray channel order should be RGB instead of BGR. Returns: diff --git a/scripts/analyze.py b/scripts/analyze.py --- a/scripts/analyze.py +++ b/scripts/analyze.py @@ -21,9 +21,8 @@ def main(args): model = ocr_predictor(args.detection, args.recognition, pretrained=True) - if args.path.endswith(".pdf"): - doc = DocumentFile.from_pdf(args.path).as_images() + doc = DocumentFile.from_pdf(args.path).as_images(output_size=(1024, 1024)) else: doc = DocumentFile.from_images(args.path)
[document] Check integrity of PDF --> img conversion with default DPI The current PDF reading implies a conversion to an image. As we are using the default args for this conversion, the DPI value might be low. We need to check that the default parameter is not bringing about performance issues due to low resolution rendering.
2021-05-04T15:52:49
mindee/doctr
240
mindee__doctr-240
[ "232" ]
0de02610a64b26df551bb1d5dcc05aa063ad5890
diff --git a/doctr/documents/reader.py b/doctr/documents/reader.py --- a/doctr/documents/reader.py +++ b/doctr/documents/reader.py @@ -10,7 +10,7 @@ from weasyprint import HTML from typing import List, Tuple, Optional, Any, Union, Sequence -__all__ = ['read_pdf', 'read_img', 'read_html', 'DocumentFile'] +__all__ = ['read_pdf', 'read_img', 'read_html', 'DocumentFile', 'PDF'] AbstractPath = Union[str, Path] @@ -92,6 +92,7 @@ def convert_page_to_numpy( page: fitz.fitz.Page, output_size: Optional[Tuple[int, int]] = None, rgb_output: bool = True, + default_scales: Tuple[float, float] = (2, 2), ) -> np.ndarray: """Convert a fitz page to a numpy-formatted image @@ -100,17 +101,21 @@ def convert_page_to_numpy( output_size: the expected output size of each page in format H x W. Default goes to 840 x 595 for A4 pdf, if you want to increase the resolution while preserving the original A4 aspect ratio can pass (1024, 726) rgb_output: whether the output ndarray channel order should be RGB instead of BGR. + default_scales: spatial scaling to be applied when output_size is not specified where (1, 1) + corresponds to 72 dpi rendering. Returns: the rendered image in numpy format """ - transform_matrix = None - # If no output size is specified, keep the origin one if output_size is not None: scales = (output_size[1] / page.MediaBox[2], output_size[0] / page.MediaBox[3]) - transform_matrix = fitz.Matrix(*scales) + else: + # Default 72 DPI (scales of (1, 1)) is unnecessarily low + scales = default_scales + + transform_matrix = fitz.Matrix(*scales) # Generate the pixel map using the transformation matrix stream = page.getPixmap(matrix=transform_matrix).getImageData()
diff --git a/test/test_documents_reader.py b/test/test_documents_reader.py --- a/test/test_documents_reader.py +++ b/test/test_documents_reader.py @@ -10,18 +10,23 @@ def test_convert_page_to_numpy(mock_pdf): pdf = fitz.open(mock_pdf) # Check correct read - rgb_page = reader.convert_page_to_numpy(pdf[0]) + rgb_page = reader.convert_page_to_numpy(pdf[0], default_scales=(1, 1)) assert isinstance(rgb_page, np.ndarray) assert rgb_page.shape == (792, 612, 3) # Check channel order - bgr_page = reader.convert_page_to_numpy(pdf[0], rgb_output=False) + bgr_page = reader.convert_page_to_numpy(pdf[0], default_scales=(1, 1), rgb_output=False) assert np.all(bgr_page == rgb_page[..., ::-1]) - # Check rescaling + # Check resizing resized_page = reader.convert_page_to_numpy(pdf[0], output_size=(396, 306)) assert resized_page.shape == (396, 306, 3) + # Check rescaling + rgb_page = reader.convert_page_to_numpy(pdf[0]) + assert isinstance(rgb_page, np.ndarray) + assert rgb_page.shape == (1584, 1224, 3) + def _check_doc_content(doc_tensors, num_pages): # 1 doc of 8 pages
[document] Check integrity of PDF --> img conversion with default DPI The current PDF reading implies a conversion to an image. As we are using the default args for this conversion, the DPI value might be low. We need to check that the default parameter is not bringing about performance issues due to low resolution rendering.
As per https://github.com/mindee/doctr/pull/237#issuecomment-832585154, we should update the default transformation for pdf reading in https://github.com/mindee/doctr/blob/main/doctr/documents/reader.py#L108 The default transformation matrix (None) yields a low DPI for page rendering. Doubling this while preserving the aspect ratio by default, would yield potentially better results. I'll open a PR to handle this!
2021-05-05T11:08:27
mindee/doctr
243
mindee__doctr-243
[ "27" ]
fb24851c5b128986c3a5d0584928543a47f63a66
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -40,7 +40,7 @@ "numpy>=1.16.0", "scipy>=1.4.0", "opencv-python>=4.2", - "tensorflow>=2.3.0", + "tensorflow>=2.4.0", "PyMuPDF>=1.16.0,<1.18.11", "pyclipper>=1.2.0", "shapely>=1.6.0",
diff --git a/test/test_models_export.py b/test/test_models_export.py --- a/test/test_models_export.py +++ b/test/test_models_export.py @@ -40,7 +40,4 @@ def test_quantize_model(mock_model): def test_export_sizes(test_convert_to_tflite, test_convert_to_fp16, test_quantize_model): assert sys.getsizeof(test_convert_to_tflite) > sys.getsizeof(test_convert_to_fp16) - if tf.__version__ < "2.4.0": - assert sys.getsizeof(test_convert_to_fp16) >= sys.getsizeof(test_quantize_model) - else: - assert sys.getsizeof(test_convert_to_fp16) > sys.getsizeof(test_quantize_model) + assert sys.getsizeof(test_convert_to_fp16) > sys.getsizeof(test_quantize_model)
Pb: unitest text_export_size not passing on tf 2.3.1 Unitest text_export_size not OK locally on tf 2.3.1 : ``` def test_export_sizes(test_convert_to_tflite, test_convert_to_fp16, test_quantize_model): assert sys.getsizeof(test_convert_to_tflite) > sys.getsizeof(test_convert_to_fp16) > assert sys.getsizeof(test_convert_to_fp16) > sys.getsizeof(test_quantize_model) E AssertionError: assert 3041 > 3041 ```
I opened an issue about this on TF repo: https://github.com/tensorflow/tensorflow/issues/46922 Let's make a conditional test while this gets investigated by the authors :ok_hand: Since the unittest has been adapted by #62, I'm moving this to next milestone considering this requires feedback from the TF team
2021-05-06T09:12:28
mindee/doctr
300
mindee__doctr-300
[ "215" ]
820634baafe9c48821fba8a4aedd0feef56db6f8
diff --git a/doctr/models/recognition/__init__.py b/doctr/models/recognition/__init__.py --- a/doctr/models/recognition/__init__.py +++ b/doctr/models/recognition/__init__.py @@ -2,3 +2,5 @@ from .crnn import * from .sar import * from .zoo import * +from .transformer import * +from .master import * diff --git a/doctr/models/recognition/master.py b/doctr/models/recognition/master.py new file mode 100644 --- /dev/null +++ b/doctr/models/recognition/master.py @@ -0,0 +1,277 @@ +# Copyright (C) 2021, Mindee. + +# This program is licensed under the Apache License version 2. +# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. + +import tensorflow as tf +from tensorflow.keras import layers, Sequential +from typing import Tuple + +from .core import RecognitionModel +from ..backbones.resnet import ResnetStage +from ..utils import conv_sequence +from .transformer import Decoder, positional_encoding, create_look_ahead_mask, create_padding_mask + +__all__ = ['MASTER'] + + +class MAGC(layers.Layer): + + """Implements the Multi-Aspect Global Context Attention, as described in + <https://arxiv.org/pdf/1910.02562.pdf>`_. + + Args: + inplanes: input channels + headers: number of headers to split channels + att_scale: if True, re-scale attention to counteract the variance distibutions + **kwargs + """ + + def __init__( + self, + inplanes: int, + headers: int = 1, + att_scale: bool = False, + **kwargs + ) -> None: + super().__init__(**kwargs) + + self.headers = headers # h + self.inplanes = inplanes # C + self.att_scale = att_scale + + self.single_header_inplanes = int(inplanes / headers) # C / h + + self.conv_mask = tf.keras.layers.Conv2D( + filters=1, + kernel_size=1, + kernel_initializer=tf.initializers.he_normal() + ) + + self.transform = tf.keras.Sequential( + [ + tf.keras.layers.Conv2D( + filters=self.inplanes, + kernel_size=1, + kernel_initializer=tf.initializers.he_normal() + ), + tf.keras.layers.LayerNormalization([1, 2, 3]), + tf.keras.layers.ReLU(), + tf.keras.layers.Conv2D( + filters=self.inplanes, + kernel_size=1, + kernel_initializer=tf.initializers.he_normal() + ), + ], + name='transform' + ) + + @tf.function + def context_modeling(self, inputs: tf.Tensor) -> tf.Tensor: + b, h, w, c = (tf.shape(inputs)[i] for i in range(4)) + + # B, H, W, C -->> B*h, H, W, C/h + x = tf.reshape(inputs, shape=(b, h, w, self.headers, self.single_header_inplanes)) + x = tf.transpose(x, perm=(0, 3, 1, 2, 4)) + x = tf.reshape(x, shape=(b * self.headers, h, w, self.single_header_inplanes)) + + # Compute shorcut + shortcut = x + # B*h, 1, H*W, C/h + shortcut = tf.reshape(shortcut, shape=(b * self.headers, 1, h * w, self.single_header_inplanes)) + # B*h, 1, C/h, H*W + shortcut = tf.transpose(shortcut, perm=[0, 1, 3, 2]) + + # Compute context mask + # B*h, H, W, 1, + context_mask = self.conv_mask(x) + # B*h, 1, H*W, 1 + context_mask = tf.reshape(context_mask, shape=(b * self.headers, 1, h * w, 1)) + # scale variance + if self.att_scale and self.headers > 1: + context_mask = context_mask / tf.sqrt(self.single_header_inplanes) + # B*h, 1, H*W, 1 + context_mask = tf.keras.activations.softmax(context_mask, axis=2) + + # Compute context + # B*h, 1, C/h, 1 + context = tf.matmul(shortcut, context_mask) + context = tf.reshape(context, shape=(b, 1, c, 1)) + # B, 1, 1, C + context = tf.transpose(context, perm=(0, 1, 3, 2)) + # Set shape to resolve shape when calling this module in the Sequential MAGCResnet + batch, chan = inputs.get_shape().as_list()[0], inputs.get_shape().as_list()[-1] + context.set_shape([batch, 1, 1, chan]) + return context + + def call(self, inputs: tf.Tensor, **kwargs) -> tf.Tensor: + # Context modeling: B, H, W, C -> B, 1, 1, C + context = self.context_modeling(inputs) + # Transform: B, 1, 1, C -> B, 1, 1, C + transformed = self.transform(context) + return inputs + transformed + + +class MAGCResnet(Sequential): + + """Implements the modified resnet with MAGC layers, as described in paper. + + Args: + headers: number of header to split channels in MAGC layers + input_shape: shape of the model input (without batch dim) + """ + + def __init__( + self, + headers: int = 1, + input_shape: Tuple[int, int, int] = (48, 160, 3), + ) -> None: + _layers = [ + # conv_1x + *conv_sequence(out_channels=64, activation='relu', bn=True, kernel_size=3, input_shape=input_shape), + *conv_sequence(out_channels=128, activation='relu', bn=True, kernel_size=3), + layers.MaxPooling2D((2, 2), (2, 2)), + # conv_2x + ResnetStage(num_blocks=1, output_channels=256), + MAGC(inplanes=256, headers=headers, att_scale=True), + *conv_sequence(out_channels=256, activation='relu', bn=True, kernel_size=3), + layers.MaxPooling2D((2, 2), (2, 2)), + # conv_3x + ResnetStage(num_blocks=2, output_channels=512), + MAGC(inplanes=512, headers=headers, att_scale=True), + *conv_sequence(out_channels=512, activation='relu', bn=True, kernel_size=3), + layers.MaxPooling2D((2, 1), (2, 1)), + # conv_4x + ResnetStage(num_blocks=5, output_channels=512), + MAGC(inplanes=512, headers=headers, att_scale=True), + *conv_sequence(out_channels=512, activation='relu', bn=True, kernel_size=3), + # conv_5x + ResnetStage(num_blocks=3, output_channels=512), + MAGC(inplanes=512, headers=headers, att_scale=True), + *conv_sequence(out_channels=512, activation='relu', bn=True, kernel_size=3), + ] + super().__init__(_layers) + + +class MASTER(RecognitionModel): + + """Implements MASTER as described in paper: <https://arxiv.org/pdf/1910.02562.pdf>`_. + Implementation based on the official TF implementation: <https://github.com/jiangxiluning/MASTER-TF>`_. + + Args: + vocab: vocabulary, (without EOS, SOS, PAD) + d_model: d parameter for the transformer decoder + headers: headers for the MAGC module + dff: depth of the pointwise feed-forward layer + num_heads: number of heads for the mutli-head attention module + num_layers: number of decoder layers to stack + max_length: maximum length of character sequence handled by the model + input_size: size of the image inputs + """ + + def __init__( + self, + vocab: str, + d_model: int = 512, + headers: int = 1, + dff: int = 2048, + num_heads: int = 8, + num_layers: int = 3, + max_length: int = 50, + input_size: tuple = (48, 160, 3), + ) -> None: + super().__init__(vocab=vocab) + + self.input_size = input_size + self.max_length = max_length + self.vocab_size = len(vocab) + + self.feature_extractor = MAGCResnet(headers=headers, input_shape=input_size) + self.seq_embedding = layers.Embedding(self.vocab_size + 1, d_model) # One additional class for EOS + + self.decoder = Decoder( + num_layers=num_layers, + d_model=d_model, + num_heads=num_heads, + dff=dff, + vocab_size=self.vocab_size, + maximum_position_encoding=max_length, + ) + self.feature_pe = positional_encoding(input_size[0] * input_size[1], d_model) + self.linear = layers.Dense(self.vocab_size + 1, kernel_initializer=tf.initializers.he_uniform()) + + @tf.function + def make_mask(self, target: tf.Tensor) -> tf.Tensor: + look_ahead_mask = create_look_ahead_mask(tf.shape(target)[1]) + target_padding_mask = create_padding_mask(target, self.vocab_size) # Pad with EOS + combined_mask = tf.maximum(target_padding_mask, look_ahead_mask) + return combined_mask + + def call(self, inputs: tf.Tensor, labels: tf.Tensor, **kwargs) -> tf.Tensor: + """Call function for training + + Args: + inputs: images + labels: tensor of labels + + Return: + Computed logits + """ + # Encode + feature = self.feature_extractor(inputs, **kwargs) + b, h, w, c = (tf.shape(feature)[i] for i in range(4)) + feature = tf.reshape(feature, shape=(b, h * w, c)) + encoded = feature + self.feature_pe[:, :h * w, :] + + tgt_mask = self.make_mask(labels) + + output = self.decoder(labels, encoded, tgt_mask, None, training=True) + logits = self.linear(output) + + return logits + + @tf.function + def decode(self, inputs: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: + """Decode function for prediction + + Args: + inputs: images to predict + + Return: + A Tuple of tf.Tensor: predictions, logits + """ + + feature = self.feature_extractor(inputs, training=False) + b, h, w, c = (tf.shape(feature)[i] for i in range(4)) + + feature = tf.reshape(feature, shape=(b, h * w, c)) + encoded = feature + self.feature_pe[:, :h * w, :] + + max_len = tf.constant(self.max_length, dtype=tf.int32) + start_symbol = tf.constant(self.vocab_size + 1, dtype=tf.int32) # SOS (EOS = vocab_size) + padding_symbol = tf.constant(self.vocab_size, dtype=tf.int32) + + ys = tf.fill(dims=(b, max_len - 1), value=padding_symbol) + start_vector = tf.fill(dims=(b, 1), value=start_symbol) + ys = tf.concat([start_vector, ys], axis=-1) + + final_logits = tf.zeros(shape=(b, max_len - 1, self.vocab_size + 1), dtype=tf.float32) # don't fgt EOS + # max_len = len + 2 + for i in range(self.max_length - 1): + ys_mask = self.make_mask(ys) + output = self.decoder(ys, encoded, ys_mask, None, training=False) + logits = self.linear(output) + prob = tf.nn.softmax(logits, axis=-1) + next_word = tf.argmax(prob, axis=-1, output_type=ys.dtype) + + # ys.shape = B, T + i_mesh, j_mesh = tf.meshgrid(tf.range(b), tf.range(max_len), indexing='ij') + indices = tf.stack([i_mesh[:, i + 1], j_mesh[:, i + 1]], axis=1) + + ys = tf.tensor_scatter_nd_update(ys, indices, next_word[:, i + 1]) + + if i == (self.max_length - 2): + final_logits = logits + + # ys predictions of shape B x max_length, final_logits of shape B x max_length x vocab_size + 1 + return ys, final_logits diff --git a/doctr/models/recognition/transformer.py b/doctr/models/recognition/transformer.py new file mode 100644 --- /dev/null +++ b/doctr/models/recognition/transformer.py @@ -0,0 +1,240 @@ +# Copyright (C) 2021, Mindee. + +# This program is licensed under the Apache License version 2. +# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. + +# This module 'transformer.py' is 100% inspired from this Tensorflow tutorial: +# https://www.tensorflow.org/text/tutorials/transformer + + +from typing import Tuple + +import tensorflow as tf +import numpy as np + + +__all__ = ['Decoder', 'positional_encoding', 'create_look_ahead_mask', 'create_padding_mask'] + + +def get_angles(pos: np.array, i: np.array, d_model: int = 512) -> np.array: + """This function compute the 2D array of angles for sinusoidal positional encoding. + + Args: + pos: range of positions to encode + i: range of depth to encode positions + d_model: depth parameter of the model + + Returns: + 2D array of angles, len(pos) x len(i) + """ + angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model)) + return pos * angle_rates + + +def positional_encoding(position: int, d_model: int = 512) -> tf.Tensor: + """This function computes the 2D positional encoding of the position, on a depth d_model + + Args: + position: Number of positions to encode + d_model: depth of the encoding + + Returns: + 2D positional encoding as described in Transformer paper. + """ + angle_rads = get_angles( + np.arange(position)[:, np.newaxis], + np.arange(d_model)[np.newaxis, :], + d_model, + ) + # apply sin to even indices in the array; 2i + angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2]) + # apply cos to odd indices in the array; 2i+1 + angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2]) + pos_encoding = angle_rads[np.newaxis, ...] + return tf.cast(pos_encoding, dtype=tf.float32) + + [email protected] +def create_padding_mask(seq: tf.Tensor, padding: int = 0) -> tf.Tensor: + seq = tf.cast(tf.math.equal(seq, padding), tf.float32) + # add extra dimensions to add the padding to the attention logits. + return seq[:, tf.newaxis, tf.newaxis, :] # (batch_size, 1, 1, seq_len) + + [email protected] +def create_look_ahead_mask(size: int) -> tf.Tensor: + mask = 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0) + return mask # (seq_len, seq_len) + + [email protected] +def scaled_dot_product_attention( + q: tf.Tensor, k: tf.Tensor, v: tf.Tensor, mask: tf.Tensor +) -> Tuple[tf.Tensor, tf.Tensor]: + + """Calculate the attention weights. + q, k, v must have matching leading dimensions. + k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v. + The mask has different shapes depending on its type(padding or look ahead) + but it must be broadcastable for addition. + Args: + q: query shape == (..., seq_len_q, depth) + k: key shape == (..., seq_len_k, depth) + v: value shape == (..., seq_len_v, depth_v) + mask: Float tensor with shape broadcastable to (..., seq_len_q, seq_len_k). Defaults to None. + Returns: + output, attention_weights + """ + + matmul_qk = tf.matmul(q, k, transpose_b=True) # (..., seq_len_q, seq_len_k) + # scale matmul_qk + dk = tf.cast(tf.shape(k)[-1], tf.float32) + scaled_attention_logits = matmul_qk / tf.math.sqrt(dk) + # add the mask to the scaled tensor. + if mask is not None: + scaled_attention_logits += (mask * -1e9) + # softmax is normalized on the last axis (seq_len_k) so that the scores + # add up to 1. + attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, seq_len_k) + output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v) + return output + + +class MultiHeadAttention(tf.keras.layers.Layer): + + def __init__(self, d_model: int = 512, num_heads: int = 8) -> None: + super(MultiHeadAttention, self).__init__() + self.num_heads = num_heads + self.d_model = d_model + + assert d_model % self.num_heads == 0 + + self.depth = d_model // self.num_heads + + self.wq = tf.keras.layers.Dense(d_model, kernel_initializer=tf.initializers.he_uniform()) + self.wk = tf.keras.layers.Dense(d_model, kernel_initializer=tf.initializers.he_uniform()) + self.wv = tf.keras.layers.Dense(d_model, kernel_initializer=tf.initializers.he_uniform()) + + self.dense = tf.keras.layers.Dense(d_model, kernel_initializer=tf.initializers.he_uniform()) + + def split_heads(self, x: tf.Tensor, batch_size: int) -> tf.Tensor: + """Split the last dimension into (num_heads, depth). + Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth) + """ + x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth)) + return tf.transpose(x, perm=[0, 2, 1, 3]) + + def call(self, v: tf.Tensor, k: tf.Tensor, q: tf.Tensor, mask: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: + batch_size = tf.shape(q)[0] + + q = self.wq(q) # (batch_size, seq_len, d_model) + k = self.wk(k) # (batch_size, seq_len, d_model) + v = self.wv(v) # (batch_size, seq_len, d_model) + + q = self.split_heads(q, batch_size) # (batch_size, num_heads, seq_len_q, depth) + k = self.split_heads(k, batch_size) # (batch_size, num_heads, seq_len_k, depth) + v = self.split_heads(v, batch_size) # (batch_size, num_heads, seq_len_v, depth) + + # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth) + # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k) + scaled_attention = scaled_dot_product_attention(q, k, v, mask) + + scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) # (batch, seq_len_q, num_heads, depth) + + concat_attention = tf.reshape(scaled_attention, + (batch_size, -1, self.d_model)) # (batch_size, seq_len_q, d_model) + + output = self.dense(concat_attention) # (batch_size, seq_len_q, d_model) + + return output + + +def point_wise_feed_forward_network(d_model: int = 512, dff: int = 2048) -> tf.keras.Sequential: + return tf.keras.Sequential([ + tf.keras.layers.Dense( + dff, activation='relu', kernel_initializer=tf.initializers.he_uniform() + ), # (batch, seq_len, dff) + tf.keras.layers.Dense(d_model, kernel_initializer=tf.initializers.he_uniform()) # (batch, seq_len, d_model) + ]) + + +class DecoderLayer(tf.keras.layers.Layer): + + def __init__(self, d_model: int = 512, num_heads: int = 8, dff: int = 2048) -> None: + super(DecoderLayer, self).__init__() + + self.mha1 = MultiHeadAttention(d_model, num_heads) + self.mha2 = MultiHeadAttention(d_model, num_heads) + + self.ffn = point_wise_feed_forward_network(d_model, dff) + + self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6) + self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6) + self.layernorm3 = tf.keras.layers.LayerNormalization(epsilon=1e-6) + + def call( + self, + x: tf.Tensor, + enc_output: tf.Tensor, + training: bool, + look_ahead_mask: tf.Tensor, + padding_mask: tf.Tensor + ) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor]: + # enc_output.shape == (batch_size, input_seq_len, d_model) + + attn1 = self.mha1(x, x, x, look_ahead_mask) # (batch_size, target_seq_len, d_model) + out1 = self.layernorm1(attn1 + x) + + attn2 = self.mha2(enc_output, enc_output, out1, padding_mask) # (batch_size, target_seq_len, d_model) + out2 = self.layernorm2(attn2 + out1) # (batch_size, target_seq_len, d_model) + + ffn_output = self.ffn(out2) # (batch_size, target_seq_len, d_model) + out3 = self.layernorm3(ffn_output + out2) # (batch_size, target_seq_len, d_model) + + return out3 + + +class Decoder(tf.keras.layers.Layer): + + def __init__( + self, + num_layers: int = 3, + d_model: int = 512, + num_heads: int = 8, + dff: int = 2048, + vocab_size: int = 120, + maximum_position_encoding: int = 50, + ) -> None: + super(Decoder, self).__init__() + + self.d_model = d_model + self.num_layers = num_layers + + self.embedding = tf.keras.layers.Embedding(vocab_size + 2, d_model) # 2 more classes EOS/SOS + self.pos_encoding = positional_encoding(maximum_position_encoding, d_model) + + self.dec_layers = [DecoderLayer(d_model, num_heads, dff) + for _ in range(num_layers)] + + def call( + self, + x: tf.Tensor, + enc_output: tf.Tensor, + look_ahead_mask: tf.Tensor, + padding_mask: tf.Tensor, + training: bool = False, + ) -> Tuple[tf.Tensor, tf.Tensor]: + + seq_len = tf.shape(x)[1] + + x = self.embedding(x) # (batch_size, target_seq_len, d_model) + x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32)) + x += self.pos_encoding[:, :seq_len, :] + + for i in range(self.num_layers): + x = self.dec_layers[i]( + x, enc_output, training, look_ahead_mask, padding_mask + ) + + # x.shape == (batch_size, target_seq_len, d_model) + return x
diff --git a/test/test_models_recognition.py b/test/test_models_recognition.py --- a/test/test_models_recognition.py +++ b/test/test_models_recognition.py @@ -103,3 +103,19 @@ def test_recognition_zoo(arch_name): def test_recognition_zoo_error(): with pytest.raises(ValueError): _ = recognition.zoo.recognition_predictor("my_fancy_model", pretrained=False) + + +def test_master(mock_vocab, max_len=50, batch_size=16): + master = recognition.MASTER(vocab=mock_vocab, d_model=512, dff=512, num_heads=2, input_size=(48, 160, 3)) + input_tensor = tf.random.uniform(shape=[batch_size, 48, 160, 3], minval=0, maxval=1) + mock_labels = tf.cast( + len(mock_vocab) * tf.random.uniform(shape=[batch_size, max_len], minval=0, maxval=1), tf.int32 + ) + logits = master(input_tensor, mock_labels) + assert isinstance(logits, tf.Tensor) + assert logits.shape == (batch_size, max_len, 1 + len(mock_vocab)) # 1 more for EOS + prediction, logits = master.decode(input_tensor) + assert isinstance(prediction, tf.Tensor) + assert isinstance(logits, tf.Tensor) + assert prediction.shape == (batch_size, max_len) + assert logits.shape == (batch_size, max_len, 1 + len(mock_vocab))
[models] Implement HRGAN or MASTER [This paper](https://arxiv.org/pdf/1904.01375v5.pdf) suggests a new architecture: Holistic Representation Guided Attention Network for text recognition model, inspired from transformers, which oustands SAR both in accuracy & speed. We should implement this model, but the impressive speed results should be handled carefully (X8 speed compared to SAR), since the experiments are conducted on a GPU, and this model is highly parallelable (no recurrency). Is this new model so fast on CPU ?
[This one](https://arxiv.org/pdf/1910.02562.pdf) seems to be even stronger
2021-06-09T15:46:39
mindee/doctr
369
mindee__doctr-369
[ "234" ]
c18025b369c4013044bff1171b5049f2a9996897
diff --git a/demo/app.py b/demo/app.py --- a/demo/app.py +++ b/demo/app.py @@ -33,10 +33,14 @@ def main(): st.title("DocTR: Document Text Recognition") # For newline st.write('\n') + # Instructions + st.markdown("*Hint: click on the top-right corner of an image to enlarge it!*") # Set the columns - cols = st.beta_columns((1, 1)) - cols[0].subheader("Input document (first page)") - cols[1].subheader("Raw heatmap (segmentation task)") + cols = st.beta_columns((1, 1, 1, 1)) + cols[0].subheader("Input page") + cols[1].subheader("Segmentation heatmap") + cols[2].subheader("OCR output") + cols[3].subheader("Page reconstitution") # Sidebar # File selection @@ -50,7 +54,8 @@ def main(): doc = DocumentFile.from_pdf(uploaded_file.read()).as_images(output_size=(1024, 1024)) else: doc = DocumentFile.from_images(uploaded_file.read()) - cols[0].image(doc[0], width=640) + page_idx = st.sidebar.selectbox("Page selection", [idx + 1 for idx in range(len(doc))]) - 1 + cols[0].image(doc[page_idx]) # Model selection st.sidebar.title("Model selection") @@ -60,7 +65,7 @@ def main(): # For newline st.sidebar.write('\n') - if st.sidebar.button("Analyze document"): + if st.sidebar.button("Analyze page"): if uploaded_file is None: st.sidebar.write("Please upload a document") @@ -72,11 +77,11 @@ def main(): with st.spinner('Analyzing...'): # Forward the image to the model - processed_batches = predictor.det_predictor.pre_processor(doc) + processed_batches = predictor.det_predictor.pre_processor([doc[page_idx]]) out = predictor.det_predictor.model(processed_batches[0], return_model_output=True, training=False) seg_map = out["out_map"] seg_map = tf.squeeze(seg_map[0, ...], axis=[2]) - seg_map = cv2.resize(seg_map.numpy(), (doc[0].shape[1], doc[0].shape[0]), + seg_map = cv2.resize(seg_map.numpy(), (doc[page_idx].shape[1], doc[page_idx].shape[0]), interpolation=cv2.INTER_LINEAR) # Plot the raw heatmap fig, ax = plt.subplots() @@ -85,15 +90,18 @@ def main(): cols[1].pyplot(fig) # Plot OCR output - out = predictor(doc, training=False) - cols[1].subheader("OCR output") - fig = visualize_page(out.pages[0].export(), doc[0], interactive=False) - cols[1].pyplot(fig) + out = predictor([doc[page_idx]], training=False) + fig = visualize_page(out.pages[0].export(), doc[page_idx], interactive=False) + cols[2].pyplot(fig) # Page reconsitution under input page - cols[0].subheader("Page reconstitution from OCR output") - img = synthetize_page(out.pages[0].export()) - cols[0].image(img, clamp=True, width=640) + page_export = out.pages[0].export() + img = synthetize_page(page_export) + cols[3].image(img, clamp=True) + + # Display JSON + st.markdown("\nHere are your analysis results in JSON format:") + st.json(page_export) if __name__ == '__main__':
[demo] Improve UI for OCR result display For very dense documents, since the predicted text value is plotted statically, there can be some readability issues. We should try to improve this
I would argue that this was solved by #320 But perhaps we should wait for additional feedback on the readability of this new layout, what do you think @charlesmindee?
2021-07-07T16:55:03
mindee/doctr
381
mindee__doctr-381
[ "347" ]
58a3f8d5d59f298716b46cfa6233cf1322e4f3ee
diff --git a/references/detection/train_pytorch.py b/references/detection/train_pytorch.py --- a/references/detection/train_pytorch.py +++ b/references/detection/train_pytorch.py @@ -15,6 +15,7 @@ import torch from torchvision.transforms import Compose, Lambda, Normalize, ColorJitter from torch.utils.data import DataLoader, RandomSampler, SequentialSampler +from torch.optim.lr_scheduler import OneCycleLR, CosineAnnealingLR from contiguous_params import ContiguousParams import wandb @@ -26,7 +27,7 @@ from utils import plot_samples -def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): +def fit_one_epoch(model, train_loader, batch_transforms, optimizer, scheduler, mb): model.train() train_iter = iter(train_loader) # Iterate over the batches of the dataset @@ -42,6 +43,7 @@ def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): optimizer.zero_grad() train_loss.backward() optimizer.step() + scheduler.step() mb.child.comment = f'Training loss: {train_loss.item():.6}' @@ -172,6 +174,11 @@ def main(args): model_params = ContiguousParams([p for p in model.parameters() if p.requires_grad]).contiguous() optimizer = torch.optim.Adam(model_params, args.lr, betas=(0.95, 0.99), eps=1e-6, weight_decay=args.weight_decay) + # Scheduler + if args.sched == 'cosine': + scheduler = CosineAnnealingLR(optimizer, args.epochs * len(train_loader), eta_min=args.lr / 25e4) + elif args.sched == 'onecycle': + scheduler = OneCycleLR(optimizer, args.lr, args.epochs * len(train_loader)) # Training monitoring current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") @@ -201,7 +208,7 @@ def main(args): # Training loop mb = master_bar(range(args.epochs)) for epoch in mb: - fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb) + fit_one_epoch(model, train_loader, batch_transforms, optimizer, scheduler, mb) # Validation loop at the end of each epoch val_loss, recall, precision, mean_iou = evaluate(model, val_loader, batch_transforms, val_metric) if val_loss < min_loss: @@ -253,6 +260,7 @@ def parse_args(): help='Load pretrained parameters before starting the training') parser.add_argument('--rotation', dest='rotation', action='store_true', help='train with rotated bbox') + parser.add_argument('--sched', type=str, default='cosine', help='scheduler to use') args = parser.parse_args() return args diff --git a/references/recognition/train_pytorch.py b/references/recognition/train_pytorch.py --- a/references/recognition/train_pytorch.py +++ b/references/recognition/train_pytorch.py @@ -15,6 +15,7 @@ import torch from torchvision.transforms import Compose, Lambda, Normalize, ColorJitter from torch.utils.data import DataLoader, RandomSampler, SequentialSampler +from torch.optim.lr_scheduler import OneCycleLR, CosineAnnealingLR from contiguous_params import ContiguousParams import wandb from pathlib import Path @@ -27,7 +28,7 @@ from utils import plot_samples -def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): +def fit_one_epoch(model, train_loader, batch_transforms, optimizer, scheduler, mb): model.train() train_iter = iter(train_loader) # Iterate over the batches of the dataset @@ -41,6 +42,7 @@ def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): optimizer.zero_grad() train_loss.backward() optimizer.step() + scheduler.step() mb.child.comment = f'Training loss: {train_loss.item():.6}' @@ -162,6 +164,11 @@ def main(args): model_params = ContiguousParams([p for p in model.parameters() if p.requires_grad]).contiguous() optimizer = torch.optim.Adam(model_params, args.lr, betas=(0.95, 0.99), eps=1e-6, weight_decay=args.weight_decay) + # Scheduler + if args.sched == 'cosine': + scheduler = CosineAnnealingLR(optimizer, args.epochs * len(train_loader), eta_min=args.lr / 25e4) + elif args.sched == 'onecycle': + scheduler = OneCycleLR(optimizer, args.lr, args.epochs * len(train_loader)) # Training monitoring current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") @@ -190,7 +197,7 @@ def main(args): # Training loop mb = master_bar(range(args.epochs)) for epoch in mb: - fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb) + fit_one_epoch(model, train_loader, batch_transforms, optimizer, scheduler, mb) # Validation loop at the end of each epoch val_loss, exact_match, partial_match = evaluate(model, val_loader, batch_transforms, val_metric) @@ -239,6 +246,7 @@ def parse_args(): help='Log to Weights & Biases') parser.add_argument('--pretrained', dest='pretrained', action='store_true', help='Load pretrained parameters before starting the training') + parser.add_argument('--sched', type=str, default='cosine', help='scheduler to use') args = parser.parse_args() return args
[references] Add learning rate scheduler Add learning rate scheduler on both tensorflow and pytorch scripts. - [x] In TensorFlow ExponentialDecay (#360) - [ ] In Pytorch (#381)
2021-07-13T13:03:26
mindee/doctr
384
mindee__doctr-384
[ "89" ]
7f9c305851e47ff93da9ef50b923461fd8009fc5
diff --git a/doctr/utils/visualization.py b/doctr/utils/visualization.py --- a/doctr/utils/visualization.py +++ b/doctr/utils/visualization.py @@ -8,13 +8,14 @@ import matplotlib.patches as patches import mplcursors from PIL import ImageFont, ImageDraw, Image +from copy import deepcopy import numpy as np import cv2 from typing import Tuple, List, Dict, Any, Union, Optional from .common_types import BoundingBox, RotatedBbox -__all__ = ['visualize_page', 'synthetize_page'] +__all__ = ['visualize_page', 'synthetize_page', 'draw_boxes'] def rect_patch( @@ -294,3 +295,34 @@ def synthetize_page( response[ymin:ymax, xmin:xmax, :] = np.array(img) return response + + +def draw_boxes( + boxes: np.ndarray, + image: np.ndarray, + color: Optional[Tuple] = None, + **kwargs +) -> None: + """Draw an array of relative straight boxes on an image + + Args: + boxes: array of relative boxes, of shape (*, 4) + image: np array, float32 or uint8 + """ + h, w = image.shape[:2] + # Convert boxes to absolute coords + _boxes = deepcopy(boxes) + _boxes[:, [0, 2]] *= w + _boxes[:, [1, 3]] *= h + _boxes = _boxes.astype(np.int32) + for box in _boxes.tolist(): + xmin, ymin, xmax, ymax = box + image = cv2.rectangle( + image, + (xmin, ymin), + (xmax, ymax), + color=color if isinstance(color, tuple) else (0, 0, 255), + thickness=2 + ) + plt.imshow(image) + plt.plot(**kwargs)
diff --git a/test/common/test_utils_visualization.py b/test/common/test_utils_visualization.py --- a/test/common/test_utils_visualization.py +++ b/test/common/test_utils_visualization.py @@ -25,3 +25,14 @@ def test_draw_page(): pages = _mock_pages() visualization.synthetize_page(pages[0].export(), draw_proba=True) visualization.synthetize_page(pages[0].export(), draw_proba=False) + + +def test_draw_boxes(): + image = np.ones((256, 256, 3), dtype=np.float32) + boxes = [ + [0.1, 0.1, 0.2, 0.2], + [0.15, 0.15, 0.19, 0.2], # to suppress + [0.5, 0.5, 0.6, 0.55], + [0.55, 0.5, 0.7, 0.55], # to suppress + ] + visualization.draw_boxes(boxes=np.array(boxes), image=image, block=False)
[utils] Add visualization capabilities for independent tasks Visualization is end-to-end for the moment dynamic, but this means that a static version is not currently available, nor that there is a visualization option for text detection or text recognition only. We should discuss and add visualization for the following blocks: - [ ] Text detection: display bounding boxes of detected items over the image - [ ] Text recognition: display the label and confidence in a corner of the crop
2021-07-18T16:38:28
mindee/doctr
393
mindee__doctr-393
[ "387" ]
9ec6b265d278c1a6f78a3205d9eaec195dd8ab1c
diff --git a/doctr/datasets/utils.py b/doctr/datasets/utils.py --- a/doctr/datasets/utils.py +++ b/doctr/datasets/utils.py @@ -6,11 +6,12 @@ import string import unicodedata import numpy as np +from functools import partial from typing import List, Optional, Any from .vocabs import VOCABS -__all__ = ['translate', 'encode_sequence', 'decode_sequence', 'encode_sequences'] +__all__ = ['translate', 'encode_string', 'decode_sequence', 'encode_sequences'] def translate( @@ -47,7 +48,7 @@ def translate( return translated -def encode_sequence( +def encode_string( input_string: str, vocab: str, ) -> List[int]: @@ -74,12 +75,13 @@ def decode_sequence( mapping: vocabulary (string), the encoding is given by the indexing of the character sequence Returns: - A string, decoded from input_array""" + A string, decoded from input_array + """ if not input_array.dtype == np.int_ or input_array.max() >= len(mapping): raise AssertionError("Input must be an array of int, with max less than mapping size") - decoded = ''.join(mapping[idx] for idx in input_array) - return decoded + + return ''.join(map(mapping.__getitem__, input_array)) def encode_sequences( @@ -89,6 +91,7 @@ def encode_sequences( eos: int = -1, sos: Optional[int] = None, pad: Optional[int] = None, + dynamic_seq_length: bool = False, **kwargs: Any, ) -> np.ndarray: """Encode character sequences using a given vocab as mapping @@ -100,6 +103,7 @@ def encode_sequences( eos: encoding of End Of String sos: optional encoding of Start Of String pad: optional encoding for padding. In case of padding, all sequences are followed by 1 EOS then PAD + dynamic_seq_length: if `target_size` is specified, uses it as upper bound and enables dynamic sequence size Returns: the padded encoded data as a tensor @@ -108,29 +112,32 @@ def encode_sequences( if 0 <= eos < len(vocab): raise ValueError("argument 'eos' needs to be outside of vocab possible indices") - if not isinstance(target_size, int): - target_size = max(len(w) for w in sequences) - if sos: - target_size += 1 - if pad: - target_size += 1 + if not isinstance(target_size, int) or dynamic_seq_length: + # Maximum string length + EOS + max_length = max(len(w) for w in sequences) + 1 + if isinstance(sos, int): + max_length += 1 + if isinstance(pad, int): + max_length += 1 + target_size = max_length if not isinstance(target_size, int) else min(max_length, target_size) # Pad all sequences - if pad: # pad with padding symbol + if isinstance(pad, int): # pad with padding symbol if 0 <= pad < len(vocab): raise ValueError("argument 'pad' needs to be outside of vocab possible indices") # In that case, add EOS at the end of the word before padding - encoded_data = np.full([len(sequences), target_size], pad, dtype=np.int32) + default_symbol = pad else: # pad with eos symbol - encoded_data = np.full([len(sequences), target_size], eos, dtype=np.int32) + default_symbol = eos + encoded_data = np.full([len(sequences), target_size], default_symbol, dtype=np.int32) - for idx, seq in enumerate(sequences): - encoded_seq = encode_sequence(seq, vocab) - if pad: # add eos at the end of the sequence - encoded_seq.append(eos) - encoded_data[idx, :min(len(encoded_seq), target_size)] = encoded_seq[:min(len(encoded_seq), target_size)] + # Encode the strings + for idx, seq in enumerate(map(partial(encode_string, vocab=vocab), sequences)): + if isinstance(pad, int): # add eos at the end of the sequence + seq.append(eos) + encoded_data[idx, :min(len(seq), target_size)] = seq[:min(len(seq), target_size)] - if sos: # place eos symbol at the beginning of each sequence + if isinstance(sos, int): # place sos symbol at the beginning of each sequence if 0 <= sos < len(vocab): raise ValueError("argument 'sos' needs to be outside of vocab possible indices") encoded_data = np.roll(encoded_data, 1)
diff --git a/test/common/test_datasets_utils.py b/test/common/test_datasets_utils.py --- a/test/common/test_datasets_utils.py +++ b/test/common/test_datasets_utils.py @@ -32,29 +32,30 @@ def test_translate(input_str, vocab, output_str): def test_encode_decode(input_str): mapping = """3K}7eé;5àÎYho]QwV6qU~W"XnbBvcADfËmy.9ÔpÛ*{CôïE%M4#ÈR:g@T$x?0î£| za1ù8,OG€P-kçHëÀÂ2É/ûIJ\'j(LNÙFut[)èZs+&°Sd=Ï!<â_Ç>rêi`l""" - encoded = utils.encode_sequence(input_str, mapping) + encoded = utils.encode_string(input_str, mapping) decoded = utils.decode_sequence(np.array(encoded), mapping) assert decoded == input_str @pytest.mark.parametrize( - "sequences, vocab, target_size, eos, sos, pad, error, out_shape, gts", + "sequences, vocab, target_size, sos, eos, pad, dynamic_len, error, out_shape, gts", [ - [['cba'], 'abcdef', None, 1, None, None, True, (1, 3), [[2, 1, 0]]], - [['cba', 'a'], 'abcdef', None, -1, None, None, False, (2, 3), [[2, 1, 0], [0, -1, -1]]], - [['cba', 'a'], 'abcdef', None, 6, None, None, False, (2, 3), [[2, 1, 0], [0, 6, 6]]], - [['cba', 'a'], 'abcdef', 2, -1, None, None, False, (2, 2), [[2, 1], [0, -1]]], - [['cba', 'a'], 'abcdef', 4, -1, None, None, False, (2, 4), [[2, 1, 0, -1], [0, -1, -1, -1]]], - [['cba', 'a'], 'abcdef', 5, -1, 7, None, False, (2, 5), [[7, 2, 1, 0, -1], [7, 0, -1, -1, -1]]], - [['cba', 'a'], 'abcdef', None, -1, 7, 9, False, (2, 5), [[7, 2, 1, 0, -1], [7, 0, -1, 9, 9]]], + [['cba'], 'abcdef', None, None, 1, None, False, True, (1, 3), [[2, 1, 0]]], # eos in vocab + [['cba', 'a'], 'abcdef', None, None, -1, None, False, False, (2, 4), [[2, 1, 0, -1], [0, -1, -1, -1]]], + [['cba', 'a'], 'abcdef', None, None, 6, None, False, False, (2, 4), [[2, 1, 0, 6], [0, 6, 6, 6]]], + [['cba', 'a'], 'abcdef', 2, None, -1, None, False, False, (2, 2), [[2, 1], [0, -1]]], + [['cba', 'a'], 'abcdef', 4, None, -1, None, False, False, (2, 4), [[2, 1, 0, -1], [0, -1, -1, -1]]], + [['cba', 'a'], 'abcdef', 5, 7, -1, None, False, False, (2, 5), [[7, 2, 1, 0, -1], [7, 0, -1, -1, -1]]], + [['cba', 'a'], 'abcdef', 6, 7, -1, None, True, False, (2, 5), [[7, 2, 1, 0, -1], [7, 0, -1, -1, -1]]], + [['cba', 'a'], 'abcdef', None, 7, -1, 9, False, False, (2, 6), [[7, 2, 1, 0, -1, 9], [7, 0, -1, 9, 9, 9]]], ], ) -def test_encode_sequences(sequences, vocab, target_size, eos, sos, pad, error, out_shape, gts): +def test_encode_sequences(sequences, vocab, target_size, sos, eos, pad, dynamic_len, error, out_shape, gts): if error: with pytest.raises(ValueError): - _ = utils.encode_sequences(sequences, vocab, target_size, eos, sos, pad) + utils.encode_sequences(sequences, vocab, target_size, eos, sos, pad, dynamic_len) else: - out = utils.encode_sequences(sequences, vocab, target_size, eos, sos, pad) + out = utils.encode_sequences(sequences, vocab, target_size, eos, sos, pad, dynamic_len) assert isinstance(out, np.ndarray) assert out.shape == out_shape assert np.all(out == np.asarray(gts)), print(out, gts)
[models] Enables dynamic sequence length Currently, a lot of memory might be wasted if we do inference on a batch of sequences with length smaller than the fixed seq_len. Allowing a soft value `min(self.seq_len, max(len(s) for s in batch))` would save a lot of memory and computation. But we need to make sure that this does not impact performances in a negative way first!
2021-07-30T18:41:05
mindee/doctr
404
mindee__doctr-404
[ "401" ]
d15725ad9a8edceac393bf0cc97a1c7ff8e2d584
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -49,7 +49,7 @@ "shapely>=1.6.0", "matplotlib>=3.1.0", "mplcursors>=0.3", - "weasyprint>=52.2", + "weasyprint>=52.2,<53.0", "unidecode>=1.0.0", "tensorflow-cpu>=2.4.0", "torch>=1.8.0",
WeasyPrint import error Python 3.7 ## 🐛 Bug When importing weasyprint with python 3.7 I have an error: `AttributeError: 'OutStream' object has no attribute 'buffer'`* ## To Reproduce Steps to reproduce the behavior: `from doctr.models import ocr_predictor` leads to: ``` AttributeError Traceback (most recent call last) <ipython-input-4-19f78ebc9b57> in <module>() ----> 1 from doctr.models import ocr_predictor 2 3 # Load predictor 4 model = ocr_predictor(pretrained=True) 7 frames /usr/local/lib/python3.7/dist-packages/doctr/__init__.py in <module>() 1 from .file_utils import is_tf_available, is_torch_available 2 from .version import __version__ # noqa: F401 ----> 3 from . import documents 4 from . import transforms 5 from . import utils /usr/local/lib/python3.7/dist-packages/doctr/documents/__init__.py in <module>() 1 from .elements import * ----> 2 from .reader import * /usr/local/lib/python3.7/dist-packages/doctr/documents/reader.py in <module>() 8 from pathlib import Path 9 import fitz ---> 10 from weasyprint import HTML 11 from typing import List, Tuple, Optional, Any, Union, Sequence, Dict 12 /usr/local/lib/python3.7/dist-packages/weasyprint/__init__.py in <module>() 321 # Work around circular imports. 322 from .css import preprocess_stylesheet # noqa isort:skip --> 323 from .html import ( # noqa isort:skip 324 HTML5_UA_COUNTER_STYLE, HTML5_UA_STYLESHEET, HTML5_PH_STYLESHEET, 325 find_base_url) /usr/local/lib/python3.7/dist-packages/weasyprint/html.py in <module>() 21 from .css.counters import CounterStyle 22 from .formatting_structure import boxes ---> 23 from .images import SVGImage 24 from .logger import LOGGER 25 from .urls import get_url_attribute /usr/local/lib/python3.7/dist-packages/weasyprint/images.py in <module>() 11 from itertools import cycle 12 ---> 13 import pydyf 14 from PIL import Image 15 /usr/local/lib/python3.7/dist-packages/pydyf/__init__.py in <module>() 402 403 --> 404 class PDF: 405 """PDF document.""" 406 def __init__(self): /usr/local/lib/python3.7/dist-packages/pydyf/__init__.py in PDF() 506 self.write_line(b'%%EOF', output) 507 --> 508 def write(self, output=sys.stdout.buffer): 509 """Write PDF to output. 510 AttributeError: 'OutStream' object has no attribute 'buffer' ``` ## Expected behavior Nothing, special ## Environment ``` DocTR version: 0.3.0 TensorFlow version: 2.5.0 PyTorch version: 1.9.0+cu102 (torchvision 0.10.0+cu102) OpenCV version: 4.5.3 OS: Ubuntu 18.04.5 LTS Python version: 3.7 Is CUDA available (TensorFlow): No Is CUDA available (PyTorch): No CUDA runtime version: 11.0.221 GPU models and configuration: Could not collect Nvidia driver version: Could not collect ```
2021-08-09T16:56:06
mindee/doctr
427
mindee__doctr-427
[ "409" ]
f657a56ad252fcb75d8196ed3b8f03d6f4651295
diff --git a/references/detection/train_pytorch.py b/references/detection/train_pytorch.py --- a/references/detection/train_pytorch.py +++ b/references/detection/train_pytorch.py @@ -9,6 +9,7 @@ import time import datetime +import logging import multiprocessing as mp import numpy as np from fastprogress.fastprogress import master_bar, progress_bar @@ -122,6 +123,12 @@ def main(args): raise AssertionError("PyTorch cannot access your GPU. Please investigate!") if args.device >= torch.cuda.device_count(): raise ValueError("Invalid device index") + # Silent default switch to GPU if available + elif torch.cuda.is_available(): + args.device = 0 + else: + logging.warning("No accessible GPU, targe device set to CPU.") + if torch.cuda.is_available(): torch.cuda.set_device(args.device) model = model.cuda() diff --git a/references/recognition/train_pytorch.py b/references/recognition/train_pytorch.py --- a/references/recognition/train_pytorch.py +++ b/references/recognition/train_pytorch.py @@ -7,6 +7,7 @@ os.environ['USE_TORCH'] = '1' +import logging import time import datetime import multiprocessing as mp @@ -35,6 +36,8 @@ def fit_one_epoch(model, train_loader, batch_transforms, optimizer, scheduler, m for _ in progress_bar(range(len(train_loader)), parent=mb): images, targets = next(train_iter) + if torch.cuda.is_available(): + images = images.cuda() images = batch_transforms(images) train_loss = model(images, targets)['loss'] @@ -58,6 +61,8 @@ def evaluate(model, val_loader, batch_transforms, val_metric): val_loss, batch_cnt = 0, 0 val_iter = iter(val_loader) for images, targets in val_iter: + if torch.cuda.is_available(): + images = images.cuda() images = batch_transforms(images) out = model(images, targets, return_preds=True) # Compute metric @@ -114,6 +119,21 @@ def main(args): checkpoint = torch.load(args.resume, map_location='cpu') model.load_state_dict(checkpoint) + # GPU + if isinstance(args.device, int): + if not torch.cuda.is_available(): + raise AssertionError("PyTorch cannot access your GPU. Please investigate!") + if args.device >= torch.cuda.device_count(): + raise ValueError("Invalid device index") + # Silent default switch to GPU if available + elif torch.cuda.is_available(): + args.device = 0 + else: + logging.warning("No accessible GPU, targe device set to CPU.") + if torch.cuda.is_available(): + torch.cuda.set_device(args.device) + model = model.cuda() + # Metrics val_metric = TextMatch()
[training] Pytorch training of recognition models is very slow Pytorch trainings are very slow for recognition models, far more slower than tensorflow trainings with the same dataset. It could either be: - A torch dataloading issue (dataset/dataloader) - A torch model issue - A hardware issue (CUDA/GPU/CPU lack of compatibility)
We need to address this indeed! Would you mind timing this the evaluation loop with both frameworks please? (since it's sequentially sampled it means we will process the exact same samples between Pytorch & TF) As you mentioned, I think we need to time the dataloading, the switch to GPU + additional transforms, the model inference, and the backward pass. Spotting difference between TF & pytorch on those should help us to tackle this efficiently :)
2021-08-25T12:00:41
mindee/doctr
477
mindee__doctr-477
[ "476" ]
cfc329f8b21cd7d8c08d5c9190c53bd77a3149c4
diff --git a/demo/app.py b/demo/app.py --- a/demo/app.py +++ b/demo/app.py @@ -18,7 +18,7 @@ from doctr.io import DocumentFile from doctr.models import ocr_predictor -from doctr.utils.visualization import synthetize_page, visualize_page +from doctr.utils.visualization import visualize_page DET_ARCHS = ["db_resnet50"] RECO_ARCHS = ["crnn_vgg16_bn", "master", "sar_resnet31"] @@ -96,7 +96,7 @@ def main(): # Page reconsitution under input page page_export = out.pages[0].export() - img = synthetize_page(page_export) + img = out.pages[0].synthesize() cols[3].image(img, clamp=True) # Display JSON
Import error synthetize_page func in streamlit demo script ## 🐛 Bug Import bug while running the streamlit demo script ## To Reproduce Steps to reproduce the behavior: 1. Install the current package version 2. Run streamlit demo/app.py Error message : ImportError: cannot import name 'synthetize_page' from 'doctr.utils.visualization' (/home/ubuntu/repos/mindee/doctr/doctr/utils/visualization.py) ## Correction Try to import "synthetize_page" [from](https://github.com/mindee/doctr/blob/cfc329f8b21cd7d8c08d5c9190c53bd77a3149c4/doctr/utils/visualization.py#L19) whereas it should be "synthesize_page" [here](https://github.com/mindee/doctr/blob/cfc329f8b21cd7d8c08d5c9190c53bd77a3149c4/demo/app.py#L21) . It's probably a typo. It works after renaming.
2021-09-16T07:35:40
mindee/doctr
496
mindee__doctr-496
[ "495" ]
76500ee819ed4d068a77168a3252e29bb0d36bbe
diff --git a/doctr/utils/visualization.py b/doctr/utils/visualization.py --- a/doctr/utils/visualization.py +++ b/doctr/utils/visualization.py @@ -11,6 +11,7 @@ from copy import deepcopy import numpy as np import cv2 +from unidecode import unidecode from typing import Tuple, List, Dict, Any, Union, Optional from .common_types import BoundingBox, RotatedBbox @@ -279,7 +280,11 @@ def synthesize_page( img = Image.new('RGB', (xmax - xmin, ymax - ymin), color=(255, 255, 255)) d = ImageDraw.Draw(img) # Draw in black the value of the word - d.text((0, 0), word["value"], font=font, fill=(0, 0, 0)) + try: + d.text((0, 0), word["value"], font=font, fill=(0, 0, 0)) + except UnicodeEncodeError: + # When character cannot be encoded, use its unidecode version + d.text((0, 0), unidecode(word["value"]), font=font, fill=(0, 0, 0)) # Colorize if draw_proba if draw_proba:
[visualization] Some unsupported characters make page synthesis crash ## 🐛 Page synthesis doesn't support all characters After some investigation on why the page synthesis feature was crashing (cf. https://twitter.com/nudelbrot/status/1442737151700082691), it turns out that default text drawing with Pillow doesn't support all characters. ## To Reproduce ```python from PIL import Image, ImageDraw img = Image.new('RGB', (100, 100), color=(255, 255, 255)) d = ImageDraw.Draw(img) d.text((0, 0), '€', fill=(0, 0, 0)) ``` yields: ``` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~/miniconda3/lib/python3.8/site-packages/PIL/ImageDraw.py in draw_text(ink, stroke_width, stroke_offset) 407 try: --> 408 mask, offset = font.getmask2( 409 text, AttributeError: 'ImageFont' object has no attribute 'getmask2' During handling of the above exception, another exception occurred: UnicodeEncodeError Traceback (most recent call last) <ipython-input-5-ec97abdf1c71> in <module> ----> 1 d.text((0, 0), '€', fill=(0, 0, 0)) ~/miniconda3/lib/python3.8/site-packages/PIL/ImageDraw.py in text(self, xy, text, fill, font, anchor, spacing, align, direction, features, language, stroke_width, stroke_fill, embedded_color, *args, **kwargs) 461 else: 462 # Only draw normal text --> 463 draw_text(ink) 464 465 def multiline_text( ~/miniconda3/lib/python3.8/site-packages/PIL/ImageDraw.py in draw_text(ink, stroke_width, stroke_offset) 421 except AttributeError: 422 try: --> 423 mask = font.getmask( 424 text, 425 mode, ~/miniconda3/lib/python3.8/site-packages/PIL/ImageFont.py in getmask(self, text, mode, *args, **kwargs) 147 :py:mod:`PIL.Image.core` interface module. 148 """ --> 149 return self.font.getmask(text, mode) 150 151 UnicodeEncodeError: 'latin-1' codec can't encode character '\u20ac' in position 0: ordinal not in range(256) ``` ## Expected behavior Page synthesis should be working with any character ## Environment - DocTR Version: 0.3.1 - TensorFlow Version: 2.5.0 - PyTorch & torchvision versions: 1.9.0 & 0.10.0 - OpenCV Version: 4.5.1 - OS: Ubuntu 20.04.3 LTS - How you installed DocTR: source - Python version: 3.8 - CUDA/cuDNN version: 11.4.100 - GPU models and configuration: Could not collect
2021-09-28T14:04:44
mindee/doctr
548
mindee__doctr-548
[ "547" ]
d82a4bc9851ed76cd9717ceaeecce673a9ad5f87
diff --git a/doctr/models/builder.py b/doctr/models/builder.py --- a/doctr/models/builder.py +++ b/doctr/models/builder.py @@ -26,8 +26,8 @@ class DocumentBuilder(NestedObject): def __init__( self, - resolve_lines: bool = False, - resolve_blocks: bool = False, + resolve_lines: bool = True, + resolve_blocks: bool = True, paragraph_break: float = 0.035, rotated_bbox: bool = False ) -> None: @@ -214,7 +214,7 @@ def _build_blocks(self, boxes: np.ndarray, word_preds: List[Tuple[str, float]]) if self.resolve_lines: lines = self._resolve_lines(boxes[:, :-1]) # Decide whether we try to form blocks - if self.resolve_blocks: + if self.resolve_blocks and len(lines) > 1: _blocks = self._resolve_blocks(boxes[:, :-1], lines) else: _blocks = [lines]
diff --git a/test/common/test_models_builder.py b/test/common/test_models_builder.py --- a/test/common/test_models_builder.py +++ b/test/common/test_models_builder.py @@ -11,7 +11,7 @@ def test_documentbuilder(): num_pages = 2 # Don't resolve lines - doc_builder = builder.DocumentBuilder() + doc_builder = builder.DocumentBuilder(resolve_lines=False, resolve_blocks=False) boxes = np.random.rand(words_per_page, 6) boxes[:2] *= boxes[2:4]
set resolve_lines and resolve_blocks to True ## 🐛 Bug As discussed in #512 it needs an improvement for the `sort_boxes ` to set the `resolve_lines` and `resolve_blocks` in `builder.py `to True as default In fact of this the `.render()` and `.export_as_xml()` results are not correct ## To Reproduce Steps to reproduce the behavior: 1. test with any document image which has multible text blocks/lines or where the document is slightly crooked in the picture, for example photographed by a mobile phone ## Expected behavior Correct sorted boxes left-right / top-bottom that the lines and blocks can be resolved correctly ## Environment -DocTR version: 0.4.1a0 -TensorFlow version: N/A -PyTorch version: 1.9.1 (torchvision 0.10.1) -OpenCV version: 4.4.0 -OS: Ubuntu 20.04.3 LTS -Python version: 3.8 -Is CUDA available (TensorFlow): N/A -Is CUDA available (PyTorch): No -CUDA runtime version: Could not collect -GPU models and configuration: Could not collect -Nvidia driver version: Could not collect -cuDNN version: Could not collect
2021-10-26T16:41:19
mindee/doctr
619
mindee__doctr-619
[ "558" ]
400aec0f6b1c343e13a958c914cf927d7673795a
diff --git a/docs/source/conf.py b/docs/source/conf.py --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -45,6 +45,8 @@ 'sphinx.ext.autosectionlabel', 'sphinxemoji.sphinxemoji', # cf. https://sphinxemojicodes.readthedocs.io/en/stable/ 'sphinx_copybutton', + 'recommonmark', + 'sphinx_markdown_tables', ] napoleon_use_ivar = True @@ -55,7 +57,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. -exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store', 'notebooks/*.rst'] # The name of the Pygments (syntax highlighting) style to use. diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -74,6 +74,8 @@ "sphinxemoji>=0.1.8", "sphinx-copybutton>=0.3.1", "docutils<0.18", + "recommonmark>=0.7.1", + "sphinx-markdown-tables>=0.0.15", ] deps = {b: a for a, b in (re.findall(r"^(([^!=<>]+)(?:[!=<>].*)?$)", x)[0] for x in _deps)} @@ -142,6 +144,8 @@ def deps_list(*pkgs): "sphinxemoji", "sphinx-copybutton", "docutils", + "recommonmark", + "sphinx-markdown-tables", ) extras["docs"] = extras["all"] + extras["docs_specific"]
How to run this github repo on google colab I want to run this repo on google colab How can I run this code?
Hi @hammadyounas2008 :wave: We're in the middle of adding a few colab tutorials to use docTR! Could you specify what you mean exactly? What would you like to run? a training? or simply using the library? :)
2021-11-12T18:31:18
mindee/doctr
681
mindee__doctr-681
[ "592" ]
e0764180650e8547f669f6e20c95590fb5fb2cce
diff --git a/doctr/models/recognition/predictor/pytorch.py b/doctr/models/recognition/predictor/pytorch.py --- a/doctr/models/recognition/predictor/pytorch.py +++ b/doctr/models/recognition/predictor/pytorch.py @@ -38,7 +38,7 @@ def __init__( self.split_wide_crops = split_wide_crops self.critical_ar = 8 # Critical aspect ratio self.dil_factor = 1.4 # Dilation factor to overlap the crops - self.target_ar = 4 # Target aspect ratio + self.target_ar = 6 # Target aspect ratio @torch.no_grad() def forward( diff --git a/doctr/models/recognition/predictor/tensorflow.py b/doctr/models/recognition/predictor/tensorflow.py --- a/doctr/models/recognition/predictor/tensorflow.py +++ b/doctr/models/recognition/predictor/tensorflow.py @@ -41,7 +41,7 @@ def __init__( self.split_wide_crops = split_wide_crops self.critical_ar = 8 # Critical aspect ratio self.dil_factor = 1.4 # Dilation factor to overlap the crops - self.target_ar = 4 # Target aspect ratio + self.target_ar = 6 # Target aspect ratio def __call__( self,
Text recognition: Split wide crops parameter highly decrease performances ### 🚀 The feature Fine tune the wide crops splitting method ### Motivation, pitch Hey! It's not a bug per se, because my code is running well. But I retrained a text recognition model, and the performances on my test set were very low compared to my validation set (both from the same dataset). I digged a bit into the code, and noticed thes lines: ``` remapped = False if self.split_wide_crops: new_crops, crop_map, remapped = split_crops(crops, self.critical_ar, self.target_ar, self.dil_factor) if remapped: crops = new_crops ``` I commented them, and the performances were back to what's expected. I understand the motivation on this feature, but i noticed that it creates a lot of characters repetition in the output strings. Example: "AZZ812ZZF21" -> "AZZ81212ZZF21" It's behaving as the cut was adding some padding, and some characters are recognized twice, leading to a repetition when reconstructing the final output. I can send you a few sample data on Mindee's slack community if you need it. ### Alternatives _No response_ ### Additional context _No response_
Hi @jonathanMindee, it would be great to have samples indeed on the slack community! Thanks for that! Hi @charlesmindee: Done on the docTR channel Coming back to this, should we then change the hyperparams of split/merge of crops to close this issue? As it turns out, this doesn't occur on our pretrained crnn. I tried a target_ar of 6, it is slightly better so I will open a PR to close this issue.
2021-12-07T14:16:44
mindee/doctr
682
mindee__doctr-682
[ "263" ]
1671cdd46edb168ef5d4dda6cff1f64412580878
diff --git a/references/classification/train_tensorflow.py b/references/classification/train_tensorflow.py --- a/references/classification/train_tensorflow.py +++ b/references/classification/train_tensorflow.py @@ -16,6 +16,7 @@ import tensorflow as tf import wandb from fastprogress.fastprogress import master_bar, progress_bar +from tensorflow.keras import mixed_precision gpu_devices = tf.config.experimental.list_physical_devices('GPU') if any(gpu_devices): @@ -27,7 +28,7 @@ from utils import plot_samples -def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): +def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb, amp=False): train_iter = iter(train_loader) # Iterate over the batches of the dataset for _ in progress_bar(range(train_loader.num_batches), parent=mb): @@ -39,6 +40,8 @@ def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): out = model(images, training=True) train_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(targets, out) grads = tape.gradient(train_loss, model.trainable_weights) + if amp: + grads = optimizer.get_unscaled_gradients(grads) optimizer.apply_gradients(zip(grads, model.trainable_weights)) mb.child.comment = f'Training loss: {train_loss.numpy().mean():.6}' @@ -81,6 +84,10 @@ def main(args): vocab = VOCABS[args.vocab] + # AMP + if args.amp: + mixed_precision.set_global_policy('mixed_float16') + # Load val data generator st = time.time() val_set = CharacterGenerator( @@ -108,6 +115,7 @@ def main(args): num_classes=len(vocab), include_top=True, ) + # Resume weights if isinstance(args.resume, str): model.load_weights(args.resume) @@ -169,6 +177,8 @@ def main(args): beta_2=0.99, epsilon=1e-6, ) + if args.amp: + optimizer = mixed_precision.LossScaleOptimizer(optimizer) # Tensorboard to monitor training current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") @@ -201,7 +211,7 @@ def main(args): # Training loop mb = master_bar(range(args.epochs)) for epoch in mb: - fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb) + fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb, args.amp) # Validation loop at the end of each epoch val_loss, acc = evaluate(model, val_loader, batch_transforms) @@ -257,6 +267,7 @@ def parse_args(): help='Log to Weights & Biases') parser.add_argument('--pretrained', dest='pretrained', action='store_true', help='Load pretrained parameters before starting the training') + parser.add_argument("--amp", dest="amp", help="Use Automatic Mixed Precision", action="store_true") args = parser.parse_args() return args diff --git a/references/detection/train_tensorflow.py b/references/detection/train_tensorflow.py --- a/references/detection/train_tensorflow.py +++ b/references/detection/train_tensorflow.py @@ -17,6 +17,7 @@ import tensorflow as tf import wandb from fastprogress.fastprogress import master_bar, progress_bar +from tensorflow.keras import mixed_precision gpu_devices = tf.config.experimental.list_physical_devices('GPU') if any(gpu_devices): @@ -29,7 +30,7 @@ from utils import plot_samples -def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): +def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb, amp=False): train_iter = iter(train_loader) # Iterate over the batches of the dataset for images, targets in progress_bar(train_iter, parent=mb): @@ -39,6 +40,8 @@ def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): with tf.GradientTape() as tape: train_loss = model(images, targets, training=True)['loss'] grads = tape.gradient(train_loss, model.trainable_weights) + if amp: + grads = optimizer.get_unscaled_gradients(grads) optimizer.apply_gradients(zip(grads, model.trainable_weights)) mb.child.comment = f'Training loss: {train_loss.numpy():.6}' @@ -74,6 +77,10 @@ def main(args): if not isinstance(args.workers, int): args.workers = min(16, mp.cpu_count()) + # AMP + if args.amp: + mixed_precision.set_global_policy('mixed_float16') + st = time.time() val_set = DetectionDataset( img_folder=os.path.join(args.val_path, 'images'), @@ -151,6 +158,8 @@ def main(args): epsilon=1e-6, clipnorm=5 ) + if args.amp: + optimizer = mixed_precision.LossScaleOptimizer(optimizer) # Tensorboard to monitor training current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") @@ -188,7 +197,7 @@ def main(args): # Training loop mb = master_bar(range(args.epochs)) for epoch in mb: - fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb) + fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb, args.amp) # Validation loop at the end of each epoch val_loss, recall, precision, mean_iou = evaluate(model, val_loader, batch_transforms, val_metric) if val_loss < min_loss: @@ -240,6 +249,7 @@ def parse_args(): help='Load pretrained parameters before starting the training') parser.add_argument('--rotation', dest='rotation', action='store_true', help='train with rotated bbox') + parser.add_argument("--amp", dest="amp", help="Use Automatic Mixed Precision", action="store_true") args = parser.parse_args() return args diff --git a/references/recognition/train_tensorflow.py b/references/recognition/train_tensorflow.py --- a/references/recognition/train_tensorflow.py +++ b/references/recognition/train_tensorflow.py @@ -18,6 +18,7 @@ import tensorflow as tf import wandb from fastprogress.fastprogress import master_bar, progress_bar +from tensorflow.keras import mixed_precision gpu_devices = tf.config.experimental.list_physical_devices('GPU') if any(gpu_devices): @@ -30,7 +31,7 @@ from utils import plot_samples -def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): +def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb, amp=False): train_iter = iter(train_loader) # Iterate over the batches of the dataset for images, targets in progress_bar(train_iter, parent=mb): @@ -40,6 +41,8 @@ def fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb): with tf.GradientTape() as tape: train_loss = model(images, targets, training=True)['loss'] grads = tape.gradient(train_loss, model.trainable_weights) + if amp: + grads = optimizer.get_unscaled_gradients(grads) optimizer.apply_gradients(zip(grads, model.trainable_weights)) mb.child.comment = f'Training loss: {train_loss.numpy().mean():.6}' @@ -76,6 +79,10 @@ def main(args): if not isinstance(args.workers, int): args.workers = min(16, mp.cpu_count()) + # AMP + if args.amp: + mixed_precision.set_global_policy('mixed_float16') + # Load val data generator st = time.time() val_set = RecognitionDataset( @@ -162,6 +169,8 @@ def main(args): epsilon=1e-6, clipnorm=5 ) + if args.amp: + optimizer = mixed_precision.LossScaleOptimizer(optimizer) # Tensorboard to monitor training current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") @@ -195,7 +204,7 @@ def main(args): # Training loop mb = master_bar(range(args.epochs)) for epoch in mb: - fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb) + fit_one_epoch(model, train_loader, batch_transforms, optimizer, mb, args.amp) # Validation loop at the end of each epoch val_loss, exact_match, partial_match = evaluate(model, val_loader, batch_transforms, val_metric) @@ -240,6 +249,7 @@ def parse_args(): help='Log to Weights & Biases') parser.add_argument('--pretrained', dest='pretrained', action='store_true', help='Load pretrained parameters before starting the training') + parser.add_argument("--amp", dest="amp", help="Use Automatic Mixed Precision", action="store_true") args = parser.parse_args() return args
[references] Add FP16 support for training The reference training script should have an option to switch from a FP32 training to a FP16 training. It would raise a question: how to harmonize model loading from both FP? A few suggestions: - simply cast the FP16 checkpoint to FP32 before hashing + uploading - for a given model, each checkpoint is marked with its FP. The user may choose how the model needs to be instantiated: by default the output FP is FP32, but this can be changed by the user. Depending on the checkpoint FP, it will be cast to its counterpart FP for loading. The second option would be cleaner and avoid unnecessary large checkpoints when they can be kept in FP16 Here is a proposition: - [x] add support of FP16 to `doctr.datasets` (#367) - [x] add support of FP16 to `doctr.models` (#382) - [x] add support of FP16 to `doctr.transforms` (#388) - [x] add support of FP16 to `references` with PyTorch (#604) - [x] add support of FP16 to `references` with TensorFlow (#682)
2021-12-07T17:16:03
mindee/doctr
810
mindee__doctr-810
[ "804" ]
a4f22bafef96be367d8b943a820d70de8e135396
diff --git a/demo/app.py b/demo/app.py --- a/demo/app.py +++ b/demo/app.py @@ -79,7 +79,7 @@ def main(): # Forward the image to the model processed_batches = predictor.det_predictor.pre_processor([doc[page_idx]]) - out = predictor.det_predictor.model(processed_batches[0], return_preds=True) + out = predictor.det_predictor.model(processed_batches[0], return_model_output=True) seg_map = out["out_map"] seg_map = tf.squeeze(seg_map[0, ...], axis=[2]) seg_map = cv2.resize(seg_map.numpy(), (doc[page_idx].shape[1], doc[page_idx].shape[0]),
Unable to run the demo using the main branch ### Bug description tried using latest master with streamlit demo as described in intro page. provided a picture with a UK Car in it, to see if it reads the plate text. It returned with the following failure. Strange, i used this 3 months ago, and was totally fine, and the recognition was really good, some how now its simply not working as good, infact alot worse. I have used the api way, and that seems to work ok, but still alot worse than what it was before. Picture was: ``` KeyError: 'out_map' Traceback: File "D:\Python39\lib\site-packages\streamlit\script_runner.py", line 354, in _run_script exec(code, module.__dict__) File "D:\gitsrc\opensource\doctr\demo\app.py", line 109, in <module> main() File "D:\gitsrc\opensource\doctr\demo\app.py", line 83, in main seg_map = out["out_map"] ``` ### Code snippet to reproduce the bug for Web app: ```shell streamlit run demo/app.py ``` For API: ```shell uvicorn --reload --workers 1 --host 0.0.0.0 --port=8002 --app-dir api/ app.main:app ``` with client code as: ```python import requests import io import json with open('D:/ImagesTest/NOREG_4127_20190324_2113499334_cpc2jh1m.jpg', 'rb') as f: data = f.read() response = requests.post("http://localhost:8002/ocr", files={'file': data}).json() with open('dataapi.json', 'w', encoding='utf-8') as f: json.dump(response, f, ensure_ascii=False, indent=4) ``` ### Error traceback ``` KeyError: 'out_map' Traceback: File "D:\Python39\lib\site-packages\streamlit\script_runner.py", line 354, in _run_script exec(code, module.__dict__) File "D:\gitsrc\opensource\doctr\demo\app.py", line 109, in <module> main() File "D:\gitsrc\opensource\doctr\demo\app.py", line 83, in main seg_map = out["out_map"] ``` ### Environment running on Windows 10 Pro latest python the collect_env.py wont work properly under wsl2. ``` Traceback (most recent call last): File "collect_env.py", line 24, in <module> import doctr File "/mnt/d/gitsrc/opensource/doctr/doctr/__init__.py", line 1, in <module> from . import datasets, io, models, transforms, utils File "/mnt/d/gitsrc/opensource/doctr/doctr/datasets/__init__.py", line 1, in <module> from doctr.file_utils import is_tf_available File "/mnt/d/gitsrc/opensource/doctr/doctr/file_utils.py", line 33 logging.info(f"PyTorch version {_torch_version} available.") ^ SyntaxError: invalid syntax ```
Hello @rclarke2050 :wave: You mentioned a picture in the issue description, but it seems to pasted a code snippet instead of the intended picture :sweat_smile: Would you mind sharing it so that we can debug this? Also, you mentioned that the environment collection script isn't working with WSL2. Are you positive that you're running Python 3? Because your failure mentions a syntax error on a perfectly fine Python3 syntax (at least to the best of my knowledge) :thinking: Best, Facing similar issue while executing via the demo app. The same image works fine with the api and docker set-up. Below is the error along with the environment details. Tried disabling the GPU and still got the same error message ************************************************************* $ streamlit run demo/app.py You can now view your Streamlit app in your browser. Local URL: http://localhost:8501 Network URL: http://172.19.36.252:8501 2022-01-18 23:50:47.130 PyTorch version 1.10.1+cu113 available. 2022-01-18 23:50:47.140 TensorFlow version 2.5.0rc3 available. 2022-01-18 23:51:04.898 Using downloaded & verified file: /home/idxuser02/.cache/doctr/models/db_resnet50-adcafc63.zip 2022-01-18 23:51:05.543 Layer lstm will use cuDNN kernels when running on GPU. 2022-01-18 23:51:05.545 Layer lstm will use cuDNN kernels when running on GPU. 2022-01-18 23:51:05.547 Layer lstm will use cuDNN kernels when running on GPU. 2022-01-18 23:51:05.548 Layer lstm_1 will use cuDNN kernels when running on GPU. 2022-01-18 23:51:05.550 Layer lstm_1 will use cuDNN kernels when running on GPU. 2022-01-18 23:51:05.552 Layer lstm_1 will use cuDNN kernels when running on GPU. Downloading https://github.com/mindee/doctr/releases/download/v0.3.0/crnn_vgg16_bn-76b7f2c6.zip to /home/idxuser02/.cache/doctr/models/crnn_vgg16_bn-76b7f2c6.zip 58759168it [00:03, 17994109.05it/s] 2022-01-18 23:51:15.522 Traceback (most recent call last): File "/home/idxuser02/miniconda3/envs/doctr-pytorch/lib/python3.8/site-packages/streamlit/script_runner.py", line 379, in _run_script exec(code, module.__dict__) File "/home/idxuser02/Documents/demo/doctr/demo/app.py", line 109, in <module> main() File "/home/idxuser02/Documents/demo/doctr/demo/app.py", line 83, in main seg_map = out["out_map"] KeyError: 'out_map' ************************************************************************************************* Collecting environment information... DocTR version: 0.5.1a0 TensorFlow version: 2.5.0-rc3 PyTorch version: 1.10.1+cu113 (torchvision 0.11.2+cu113) OpenCV version: 4.5.4 OS: Ubuntu 20.04.2 LTS Python version: 3.8.0 Is CUDA available (TensorFlow): Yes Is CUDA available (PyTorch): Yes CUDA runtime version: 11.2.152 GPU models and configuration: GPU 0: GeForce RTX 3090 Nvidia driver version: 460.91.03 cuDNN version: Probably one of the following: /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn.so.8.1.1 /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.1.1 /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.1.1 /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.1.1 /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.1.1 /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.1.1 /usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.1.1 ******************************************************************************************
2022-01-19T08:55:04
mindee/doctr
848
mindee__doctr-848
[ "840" ]
a2b31cc1b0ba639af399b4269670f47dc0b1c105
diff --git a/doctr/datasets/datasets/pytorch.py b/doctr/datasets/datasets/pytorch.py --- a/doctr/datasets/datasets/pytorch.py +++ b/doctr/datasets/datasets/pytorch.py @@ -4,6 +4,7 @@ # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. import os +from copy import deepcopy from typing import Any, List, Tuple import torch @@ -22,7 +23,7 @@ def _read_sample(self, index: int) -> Tuple[torch.Tensor, Any]: # Read image img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=torch.float32) - return img, target + return img, deepcopy(target) @staticmethod def collate_fn(samples: List[Tuple[torch.Tensor, Any]]) -> Tuple[torch.Tensor, List[Any]]: diff --git a/doctr/datasets/datasets/tensorflow.py b/doctr/datasets/datasets/tensorflow.py --- a/doctr/datasets/datasets/tensorflow.py +++ b/doctr/datasets/datasets/tensorflow.py @@ -4,6 +4,7 @@ # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. import os +from copy import deepcopy from typing import Any, List, Tuple import tensorflow as tf @@ -22,7 +23,7 @@ def _read_sample(self, index: int) -> Tuple[tf.Tensor, Any]: # Read image img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32) - return img, target + return img, deepcopy(target) @staticmethod def collate_fn(samples: List[Tuple[tf.Tensor, Any]]) -> Tuple[tf.Tensor, List[Any]]:
diff --git a/tests/common/test_datasets.py b/tests/common/test_datasets.py --- a/tests/common/test_datasets.py +++ b/tests/common/test_datasets.py @@ -42,3 +42,14 @@ def test_abstractdataset(mock_image_path): ds.sample_transforms = lambda x, y: (x, y + 1) img3, target3 = ds[0] assert np.all(img3.numpy() == img.numpy()) and (target3 == (target + 1)) + + # Check inplace modifications + ds.data = [(ds.data[0][0], {"label": "A"})] + + def inplace_transfo(x, target): + target["label"] += "B" + return x, target + ds.sample_transforms = inplace_transfo + _, t = ds[0] + _, t = ds[0] + assert t['label'] == "AB"
[datasets] Targets are modified inplace ### Bug description **Targets** are being changed when iterating over some dataset more than one time. The reason is storing targets in self.data, and changing them in the `__getitem__` ***in place*** using `pre_transforms`, etc. ```python # _AbstractDataset def __getitem__( self, index: int ) -> Tuple[Any, Any]: # Read image img, target = self._read_sample(index) # Pre-transforms (format conversion at run-time etc.) if self._pre_transforms is not None: img, target = self._pre_transforms(img, target) if self.img_transforms is not None: # typing issue cf. https://github.com/python/mypy/issues/5485 img = self.img_transforms(img) # type: ignore[call-arg] if self.sample_transforms is not None: img, target = self.sample_transforms(img, target) return img, target ``` This can be fixed by copying target in the `_read_sample` ```python # AbstractDataset def _read_sample(self, index: int) -> Tuple[tf.Tensor, Any]: img_name, target = self.data[index] # Read image img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32) return img, target ``` **OR** returning a copy of the target in all transform methods. ```python def convert_target_to_relative(img: ImageTensor, target: Dict[str, Any]) -> Tuple[ImageTensor, Dict[str, Any]]: target['boxes'] = convert_to_relative_coords(target['boxes'], get_img_shape(img)) return img, target ``` ### Code snippet to reproduce the bug ```python def process_image(train_example): img, target = train_example img_numpy = img.numpy() * 255 for example in target['boxes']: print(example) unnormalized_example = [int(example[0]*img.shape[1]), int(example[1]*img.shape[0]), int(example[2]*img.shape[1]), int(example[3]*img.shape[0])] cv2.rectangle(img=img_numpy, pt1=(unnormalized_example[0], unnormalized_example[1]), pt2=(unnormalized_example[2], unnormalized_example[3]), color=(0, 0, 255), thickness=2) return img_numpy train_set = SROIE(train=True, download=True) for i in range(2): for j, example in enumerate(train_set): if j == 0: print(f"{i} ____") img_n = process_image(example) ``` P.S. Sorry for not a pretty code style. This snippet is just for an example :) ### Error traceback ~changed target box coordinates ### Environment .
Hi @max-kalganov :wave: Thanks for reporting this! Reading your snippets, if you implemented an inplace transform and pass it to the dataset, this will indeed modify the source target. But so far, it's up to the developer. However, you mention a change of target, but your `process_image` is only changing the image. Could you elaborate on your snippet so that it prints / highlight the part where the unwanted behaviour happens please? And more generally speaking, are you suggesting that we enforce a deepcopy of the target & image in the `_read_sample` method? Cheers :v: Hi @fg-mindee Thanks for the fast response! :) I will try to explain my case in a slightly different way. 1. *Reading your snippets, if you implemented an inplace transform and pass it to the dataset, this will indeed modify the source target.* - `convert_target_to_relative` is ***not*** my code. I have found it in the doctr [sources](https://github.com/mindee/doctr/blob/e5ca2d536864ccff1460ede9bf3da66b13a2ab9a/doctr/datasets/utils.py#L160). 2. *But so far, it's up to the developer* - well, that's the reason why I haven't created a fork. Leaving the code as it is may lead to some unfortunate behavior as I found. So it would be nice to have some common guideline for samples/targets transformers. Which is generally up to you :) Either making copies in all transform methods or coping samples/targets before all transformations. 3. *However, you mention a change of target, but your process_image is only changing the image.* - the code in the **Code snippet to reproduce the bug** section is to represent *target changes* (*image bounding boxes in this case*) when iterating twice over `train_set`. But yeah, you are right. My code is quite redundant. Here is a more compact version ```python def print_example(train_example): _, target = train_example for target_boxes in target['boxes']: print(f"target_boxes - {target_boxes}") train_set = SROIE(train=True, download=True) for i in range(3): for x_y in train_set: print(f"{i} ____") print_example(x_y) break ``` Results example: ``` 0 ____ target_boxes - [0.08819345 0.09345794 0.5647226 0.11105002] target_boxes - [0.09672831 0.11050028 0.25320056 0.1275426 ] target_boxes - [0.09103841 0.12809236 0.5817923 0.14293568] ... target_boxes - [0.09103841 0.96206707 0.37980086 0.9769104 ] 1 ____ target_boxes - [1.2545299e-04 5.1378749e-05 8.0330385e-04 6.1050043e-05] target_boxes - [1.3759361e-04 6.0747814e-05 3.6017149e-04 7.0116876e-05] target_boxes - [1.2949987e-04 7.0419112e-05 8.2758506e-04 7.8579265e-05] ... target_boxes - [0.0001295 0.0005289 0.00054026 0.00053706] 2 ____ target_boxes - [1.7845376e-07 2.8245601e-08 1.1426797e-06 3.3562422e-08] target_boxes - [1.9572349e-07 3.3396269e-08 5.1233496e-07 3.8546936e-08] target_boxes - [1.8421034e-07 3.8713090e-08 1.1772191e-06 4.3199158e-08] ... target_boxes - [1.8421034e-07 2.9076355e-07 7.6850250e-07 2.9524961e-07] Process finished with exit code 0 ``` As you can see, boxes are changing over iterations. 4. *And more generally speaking, are you suggesting that we enforce a deepcopy of the target & image in the _read_sample method?* - well, yes, this could be a solution. But I left it for you to decide. Because as I understand, targets can be `Any` type as was mentioned somewhere in the sources. So using `deepcopy` in this case is not the best solution. As a conclusion, I just want to point you at this problem. Because of a deep coherency in code structures, changes need to be supported over all lib. So there is only for you to decide which way of solving the problem is more convenient for you. I will accept any of these. :) Looking forward to see which decision will you make. Best regards! Hey there :wave: I'll try to answer all your points: - first, I'll have to say: if there is an issue with existing datasets, we wouldn't have spotted it. The reason behind this is that all our training datasets are already in relative coords, and the ones using the relative coord conversion, are datasets we use for test (we only iterate once on it). So it's very possible that there is an issue since it wouldn't have come up on our usage! > `convert_target_to_relative` is _**not**_ my code. I have found it in the doctr [sources](https://github.com/mindee/doctr/blob/e5ca2d536864ccff1460ede9bf3da66b13a2ab9a/doctr/datasets/utils.py#L160). Sure, the function was implemented here, but you pointed out `AbstractDataset` which doesn't use relative conversion. So I guess you're actually using a snippet with the ones that are using it (FUNSD, SROIE, IC13, CORD, SynthText, IIIT5K, SVHN, or Imgur5k)? > 2. _But so far, it's up to the developer_ - well, that's the reason why I haven't created a fork. Leaving the code as it is may lead to some unfortunate behavior as I found. So it would be nice to have some common guideline for samples/targets transformers. Which is generally up to you :) Either making copies in all transform methods or coping samples/targets before all transformations. Oh yeah sure, I meant: if you implement custom transforms, it's up to you to check the behaviour you're implementing :) But here if there is an inplace trouble, it's up to us to fix it of course. > 3. _However, you mention a change of target, but your process_image is only changing the image._ - the code in the **Code snippet to reproduce the bug** section is to represent _target changes_ (_image bounding boxes in this case_) when iterating twice over `train_set`. But yeah, you are right. My code is quite redundant. Here is a more compact version Thanks, much clearer! > As a conclusion, I just want to point you at this problem. Because of a deep coherency in code structures, changes need to be supported over all lib. So there is only for you to decide which way of solving the problem is more convenient for you. I will accept any of these. :) Looking forward to see which decision will you make. I'll run some test, but most likely, I'll just make sure the target is a deepcopy in `_read_sample`. That will sterilize any inplace operations on the target :+1:
2022-03-10T10:39:58
mindee/doctr
929
mindee__doctr-929
[ "927" ]
607aaaf61f1e2c99ba0cbcbce51a41920ca29d02
diff --git a/doctr/datasets/utils.py b/doctr/datasets/utils.py --- a/doctr/datasets/utils.py +++ b/doctr/datasets/utils.py @@ -72,7 +72,10 @@ def encode_string( Returns: A list encoding the input_string""" - return list(map(vocab.index, input_string)) # type: ignore[arg-type] + try: + return list(map(vocab.index, input_string)) # type: ignore[arg-type] + except ValueError: + raise ValueError("some characters cannot be found in 'vocab'") def decode_sequence(
Fix encode_string function ### Bug description Currently there is no check if the single characters are also available in the given vocabulary. We need a check for this :) TODO's: - [ ] check that in the function and throw a meaningful exception - [ ] improve the corresponding test discussion: #926 ### Code snippet to reproduce the bug ```python from doctr.datasets.utils import encode_string from doctr.datasets import VOCABS x = encode_string(input_string='abcDÄÜ', vocab=VOCABS['english']) # Ä and Ü does not exist in vocab # raises ValueError: substring not found ``` ### Error traceback ``` Traceback (most recent call last): File "/home/felix/Desktop/doctr/test.py", line 7, in <module> x = encode_string(input_string='abcDÄÜ', vocab=VOCABS['english']) # Ä and Ü does not exist in vocab File "/home/felix/Desktop/doctr/doctr/datasets/utils.py", line 75, in encode_string return list(map(vocab.index, input_string)) # type: ignore[arg-type] ValueError: substring not found ``` ### Environment not need :) ### Deep Learning backend same
Thanks for the issue 🙏 I'd argue it's a documentation/error message clarity issue rather than a bug (meaning that we don't want the code to stop failing in this snippet)
2022-05-25T19:08:31
mindee/doctr
963
mindee__doctr-963
[ "454", "454" ]
2ffaf50f7126b31b893d43a2292793ba40c8e110
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -44,7 +44,7 @@ "scipy>=1.4.0", "h5py>=3.1.0", "opencv-python>=3.4.5.20", - "tensorflow>=2.4.0", + "tensorflow>=2.9.0,<3.0.0", # cf. https://github.com/mindee/doctr/issues/454 "pypdfium2>=2.1.0, <3.0.0", # cf. https://github.com/mindee/doctr/issues/947 "pyclipper>=1.2.0", "shapely>=1.6.0", @@ -59,7 +59,6 @@ "tqdm>=4.30.0", "tensorflow-addons>=0.13.0", "rapidfuzz>=1.6.0", - "keras<2.7.0", # cf. https://github.com/mindee/doctr/pull/579 "tf2onnx>=1.9.2", "huggingface-hub>=0.4.0", # Testing @@ -115,14 +114,12 @@ def deps_list(*pkgs): extras["tf"] = deps_list( "tensorflow", "tensorflow-addons", - "keras", "tf2onnx", ) extras["tf-cpu"] = deps_list( "tensorflow-cpu", "tensorflow-addons", - "keras", "tf2onnx", )
diff --git a/tests/tensorflow/test_models_classification_tf.py b/tests/tensorflow/test_models_classification_tf.py --- a/tests/tensorflow/test_models_classification_tf.py +++ b/tests/tensorflow/test_models_classification_tf.py @@ -97,9 +97,10 @@ def test_crop_orientation_model(mock_text_box): # Name:'res_net_4/magc/transform/conv2d_289/Conv2D:0_nchwc' # Status Message: Input channels C is not equal to kernel channels * group. C: 32 kernel channels: 256 group: 1 #["magc_resnet31", (32, 32, 3), (126,)], - ["mobilenet_v3_small", (512, 512, 3), (126,)], - ["mobilenet_v3_large", (512, 512, 3), (126,)], - ["mobilenet_v3_small_orientation", (128, 128, 3), (4,)], + # Disabled for now + # ["mobilenet_v3_small", (512, 512, 3), (126,)], + # ["mobilenet_v3_large", (512, 512, 3), (126,)], + # ["mobilenet_v3_small_orientation", (128, 128, 3), (4,)], ], ) def test_models_saved_model_export(arch_name, input_shape, output_size):
Inconsistency in TF inference for grouped convolutions on CPU ## 🐛 Troubles with grouped convolutions on CPU It seems that TF has troubles with fused grouped convolutions on CPU using `keras.Model.predict` while using the `call` method with `training=False` does run smoothly. This issue is only happening on CPU, on GPU the script runs smoothly. ## To Reproduce ```python import os os.environ['CUDA_VISIBLE_DEVICES'] = '-1' import tensorflow as tf from doctr.models import mobilenet_v3_large samples = tf.zeros((1, 512, 512, 3), dtype=tf.float32) model = mobilenet_v3_large(input_shape=(512, 512, 3)) # This works out = model.call(samples, training=False) # And this throws an error out = model.predict(samples) ``` which yields ``` --------------------------------------------------------------------------- UnimplementedError Traceback (most recent call last) <ipython-input-1-d329ff911697> in <module> 11 out = model.call(samples, training=False) 12 # And this throws an error ---> 13 out = model.predict(samples) ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing) 1725 for step in data_handler.steps(): 1726 callbacks.on_predict_batch_begin(step) -> 1727 tmp_batch_outputs = self.predict_function(iterator) 1728 if data_handler.should_sync: 1729 context.async_wait() ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) 887 888 with OptionalXlaContext(self._jit_compile): --> 889 result = self._call(*args, **kwds) 890 891 new_tracing_count = self.experimental_get_tracing_count() ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) 954 *args, **kwds) 955 # If we did not create any variables the trace we have is good enough. --> 956 return self._concrete_stateful_fn._call_flat( 957 filtered_flat_args, self._concrete_stateful_fn.captured_inputs) # pylint: disable=protected-access 958 ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _call_flat(self, args, captured_inputs, cancellation_manager) 1958 and executing_eagerly): 1959 # No tape is watching; skip to running the function. -> 1960 return self._build_call_outputs(self._inference_function.call( 1961 ctx, args, cancellation_manager=cancellation_manager)) 1962 forward_backward = self._select_forward_and_backward_functions( ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in call(self, ctx, args, cancellation_manager) 589 with _InterpolateFunctionError(self): 590 if cancellation_manager is None: --> 591 outputs = execute.execute( 592 str(self.signature.name), 593 num_outputs=self._num_outputs, ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name) 57 try: 58 ctx.ensure_initialized() ---> 59 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, 60 inputs, attrs, num_outputs) 61 except core._NotOkStatusException as e: UnimplementedError: Fused conv implementation does not support grouped convolutions for now. [[node mobile_net_v3/inverted_0/sequential/activation_1/Relu (defined at /home/fg/Documents/doctr/doctr/models/backbones/mobilenet/tensorflow.py:140) ]] [Op:__inference_predict_function_6941] Function call stack: predict_function ``` ## Expected behavior The script should run smoothly ## Environment - DocTR Version: 0.3.1 - TensorFlow Version: 2.5.0 - PyTorch & torchvision versions: 1.9.0 (torchvision 0.10.0) - OpenCV Version: 4.5.1 - OS: Ubuntu 20.04.3 LTS - How you installed DocTR: source - Python version: 3.8 - CUDA/cuDNN version: CUDA 11.4.100 (cuDNN 8.2.0) - GPU models and configuration: NVIDIA GeForce RTX 2070 with Max-Q Design (driver 470.57.02) Inconsistency in TF inference for grouped convolutions on CPU ## 🐛 Troubles with grouped convolutions on CPU It seems that TF has troubles with fused grouped convolutions on CPU using `keras.Model.predict` while using the `call` method with `training=False` does run smoothly. This issue is only happening on CPU, on GPU the script runs smoothly. ## To Reproduce ```python import os os.environ['CUDA_VISIBLE_DEVICES'] = '-1' import tensorflow as tf from doctr.models import mobilenet_v3_large samples = tf.zeros((1, 512, 512, 3), dtype=tf.float32) model = mobilenet_v3_large(input_shape=(512, 512, 3)) # This works out = model.call(samples, training=False) # And this throws an error out = model.predict(samples) ``` which yields ``` --------------------------------------------------------------------------- UnimplementedError Traceback (most recent call last) <ipython-input-1-d329ff911697> in <module> 11 out = model.call(samples, training=False) 12 # And this throws an error ---> 13 out = model.predict(samples) ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing) 1725 for step in data_handler.steps(): 1726 callbacks.on_predict_batch_begin(step) -> 1727 tmp_batch_outputs = self.predict_function(iterator) 1728 if data_handler.should_sync: 1729 context.async_wait() ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) 887 888 with OptionalXlaContext(self._jit_compile): --> 889 result = self._call(*args, **kwds) 890 891 new_tracing_count = self.experimental_get_tracing_count() ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) 954 *args, **kwds) 955 # If we did not create any variables the trace we have is good enough. --> 956 return self._concrete_stateful_fn._call_flat( 957 filtered_flat_args, self._concrete_stateful_fn.captured_inputs) # pylint: disable=protected-access 958 ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in _call_flat(self, args, captured_inputs, cancellation_manager) 1958 and executing_eagerly): 1959 # No tape is watching; skip to running the function. -> 1960 return self._build_call_outputs(self._inference_function.call( 1961 ctx, args, cancellation_manager=cancellation_manager)) 1962 forward_backward = self._select_forward_and_backward_functions( ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py in call(self, ctx, args, cancellation_manager) 589 with _InterpolateFunctionError(self): 590 if cancellation_manager is None: --> 591 outputs = execute.execute( 592 str(self.signature.name), 593 num_outputs=self._num_outputs, ~/miniconda3/lib/python3.8/site-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name) 57 try: 58 ctx.ensure_initialized() ---> 59 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, 60 inputs, attrs, num_outputs) 61 except core._NotOkStatusException as e: UnimplementedError: Fused conv implementation does not support grouped convolutions for now. [[node mobile_net_v3/inverted_0/sequential/activation_1/Relu (defined at /home/fg/Documents/doctr/doctr/models/backbones/mobilenet/tensorflow.py:140) ]] [Op:__inference_predict_function_6941] Function call stack: predict_function ``` ## Expected behavior The script should run smoothly ## Environment - DocTR Version: 0.3.1 - TensorFlow Version: 2.5.0 - PyTorch & torchvision versions: 1.9.0 (torchvision 0.10.0) - OpenCV Version: 4.5.1 - OS: Ubuntu 20.04.3 LTS - How you installed DocTR: source - Python version: 3.8 - CUDA/cuDNN version: CUDA 11.4.100 (cuDNN 8.2.0) - GPU models and configuration: NVIDIA GeForce RTX 2070 with Max-Q Design (driver 470.57.02)
cf. https://github.com/tensorflow/tensorflow/issues/51825 I seems that they are not likely to fix this in the near future... Yes unfortunately, but we'll have to keep this one open for reference then :/ @charlesmindee @fg-mindee same problem if we try to export to SavedModel format (only mobilenet arch) So the upstream problem about grouped conv on CPU is now resolved for TF 2.9 👍 We're gonna have to look at updating our version specifiers @frgfm sounds good :) cf. https://github.com/tensorflow/tensorflow/issues/51825 I seems that they are not likely to fix this in the near future... Yes unfortunately, but we'll have to keep this one open for reference then :/ @charlesmindee @fg-mindee same problem if we try to export to SavedModel format (only mobilenet arch) So the upstream problem about grouped conv on CPU is now resolved for TF 2.9 👍 We're gonna have to look at updating our version specifiers @frgfm sounds good :)
2022-06-27T16:33:00
mindee/doctr
1,280
mindee__doctr-1280
[ "1206" ]
95857cf05d7b8054fc1dcb2a20d79119d50488ba
diff --git a/demo/backend/pytorch.py b/demo/backend/pytorch.py --- a/demo/backend/pytorch.py +++ b/demo/backend/pytorch.py @@ -9,8 +9,25 @@ from doctr.models import ocr_predictor from doctr.models.predictor import OCRPredictor -DET_ARCHS = ["db_resnet50", "db_mobilenet_v3_large", "linknet_resnet50_rotation"] -RECO_ARCHS = ["crnn_vgg16_bn", "crnn_mobilenet_v3_small", "master", "sar_resnet31"] +DET_ARCHS = [ + "db_resnet50", + "db_resnet34", + "db_mobilenet_v3_large", + "db_resnet50_rotation", + "linknet_resnet18", + "linknet_resnet34", + "linknet_resnet50", +] +RECO_ARCHS = [ + "crnn_vgg16_bn", + "crnn_mobilenet_v3_small", + "crnn_mobilenet_v3_large", + "master", + "sar_resnet31", + "vitstr_small", + "vitstr_base", + "parseq", +] def load_predictor(det_arch: str, reco_arch: str, device) -> OCRPredictor: diff --git a/demo/backend/tensorflow.py b/demo/backend/tensorflow.py --- a/demo/backend/tensorflow.py +++ b/demo/backend/tensorflow.py @@ -9,8 +9,24 @@ from doctr.models import ocr_predictor from doctr.models.predictor import OCRPredictor -DET_ARCHS = ["db_resnet50", "db_mobilenet_v3_large", "linknet_resnet18_rotation"] -RECO_ARCHS = ["crnn_vgg16_bn", "crnn_mobilenet_v3_small", "master", "sar_resnet31"] +DET_ARCHS = [ + "db_resnet50", + "db_mobilenet_v3_large", + "linknet_resnet18", + "linknet_resnet18_rotation", + "linknet_resnet34", + "linknet_resnet50", +] +RECO_ARCHS = [ + "crnn_vgg16_bn", + "crnn_mobilenet_v3_small", + "crnn_mobilenet_v3_large", + "master", + "sar_resnet31", + "vitstr_small", + "vitstr_base", + "parseq", +] def load_predictor(det_arch: str, reco_arch: str, device) -> OCRPredictor:
listing the detection and recognition models not working in pytorch ### Bug description Hi, This is the list of models not working in inference: - detection models: * db_resnet_34 * linknet_resnet18 * linknet_resnet34 * linknet_resnet50 for all these detection models in pytorch, the code inference works but it get to much segmentations/detected boxes. - recognition models: * sar_resnet31 * master * vitstr_small * vitstr_base For all of these models in pytorch, the code inference seems to work, but it gets random character recognition. I think they are not correct loaded or trained. ### Code snippet to reproduce the bug in doctr/demo/backend/pytorch.py file, changing this lines ``` DET_ARCHS = ["db_resnet50", "db_mobilenet_v3_large", "linknet_resnet50_rotation"] RECO_ARCHS = ["crnn_vgg16_bn", "crnn_mobilenet_v3_small", "master", "sar_resnet31"] ``` by this lines ``` #DET_ARCHS = ["db_resnet50", "db_mobilenet_v3_large", "linknet_resnet50_rotation"] DET_ARCHS = [ "db_resnet34", "db_resnet50", "db_mobilenet_v3_large", "linknet_resnet18", "linknet_resnet34", "linknet_resnet50", "db_resnet50_rotation"] #RECO_ARCHS = ["crnn_vgg16_bn", "crnn_mobilenet_v3_small", "master", "sar_resnet31"] RECO_ARCHS=[ "crnn_vgg16_bn", "crnn_mobilenet_v3_small", "crnn_mobilenet_v3_large", "sar_resnet31", "master", "vitstr_small", "vitstr_base"] ``` and running this code to try all the pytorch models ``` USE_TF=0 streamlit run demo/app.py ``` ### Error traceback not errors but bugs on models ### Environment wget https://raw.githubusercontent.com/mindee/doctr/main/scripts/collect_env.py # For security purposes, please check the contents of collect_env.py before running it. python collect_env.py ### Deep Learning backend from doctr.file_utils import is_tf_available, is_torch_available print(f"is_tf_available: {is_tf_available()}") print(f"is_torch_available: {is_torch_available()}")
Hey @nikokks :wave:, the most of this models does not have pretrained checkpoints but @odulcy-mindee and @charlesmindee are currently on it so stay tuned #969 Hello @nikokks, Thanks for this issue! Indeed, we're on it, we'll release model one by one when they'll be trained :+1:
2023-08-10T10:49:25
weni-ai/bothub-engine
43
weni-ai__bothub-engine-43
[ "42" ]
8523a48997fcff9b0bbcf698a158755c9a493728
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -66,15 +66,6 @@ def has_object_permission(self, request, view, obj): return authorization.can_contribute -class RepositoryExampleEntityPermission(permissions.BasePermission): - def has_object_permission(self, request, view, obj): - authorization = obj.repository_example.repository_update.repository \ - .get_user_authorization(request.user) - if request.method in READ_METHODS: - return authorization.can_read - return authorization.can_contribute - - class RepositoryTranslatedExamplePermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): repository = obj.original_example.repository_update.repository @@ -130,8 +121,7 @@ def filter_repository_uuid(self, queryset, name, value): authorization = repository.get_user_authorization(request.user) if not authorization.can_read: raise PermissionDenied() - return queryset.filter( - repository_update__repository=repository) + return repository.examples(queryset=queryset) except Repository.DoesNotExist: raise NotFound( _('Repository {} does not exist').format(value)) diff --git a/bothub/common/migrations/0004_auto_20180514_1129.py b/bothub/common/migrations/0004_auto_20180514_1129.py new file mode 100644 --- /dev/null +++ b/bothub/common/migrations/0004_auto_20180514_1129.py @@ -0,0 +1,17 @@ +# Generated by Django 2.0.2 on 2018-05-14 11:29 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('common', '0003_auto_20180503_1223'), + ] + + operations = [ + migrations.AlterModelOptions( + name='repositoryexample', + options={'ordering': ['-created_at'], 'verbose_name': 'repository example', 'verbose_name_plural': 'repository examples'}, + ), + ] diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -102,8 +102,10 @@ def languages_status(self): languages.SUPPORTED_LANGUAGES, )) - def examples(self, language=None, deleted=True): - query = RepositoryExample.objects.filter( + def examples(self, language=None, deleted=True, queryset=None): + if queryset is None: + queryset = RepositoryExample.objects + query = queryset.filter( repository_update__repository=self) if language: query = query.filter( @@ -267,6 +269,7 @@ class RepositoryExample(models.Model): class Meta: verbose_name = _('repository example') verbose_name_plural = _('repository examples') + ordering = ['-created_at'] repository_update = models.ForeignKey( RepositoryUpdate,
diff --git a/bothub/api/tests/example.py b/bothub/api/tests/example.py --- a/bothub/api/tests/example.py +++ b/bothub/api/tests/example.py @@ -8,6 +8,7 @@ from bothub.common import languages from bothub.common.models import Repository from bothub.common.models import RepositoryExample +from bothub.common.models import RepositoryExampleEntity from ..views import NewRepositoryExampleViewSet from ..views import RepositoryExampleViewSet @@ -34,7 +35,8 @@ def request(self, token, data): } request = self.factory.post( '/api/example/new/', - data, + json.dumps(data), + content_type='application/json', **authorization_header) response = NewRepositoryExampleViewSet.as_view( {'post': 'create'})(request) @@ -48,9 +50,10 @@ def test_okay(self): response, content_data = self.request( self.owner_token, { - 'repository': self.repository.uuid, + 'repository': str(self.repository.uuid), 'text': text, 'intent': intent, + 'entities': [], }) self.assertEqual( response.status_code, @@ -66,9 +69,10 @@ def test_forbidden(self): response, content_data = self.request( self.user_token, { - 'repository': self.repository.uuid, + 'repository': str(self.repository.uuid), 'text': 'hi', 'intent': 'greet', + 'entities': [], }) self.assertEqual( response.status_code, @@ -80,6 +84,7 @@ def test_repository_uuid_required(self): { 'text': 'hi', 'intent': 'greet', + 'entities': [], }) self.assertEqual( response.status_code, @@ -89,9 +94,10 @@ def test_repository_does_not_exists(self): response, content_data = self.request( self.owner_token, { - 'repository': uuid.uuid4(), + 'repository': str(uuid.uuid4()), 'text': 'hi', 'intent': 'greet', + 'entities': [], }) self.assertEqual( response.status_code, @@ -107,11 +113,34 @@ def test_invalid_repository_uuid(self): 'repository': 'invalid', 'text': 'hi', 'intent': 'greet', + 'entities': [], }) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST) + def test_with_entities(self): + response, content_data = self.request( + self.owner_token, + { + 'repository': str(self.repository.uuid), + 'text': 'my name is douglas', + 'intent': 'greet', + 'entities': [ + { + 'start': 11, + 'end': 18, + 'entity': 'name', + }, + ], + }) + self.assertEqual( + response.status_code, + status.HTTP_201_CREATED) + self.assertEqual( + len(content_data.get('entities')), + 1) + class RepositoryExampleRetrieveTestCase(TestCase): def setUp(self): @@ -127,7 +156,12 @@ def setUp(self): language=languages.LANGUAGE_EN) self.example = RepositoryExample.objects.create( repository_update=self.repository.current_update(), - text='hi') + text='my name is douglas') + RepositoryExampleEntity.objects.create( + repository_example=self.example, + start=11, + end=18, + entity='name') self.private_repository = Repository.objects.create( owner=self.owner, @@ -182,6 +216,17 @@ def test_public(self): content_data.get('id'), self.example.id) + def test_list_entities(self): + response, content_data = self.request( + self.example, + self.owner_token) + self.assertEqual( + response.status_code, + status.HTTP_200_OK) + self.assertEqual( + len(content_data.get('entities')), + 1) + class RepositoryExampleDestroyTestCase(TestCase): def setUp(self): diff --git a/bothub/api/tests/examples.py b/bothub/api/tests/examples.py --- a/bothub/api/tests/examples.py +++ b/bothub/api/tests/examples.py @@ -33,6 +33,10 @@ def setUp(self): original_example=self.example, text='oi', language=languages.LANGUAGE_PT) + self.deleted = RepositoryExample.objects.create( + repository_update=self.repository.current_update(), + text='hey') + self.deleted.delete() self.private_repository = Repository.objects.create( owner=self.owner, @@ -161,3 +165,15 @@ def test_forbidden(self): self.assertEqual( response.status_code, status.HTTP_403_FORBIDDEN) + + def test_dont_list_deleted(self): + response, content_data = self.request( + { + 'repository_uuid': self.repository.uuid, + }, + self.owner_token) + self.assertEqual( + response.status_code, + status.HTTP_200_OK) + for repository in content_data.get('results'): + self.failIf(self.deleted.id == repository.get('id'))
Examples route permission using user authorization
2018-05-14T18:27:20
weni-ai/bothub-engine
68
weni-ai__bothub-engine-68
[ "67" ]
fe7241d17e0c7c8416dd8b1f6d4155f99bb1c37a
diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -174,9 +174,13 @@ def language_status(self, language): 'is_base_language': is_base_language, 'examples': { 'count': examples_count, - 'entities': list(examples.values_list( - 'entities__entity', - flat=True).distinct()), + 'entities': list( + set( + filter( + lambda x: x, + examples.values_list( + 'entities__entity', + flat=True).distinct()))), }, 'base_translations': { 'count': base_translations_count, diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.6.0', + version='1.6.1', description='bothub', packages=find_packages(), install_requires=install_requires,
diff --git a/bothub/api/tests/repository.py b/bothub/api/tests/repository.py --- a/bothub/api/tests/repository.py +++ b/bothub/api/tests/repository.py @@ -9,6 +9,8 @@ from bothub.common import languages from bothub.common.models import RepositoryCategory from bothub.common.models import Repository +from bothub.common.models import RepositoryExample +from bothub.common.models import RepositoryExampleEntity from ..views import NewRepositoryViewSet from ..views import RepositoryViewSet @@ -576,3 +578,94 @@ def test_text_required(self): response.status_code, status.HTTP_400_BAD_REQUEST) self.assertIn('text', content_data.keys()) + + +class LanguagesStatusTestCase(TestCase): + def setUp(self): + self.factory = RequestFactory() + + self.owner, self.owner_token = create_user_and_token('owner') + self.user, self.user_token = create_user_and_token() + + self.repository = Repository.objects.create( + owner=self.owner, + name='Testing', + slug='test', + language=languages.LANGUAGE_EN) + + self.example_1 = RepositoryExample.objects.create( + repository_update=self.repository.current_update( + languages.LANGUAGE_EN), + text='hi', + intent='greet') + self.example_2 = RepositoryExample.objects.create( + repository_update=self.repository.current_update( + languages.LANGUAGE_EN), + text='Here is London', + intent='place') + self.example_3 = RepositoryExample.objects.create( + repository_update=self.repository.current_update( + languages.LANGUAGE_EN), + text='Here is Brazil', + intent='place') + + def request(self, repository, token): + authorization_header = { + 'HTTP_AUTHORIZATION': 'Token {}'.format(token.key), + } + request = self.factory.get( + '/api/repository/{}/{}/languagesstatus/'.format( + repository.owner.nickname, + repository.slug), + **authorization_header) + response = RepositoryViewSet.as_view( + {'get': 'languagesstatus'})(request) + response.render() + content_data = json.loads(response.content) + return (response, content_data,) + + def test_okay(self): + response, content_data = self.request( + self.repository, + self.owner_token) + self.assertEqual( + response.status_code, + status.HTTP_200_OK) + + def test_unique_entities(self): + RepositoryExampleEntity.objects.create( + repository_example=self.example_1, + start=0, + end=0, + entity='entity1') + RepositoryExampleEntity.objects.create( + repository_example=self.example_2, + start=0, + end=0, + entity='entity1') + RepositoryExampleEntity.objects.create( + repository_example=self.example_3, + start=0, + end=0, + entity='entity2') + + counter = {} + response, content_data = self.request( + self.repository, + self.owner_token) + languages_status = content_data.get('languages_status') + for language in languages_status: + language_status = languages_status.get(language) + for entity in language_status.get('examples').get('entities'): + counter[entity] = counter.get(entity, 0) + 1 + self.failIfEqual(counter.get(entity), 2) + + def test_none_entities(self): + response, content_data = self.request( + self.repository, + self.owner_token) + languages_status = content_data.get('languages_status') + for language in languages_status: + language_status = languages_status.get(language) + for entity in language_status.get('examples').get('entities'): + self.failIfEqual(entity, None)
Languages Status show repeated examples entities ![captura de tela 2018-05-28 as 10 35 27](https://user-images.githubusercontent.com/8301135/40616871-e1ec8188-6262-11e8-9531-b680bdd839fe.png)
2018-05-28T16:48:54
weni-ai/bothub-engine
76
weni-ai__bothub-engine-76
[ "72" ]
461e5cd51cdfca325520653b1b008fac391b9d46
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.7.1', + version='1.7.2', description='bothub', packages=find_packages(), install_requires=install_requires,
Next link in pagination broken in production The links starts with ```https://bothub/```, correct is ```https://bothub.it/```
2018-05-30T16:20:58
weni-ai/bothub-engine
77
weni-ai__bothub-engine-77
[ "69" ]
80b79cc6537fd2000d60a55f9bb5ba6afc7ce9d8
diff --git a/bothub/api/serializers/translate.py b/bothub/api/serializers/translate.py --- a/bothub/api/serializers/translate.py +++ b/bothub/api/serializers/translate.py @@ -9,6 +9,7 @@ from ..validators import CanContributeInRepositoryTranslatedExampleValidator from ..validators import CanContributeInRepositoryExampleValidator from ..validators import TranslatedExampleEntitiesValidator +from ..validators import TranslatedExampleLanguageValidator class RepositoryTranslatedExampleEntitySeralizer(serializers.ModelSerializer): @@ -95,6 +96,7 @@ class Meta: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.validators.append(TranslatedExampleEntitiesValidator()) + self.validators.append(TranslatedExampleLanguageValidator()) original_example = serializers.PrimaryKeyRelatedField( queryset=RepositoryExample.objects, diff --git a/bothub/api/validators.py b/bothub/api/validators.py --- a/bothub/api/validators.py +++ b/bothub/api/validators.py @@ -51,3 +51,11 @@ def __call__(self, attrs): list(map(lambda x: x.to_dict, original_example.entities.all()))) if not entities_valid: raise ValidationError({'entities': _('Invalid entities')}) + + +class TranslatedExampleLanguageValidator(object): + def __call__(self, attrs): + original_example = attrs.get('original_example') + language = attrs.get('language') + if original_example.repository_update.language == language: + raise ValidationError({'language': _('Can\'t translate to same language')})
diff --git a/bothub/api/tests/translate.py b/bothub/api/tests/translate.py --- a/bothub/api/tests/translate.py +++ b/bothub/api/tests/translate.py @@ -163,6 +163,22 @@ def test_entities_no_valid(self): len(content_data.get('entities')), 1) + def test_can_not_translate_to_same_language(self): + response, content_data = self.request( + { + 'original_example': self.example.id, + 'language': self.example.repository_update.language, + 'text': 'oi', + 'entities': [], + }, + self.owner_token) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertIn( + 'language', + content_data.keys()) + class RepositoryTranslatedExampleRetrieveTestCase(TestCase): def setUp(self):
Is possible translate example to same language
2018-05-30T16:46:38
weni-ai/bothub-engine
78
weni-ai__bothub-engine-78
[ "69" ]
502ba2354c3dc3aa86ba01f78cac73956d131fa3
diff --git a/bothub/api/serializers/translate.py b/bothub/api/serializers/translate.py --- a/bothub/api/serializers/translate.py +++ b/bothub/api/serializers/translate.py @@ -9,6 +9,7 @@ from ..validators import CanContributeInRepositoryTranslatedExampleValidator from ..validators import CanContributeInRepositoryExampleValidator from ..validators import TranslatedExampleEntitiesValidator +from ..validators import TranslatedExampleLanguageValidator class RepositoryTranslatedExampleEntitySeralizer(serializers.ModelSerializer): @@ -95,6 +96,7 @@ class Meta: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.validators.append(TranslatedExampleEntitiesValidator()) + self.validators.append(TranslatedExampleLanguageValidator()) original_example = serializers.PrimaryKeyRelatedField( queryset=RepositoryExample.objects, diff --git a/bothub/api/validators.py b/bothub/api/validators.py --- a/bothub/api/validators.py +++ b/bothub/api/validators.py @@ -51,3 +51,11 @@ def __call__(self, attrs): list(map(lambda x: x.to_dict, original_example.entities.all()))) if not entities_valid: raise ValidationError({'entities': _('Invalid entities')}) + + +class TranslatedExampleLanguageValidator(object): + def __call__(self, attrs): + original_example = attrs.get('original_example') + language = attrs.get('language') + if original_example.repository_update.language == language: + raise ValidationError({'language': _('Can\'t translate to same language')}) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.7.2', + version='1.7.3', description='bothub', packages=find_packages(), install_requires=install_requires,
diff --git a/bothub/api/tests/translate.py b/bothub/api/tests/translate.py --- a/bothub/api/tests/translate.py +++ b/bothub/api/tests/translate.py @@ -163,6 +163,22 @@ def test_entities_no_valid(self): len(content_data.get('entities')), 1) + def test_can_not_translate_to_same_language(self): + response, content_data = self.request( + { + 'original_example': self.example.id, + 'language': self.example.repository_update.language, + 'text': 'oi', + 'entities': [], + }, + self.owner_token) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertIn( + 'language', + content_data.keys()) + class RepositoryTranslatedExampleRetrieveTestCase(TestCase): def setUp(self):
Is possible translate example to same language
2018-05-30T16:50:46
weni-ai/bothub-engine
81
weni-ai__bothub-engine-81
[ "62" ]
c8662aada0b54a63af4c00208594891d7f647845
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -352,7 +352,8 @@ def train(self, request, **kwargs): @detail_route( methods=['POST'], - url_name='repository-analyze') + url_name='repository-analyze', + permission_classes=[]) def analyze(self, request, **kwargs): repository = self.get_object() user_authorization = repository.get_user_authorization(request.user) @@ -369,12 +370,9 @@ def analyze(self, request, **kwargs): except Exception: pass raise APIException( # pragma: no cover - { - 'status_code': request.status_code, - 'response': response, - }, + response, code=request.status_code) - return Response(request.json()) # pragma: no cover + return Response(response) # pragma: no cover def get_serializer_class(self): if self.request and self.request.method in \
diff --git a/bothub/api/tests/repository.py b/bothub/api/tests/repository.py --- a/bothub/api/tests/repository.py +++ b/bothub/api/tests/repository.py @@ -525,6 +525,12 @@ def setUp(self): name='Testing', slug='test', language=languages.LANGUAGE_EN) + self.private_repository = Repository.objects.create( + owner=self.owner, + name='Testing', + slug='private', + language=languages.LANGUAGE_EN, + is_private=True) def request(self, repository, token, data): authorization_header = { @@ -536,14 +542,17 @@ def request(self, repository, token, data): repository.slug), data, **authorization_header) - response = RepositoryViewSet.as_view({'post': 'analyze'})(request) + response = RepositoryViewSet.as_view({'post': 'analyze'})( + request, + owner__nickname=repository.owner.nickname, + slug=repository.slug) response.render() content_data = json.loads(response.content) return (response, content_data,) - def test_permission_denied(self): + def test_permission_denied_in_private_repository(self): response, content_data = self.request( - self.repository, + self.private_repository, self.user_token, { 'language': 'en',
Forbidden analyze text in public repository
"Analyze text" use POST method, the validators assume it as write action and block the request. Fix here: https://github.com/push-flow/bothub/blob/master/bothub/api/views.py#L282
2018-05-30T18:09:36
weni-ai/bothub-engine
82
weni-ai__bothub-engine-82
[ "62" ]
dee32d2e3f0d1729d201960cb4684062d7a8bd25
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -352,7 +352,8 @@ def train(self, request, **kwargs): @detail_route( methods=['POST'], - url_name='repository-analyze') + url_name='repository-analyze', + permission_classes=[]) def analyze(self, request, **kwargs): repository = self.get_object() user_authorization = repository.get_user_authorization(request.user) @@ -369,12 +370,9 @@ def analyze(self, request, **kwargs): except Exception: pass raise APIException( # pragma: no cover - { - 'status_code': request.status_code, - 'response': response, - }, + response, code=request.status_code) - return Response(request.json()) # pragma: no cover + return Response(response) # pragma: no cover def get_serializer_class(self): if self.request and self.request.method in \ diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.7.4', + version='1.7.5', description='bothub', packages=find_packages(), install_requires=install_requires,
diff --git a/bothub/api/tests/repository.py b/bothub/api/tests/repository.py --- a/bothub/api/tests/repository.py +++ b/bothub/api/tests/repository.py @@ -525,6 +525,12 @@ def setUp(self): name='Testing', slug='test', language=languages.LANGUAGE_EN) + self.private_repository = Repository.objects.create( + owner=self.owner, + name='Testing', + slug='private', + language=languages.LANGUAGE_EN, + is_private=True) def request(self, repository, token, data): authorization_header = { @@ -536,14 +542,17 @@ def request(self, repository, token, data): repository.slug), data, **authorization_header) - response = RepositoryViewSet.as_view({'post': 'analyze'})(request) + response = RepositoryViewSet.as_view({'post': 'analyze'})( + request, + owner__nickname=repository.owner.nickname, + slug=repository.slug) response.render() content_data = json.loads(response.content) return (response, content_data,) - def test_permission_denied(self): + def test_permission_denied_in_private_repository(self): response, content_data = self.request( - self.repository, + self.private_repository, self.user_token, { 'language': 'en',
Forbidden analyze text in public repository
"Analyze text" use POST method, the validators assume it as write action and block the request. Fix here: https://github.com/push-flow/bothub/blob/master/bothub/api/views.py#L282
2018-05-30T18:13:53
weni-ai/bothub-engine
87
weni-ai__bothub-engine-87
[ "84" ]
3c37dfc9ee46123d532b62cb766883cb0844bc42
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -453,7 +453,6 @@ class RepositoryExampleViewSet( queryset = RepositoryExample.objects serializer_class = RepositoryExampleSerializer permission_classes = [ - permissions.IsAuthenticated, RepositoryExamplePermission, ]
Example retrieve need user authenticated AnonUser can't retireve example infos.
2018-06-04T12:20:26
weni-ai/bothub-engine
88
weni-ai__bothub-engine-88
[ "84" ]
6934f13b3c5d48ca37522efb7aa1d82e8597ca1f
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -453,7 +453,6 @@ class RepositoryExampleViewSet( queryset = RepositoryExample.objects serializer_class = RepositoryExampleSerializer permission_classes = [ - permissions.IsAuthenticated, RepositoryExamplePermission, ] diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.8.0', + version='1.8.1', description='bothub', packages=find_packages(), install_requires=install_requires,
Example retrieve need user authenticated AnonUser can't retireve example infos.
2018-06-04T12:35:48
weni-ai/bothub-engine
104
weni-ai__bothub-engine-104
[ "96" ]
397eda53315402864eed61fe7b384c875dd76c57
diff --git a/bothub/authentication/migrations/0004_auto_20180605_1357.py b/bothub/authentication/migrations/0004_auto_20180605_1357.py new file mode 100644 --- /dev/null +++ b/bothub/authentication/migrations/0004_auto_20180605_1357.py @@ -0,0 +1,20 @@ +# Generated by Django 2.0.2 on 2018-06-05 13:57 + +import django.core.validators +from django.db import migrations, models +import re + + +class Migration(migrations.Migration): + + dependencies = [ + ('authentication', '0003_auto_20180522_1705'), + ] + + operations = [ + migrations.AlterField( + model_name='user', + name='nickname', + field=models.CharField(help_text="User's nickname, using letters, numbers, underscores and hyphens without spaces.", max_length=16, unique=True, validators=[django.core.validators.RegexValidator(re.compile('^[-a-zA-Z0-9_]+\\Z'), "Enter a valid 'nickname' consisting of letters, numbers, underscores or hyphens.", 'invalid')], verbose_name='nickname'), + ), + ] diff --git a/bothub/authentication/models.py b/bothub/authentication/models.py --- a/bothub/authentication/models.py +++ b/bothub/authentication/models.py @@ -68,7 +68,8 @@ class Meta: max_length=16, validators=[validate_user_nickname], help_text=_('User\'s nickname, using letters, numbers, underscores ' + - 'and hyphens without spaces.')) + 'and hyphens without spaces.'), + unique=True) locale = models.CharField( _('locale'), max_length=48,
diff --git a/bothub/api/tests/user.py b/bothub/api/tests/user.py --- a/bothub/api/tests/user.py +++ b/bothub/api/tests/user.py @@ -60,6 +60,22 @@ def test_invalid_password(self): 'password', content_data.keys()) + def test_unique_nickname(self): + nickname = 'fake' + User.objects.create_user('[email protected]', nickname) + response, content_data = self.request({ + 'email': '[email protected]', + 'name': 'Fake', + 'nickname': nickname, + 'password': 'abc!1234', + }) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertIn( + 'nickname', + content_data.keys()) + class UserUpdateTestCase(TestCase): def setUp(self): diff --git a/bothub/authentication/tests.py b/bothub/authentication/tests.py --- a/bothub/authentication/tests.py +++ b/bothub/authentication/tests.py @@ -1,4 +1,5 @@ from django.test import TestCase +from django.db import IntegrityError from .models import User @@ -24,3 +25,8 @@ def test_new_superuser_fail_issuperuser_false(self): '[email protected]', 'fake', is_superuser=False) + + def test_user_unique_nickname(self): + User.objects.create_user('[email protected]', 'fake') + with self.assertRaises(IntegrityError): + User.objects.create_user('[email protected]', 'fake') diff --git a/bothub/common/tests.py b/bothub/common/tests.py --- a/bothub/common/tests.py +++ b/bothub/common/tests.py @@ -258,7 +258,7 @@ def test_does_not_have_translation(self): class RepositoryTestCase(TestCase): def setUp(self): - self.owner = User.objects.create_user('[email protected]', 'user') + self.owner = User.objects.create_user('[email protected]', 'owner') self.user = User.objects.create_user('[email protected]', 'user') self.repository = Repository.objects.create( @@ -354,7 +354,7 @@ def teste_delete(self): class RepositoryAuthorizationTestCase(TestCase): def setUp(self): - self.owner = User.objects.create_user('[email protected]', 'user') + self.owner = User.objects.create_user('[email protected]', 'owner') self.user = User.objects.create_user('[email protected]', 'user') self.repository = Repository.objects.create(
Duplicated nicknames Duplicated nicknames are enabled but it's not supposed to be, it's a security issue.
User's nickname field must be unique https://github.com/push-flow/bothub/blob/master/bothub/authentication/models.py#L66
2018-06-05T14:11:25
weni-ai/bothub-engine
106
weni-ai__bothub-engine-106
[ "99" ]
ba5ada0cf1160e244a475c710c70252d5c343fd6
diff --git a/bothub/api/serializers/example.py b/bothub/api/serializers/example.py --- a/bothub/api/serializers/example.py +++ b/bothub/api/serializers/example.py @@ -9,6 +9,7 @@ from ..fields import EntityText from ..validators import CanContributeInRepositoryExampleValidator from ..validators import CanContributeInRepositoryValidator +from ..validators import ExampleWithIntentOrEntityValidator from .translate import RepositoryTranslatedExampleSerializer @@ -109,6 +110,10 @@ class Meta: many=True, style={'text_field': 'text'}) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.validators.append(ExampleWithIntentOrEntityValidator()) + def validate_repository(self, repository): return repository.current_update() diff --git a/bothub/api/validators.py b/bothub/api/validators.py --- a/bothub/api/validators.py +++ b/bothub/api/validators.py @@ -60,3 +60,12 @@ def __call__(self, attrs): if original_example.repository_update.language == language: raise ValidationError({'language': _( 'Can\'t translate to the same language')}) + + +class ExampleWithIntentOrEntityValidator(object): + def __call__(self, attrs): + intent = attrs.get('intent') + entities = attrs.get('entities') + + if not intent and not entities: + raise ValidationError(_('Define a intent or one entity'))
diff --git a/bothub/api/tests/example.py b/bothub/api/tests/example.py --- a/bothub/api/tests/example.py +++ b/bothub/api/tests/example.py @@ -141,6 +141,19 @@ def test_with_entities(self): len(content_data.get('entities')), 1) + def test_intent_or_entity_required(self): + response, content_data = self.request( + self.owner_token, + { + 'repository': str(self.repository.uuid), + 'text': 'hi', + 'intent': '', + 'entities': [], + }) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + class RepositoryExampleRetrieveTestCase(TestCase): def setUp(self):
Disallow samples without intent or entities Disallow samples creation without an intent or one entity at least.
Validate it in API level https://github.com/push-flow/bothub/blob/master/bothub/api/serializers/example.py#L82
2018-06-05T14:54:19
weni-ai/bothub-engine
107
weni-ai__bothub-engine-107
[ "102", "102" ]
c89f38ec830c0003ab46918e38cbda8a269b79ba
diff --git a/bothub/api/validators.py b/bothub/api/validators.py --- a/bothub/api/validators.py +++ b/bothub/api/validators.py @@ -46,11 +46,24 @@ def set_context(self, serializer): class TranslatedExampleEntitiesValidator(object): def __call__(self, attrs): original_example = attrs.get('original_example') + entities_list = list(map(lambda x: dict(x), attrs.get('entities'))) + original_entities_list = list(map( + lambda x: x.to_dict, + original_example.entities.all())) entities_valid = RepositoryTranslatedExample.same_entities_validator( - list(map(lambda x: dict(x), attrs.get('entities'))), - list(map(lambda x: x.to_dict, original_example.entities.all()))) + entities_list, + original_entities_list) if not entities_valid: - raise ValidationError({'entities': _('Invalid entities')}) + raise ValidationError({'entities': _( + 'Entities need to match from the original content. ' + + 'Entities: {0}. Original entities: {1}.').format( + RepositoryTranslatedExample.count_entities( + entities_list, + to_str=True), + RepositoryTranslatedExample.count_entities( + original_entities_list, + to_str=True), + )}) class TranslatedExampleLanguageValidator(object): diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -2,6 +2,8 @@ import base64 import requests +from functools import reduce + from django.db import models from django.utils.translation import gettext as _ from django.utils import timezone @@ -466,6 +468,21 @@ def same_entities_validator(cls, a, b): return False return True + @classmethod + def count_entities(cls, entities_list, to_str=False): + r = {} + reduce( + lambda current, next: current.update({ + next.get('entity'): current.get('entity', 0) + 1, + }), + entities_list, + r) + if to_str: + r = ', '.join(map( + lambda x: '{} {}'.format(x[1], x[0]), + r.items())) if entities_list else 'no entities' + return r + @property def has_valid_entities(self): original_entities = self.original_example.entities.all()
Update invalid entities text on translation Replace the `Invalid Entities` text to `Entities need to match from the original content` when translating a sample with entities. Update invalid entities text on translation Replace the `Invalid Entities` text to `Entities need to match from the original content` when translating a sample with entities.
Change here: https://github.com/push-flow/bothub/blob/master/bothub/api/validators.py#L53 Change here: https://github.com/push-flow/bothub/blob/master/bothub/api/validators.py#L53
2018-06-05T16:34:10
weni-ai/bothub-engine
116
weni-ai__bothub-engine-116
[ "115" ]
efedaacdb7d50d31c50e5ae1af99c219fc178209
diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -8,6 +8,7 @@ from django.utils.translation import gettext as _ from django.utils import timezone from django.conf import settings +from django.core.validators import RegexValidator, _lazy_re_compile from bothub.authentication.models import User @@ -18,6 +19,15 @@ from .exceptions import DoesNotHaveTranslation +entity_and_intent_regex = _lazy_re_compile(r'^[-a-z0-9_]+\Z') +validate_entity_and_intent = RegexValidator( + entity_and_intent_regex, + _('Enter a valid value consisting of lowercase letters, numbers, ' + + 'underscores or hyphens.'), + 'invalid' +) + + class RepositoryCategory(models.Model): class Meta: verbose_name = _('repository category') @@ -379,7 +389,8 @@ class Meta: _('intent'), max_length=64, blank=True, - help_text=_('Example intent reference')) + help_text=_('Example intent reference'), + validators=[validate_entity_and_intent]) created_at = models.DateTimeField( _('created at'), auto_now_add=True) @@ -525,7 +536,8 @@ class Meta: entity = models.CharField( _('entity'), max_length=64, - help_text=_('Entity name')) + help_text=_('Entity name'), + validators=[validate_entity_and_intent]) created_at = models.DateTimeField( _('created at'), auto_now_add=True)
diff --git a/bothub/api/tests/example.py b/bothub/api/tests/example.py --- a/bothub/api/tests/example.py +++ b/bothub/api/tests/example.py @@ -154,6 +154,44 @@ def test_intent_or_entity_required(self): response.status_code, status.HTTP_400_BAD_REQUEST) + def test_entity_with_special_char(self): + response, content_data = self.request( + self.owner_token, + { + 'repository': str(self.repository.uuid), + 'text': 'my name is douglas', + 'intent': '', + 'entities': [ + { + 'start': 11, + 'end': 18, + 'entity': 'nam&', + }, + ], + }) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertEqual( + len(content_data.get('entities')), + 1) + + def test_intent_with_special_char(self): + response, content_data = self.request( + self.owner_token, + { + 'repository': str(self.repository.uuid), + 'text': 'my name is douglas', + 'intent': 'nam$s', + 'entities': [], + }) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertEqual( + len(content_data.get('intent')), + 1) + class RepositoryExampleRetrieveTestCase(TestCase): def setUp(self):
Validate entity chars, no special chars
2018-06-07T21:16:45
weni-ai/bothub-engine
117
weni-ai__bothub-engine-117
[ "115" ]
338c2d938319014dd60972f6e984c7a0031506cb
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -9,6 +9,7 @@ from rest_framework.authtoken.models import Token from rest_framework import status from rest_framework.filters import OrderingFilter +from rest_framework.filters import SearchFilter from rest_framework.permissions import IsAuthenticated from django.utils.translation import gettext as _ from django.db.models import Count @@ -174,6 +175,7 @@ class RepositoriesFilter(filters.FilterSet): class Meta: model = Repository fields = [ + 'name', 'categories', ] @@ -718,6 +720,15 @@ class RepositoriesViewSet( serializer_class = RepositorySerializer queryset = Repository.objects.all().publics().order_by_relevance() filter_class = RepositoriesFilter + filter_backends = [ + DjangoFilterBackend, + SearchFilter, + ] + search_fields = [ + '$name', + '^name', + '=name', + ] class TranslationsViewSet( diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -8,6 +8,7 @@ from django.utils.translation import gettext as _ from django.utils import timezone from django.conf import settings +from django.core.validators import RegexValidator, _lazy_re_compile from bothub.authentication.models import User @@ -18,6 +19,15 @@ from .exceptions import DoesNotHaveTranslation +entity_and_intent_regex = _lazy_re_compile(r'^[-a-z0-9_]+\Z') +validate_entity_and_intent = RegexValidator( + entity_and_intent_regex, + _('Enter a valid value consisting of lowercase letters, numbers, ' + + 'underscores or hyphens.'), + 'invalid' +) + + class RepositoryCategory(models.Model): class Meta: verbose_name = _('repository category') @@ -379,7 +389,8 @@ class Meta: _('intent'), max_length=64, blank=True, - help_text=_('Example intent reference')) + help_text=_('Example intent reference'), + validators=[validate_entity_and_intent]) created_at = models.DateTimeField( _('created at'), auto_now_add=True) @@ -525,7 +536,8 @@ class Meta: entity = models.CharField( _('entity'), max_length=64, - help_text=_('Entity name')) + help_text=_('Entity name'), + validators=[validate_entity_and_intent]) created_at = models.DateTimeField( _('created at'), auto_now_add=True) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.8.5', + version='1.8.6', description='bothub', packages=find_packages(), install_requires=install_requires,
diff --git a/bothub/api/tests/example.py b/bothub/api/tests/example.py --- a/bothub/api/tests/example.py +++ b/bothub/api/tests/example.py @@ -154,6 +154,44 @@ def test_intent_or_entity_required(self): response.status_code, status.HTTP_400_BAD_REQUEST) + def test_entity_with_special_char(self): + response, content_data = self.request( + self.owner_token, + { + 'repository': str(self.repository.uuid), + 'text': 'my name is douglas', + 'intent': '', + 'entities': [ + { + 'start': 11, + 'end': 18, + 'entity': 'nam&', + }, + ], + }) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertEqual( + len(content_data.get('entities')), + 1) + + def test_intent_with_special_char(self): + response, content_data = self.request( + self.owner_token, + { + 'repository': str(self.repository.uuid), + 'text': 'my name is douglas', + 'intent': 'nam$s', + 'entities': [], + }) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertEqual( + len(content_data.get('intent')), + 1) + class RepositoryExampleRetrieveTestCase(TestCase): def setUp(self): diff --git a/bothub/api/tests/repository.py b/bothub/api/tests/repository.py --- a/bothub/api/tests/repository.py +++ b/bothub/api/tests/repository.py @@ -462,9 +462,10 @@ def setUp(self): is_private=True) self.repository.categories.add(self.category) - def request(self): + def request(self, data={}): request = self.factory.get( - '/api/repositories/') + '/api/repositories/', + data) response = RepositoriesViewSet.as_view({'get': 'list'})(request) response.render() content_data = json.loads(response.content) @@ -479,6 +480,27 @@ def test_show_just_publics(self): uuid.UUID(content_data.get('results')[0].get('uuid')), self.repository.uuid) + def test_filter_by_name(self): + response, content_data = self.request({ + 'search': 'Test', + }) + self.assertEqual( + response.status_code, + status.HTTP_200_OK) + self.assertEqual( + content_data.get('count'), + 1) + + response, content_data = self.request({ + 'search': 'z', + }) + self.assertEqual( + response.status_code, + status.HTTP_200_OK) + self.assertEqual( + content_data.get('count'), + 0) + class TrainRepositoryTestCase(TestCase): def setUp(self):
Validate entity chars, no special chars
2018-06-08T11:44:47
weni-ai/bothub-engine
119
weni-ai__bothub-engine-119
[ "118" ]
665ea5a60832a18d18a1235f62e2ee24ec3062fd
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -418,13 +418,26 @@ def get_serializer_class(self): return self.edit_serializer_class return self.serializer_class - def get_permissions(self): - fn = getattr(self, self.action) + def get_action_permissions_classes(self): + if not self.action: + return None + fn = getattr(self, self.action, None) + if not fn: + return None fn_kwargs = getattr(fn, 'kwargs', None) - if fn_kwargs: - permission_classes = fn_kwargs.get('permission_classes') - if permission_classes: - return [permission() for permission in permission_classes] + if not fn_kwargs: + return None + permission_classes = fn_kwargs.get('permission_classes') + if not permission_classes: + return None + return permission_classes + + def get_permissions(self): + action_permissions_classes = self.get_action_permissions_classes() + if action_permissions_classes: + return [permission() + for permission + in action_permissions_classes] return super().get_permissions()
Repository edit options error RepositoryViewSet raised this exception: ``` 'RepositoryViewSet' object has no attribute 'metadata' ```
2018-06-08T13:39:20
weni-ai/bothub-engine
120
weni-ai__bothub-engine-120
[ "118" ]
be551e6ee4bf2054bd403315e5c57e1cb80bfc22
diff --git a/bothub/api/views.py b/bothub/api/views.py --- a/bothub/api/views.py +++ b/bothub/api/views.py @@ -418,13 +418,26 @@ def get_serializer_class(self): return self.edit_serializer_class return self.serializer_class - def get_permissions(self): - fn = getattr(self, self.action) + def get_action_permissions_classes(self): + if not self.action: + return None + fn = getattr(self, self.action, None) + if not fn: + return None fn_kwargs = getattr(fn, 'kwargs', None) - if fn_kwargs: - permission_classes = fn_kwargs.get('permission_classes') - if permission_classes: - return [permission() for permission in permission_classes] + if not fn_kwargs: + return None + permission_classes = fn_kwargs.get('permission_classes') + if not permission_classes: + return None + return permission_classes + + def get_permissions(self): + action_permissions_classes = self.get_action_permissions_classes() + if action_permissions_classes: + return [permission() + for permission + in action_permissions_classes] return super().get_permissions() diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.8.6', + version='1.8.7', description='bothub', packages=find_packages(), install_requires=install_requires,
Repository edit options error RepositoryViewSet raised this exception: ``` 'RepositoryViewSet' object has no attribute 'metadata' ```
2018-06-08T14:14:46
weni-ai/bothub-engine
127
weni-ai__bothub-engine-127
[ "126" ]
3764ca42889a36d96ac72241f84f1def73ad1cb8
diff --git a/bothub/authentication/migrations/0005_auto_20180620_2059.py b/bothub/authentication/migrations/0005_auto_20180620_2059.py new file mode 100644 --- /dev/null +++ b/bothub/authentication/migrations/0005_auto_20180620_2059.py @@ -0,0 +1,21 @@ +# Generated by Django 2.0.6 on 2018-06-20 20:59 + +import bothub.authentication.models +import django.core.validators +from django.db import migrations, models +import re + + +class Migration(migrations.Migration): + + dependencies = [ + ('authentication', '0004_auto_20180605_1357'), + ] + + operations = [ + migrations.AlterField( + model_name='user', + name='nickname', + field=models.CharField(help_text="User's nickname, using letters, numbers, underscores and hyphens without spaces.", max_length=16, unique=True, validators=[django.core.validators.RegexValidator(re.compile('^[-a-zA-Z0-9_]+\\Z'), "Enter a valid 'nickname' consisting of letters, numbers, underscores or hyphens.", 'invalid'), bothub.authentication.models.validate_user_nickname_value], verbose_name='nickname'), + ), + ] diff --git a/bothub/authentication/models.py b/bothub/authentication/models.py --- a/bothub/authentication/models.py +++ b/bothub/authentication/models.py @@ -8,10 +8,11 @@ from django.core.mail import send_mail from django.template.loader import render_to_string from django.conf import settings +from django.core.exceptions import ValidationError user_nickname_re = _lazy_re_compile(r'^[-a-zA-Z0-9_]+\Z') -validate_user_nickname = RegexValidator( +validate_user_nickname_format = RegexValidator( user_nickname_re, _('Enter a valid \'nickname\' consisting of letters, numbers, ' + 'underscores or hyphens.'), @@ -19,6 +20,12 @@ ) +def validate_user_nickname_value(value): + if value in ['api', 'docs', 'admin']: + raise ValidationError( + _('The user nickname can\'t be \'{}\'').format(value)) + + class UserManager(BaseUserManager): def _create_user(self, email, nickname, password=None, **extra_fields): if not email: @@ -66,7 +73,10 @@ class Meta: nickname = models.CharField( _('nickname'), max_length=16, - validators=[validate_user_nickname], + validators=[ + validate_user_nickname_format, + validate_user_nickname_value, + ], help_text=_('User\'s nickname, using letters, numbers, underscores ' + 'and hyphens without spaces.'), unique=True)
diff --git a/bothub/api/tests/test_user.py b/bothub/api/tests/test_user.py --- a/bothub/api/tests/test_user.py +++ b/bothub/api/tests/test_user.py @@ -76,6 +76,28 @@ def test_unique_nickname(self): 'nickname', content_data.keys()) + def test_invalid_nickname_url_conflict(self): + URL_PATHS = [ + 'api', + 'docs', + 'admin', + ] + + for url_path in URL_PATHS: + response, content_data = self.request({ + 'email': '{}@fake.com'.format(url_path), + 'name': 'Fake', + 'nickname': url_path, + 'password': 'abc!1234', + }) + + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertIn( + 'nickname', + content_data.keys()) + class UserUpdateTestCase(TestCase): def setUp(self):
User can set "api", "docs" or "admin" as nickname In production this generate url conflict
Reported in https://github.com/push-flow/bothub-issues/issues/8
2018-06-20T21:03:51
weni-ai/bothub-engine
140
weni-ai__bothub-engine-140
[ "138" ]
fb91b75dbaf33e3d51804947ebdafe281e7f89a4
diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -181,9 +181,10 @@ def votes_sum(self): @property def intents(self): return list(set(self.examples( - deleted=False).values_list( - 'intent', - flat=True))) + deleted=False).exclude( + intent='').values_list( + 'intent', + flat=True))) @property def entities(self):
diff --git a/bothub/common/tests.py b/bothub/common/tests.py --- a/bothub/common/tests.py +++ b/bothub/common/tests.py @@ -312,6 +312,16 @@ def test_entities(self): 'name', self.repository.entities) + def test_not_blank_value_in_intents(self): + RepositoryExample.objects.create( + repository_update=self.repository.current_update( + languages.LANGUAGE_EN), + text='hi') + + self.assertNotIn( + '', + self.repository.intents) + class RepositoryExampleTestCase(TestCase): def setUp(self):
Intents field in repository serializer return blank item
2018-07-02T13:48:49
weni-ai/bothub-engine
145
weni-ai__bothub-engine-145
[ "144" ]
972efeca2bf0a9268ebeae6708367d76379ca2e9
diff --git a/bothub/settings.py b/bothub/settings.py --- a/bothub/settings.py +++ b/bothub/settings.py @@ -169,7 +169,7 @@ default='webmaster@localhost') SERVER_EMAIL = config('SERVER_EMAIL', default='root@localhost') -if not DEBUG and envvar_EMAIL_HOST: +if envvar_EMAIL_HOST: EMAIL_HOST = envvar_EMAIL_HOST EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int) EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')
Just email console backend in development mode When EMAIL_HOST is setted and DEBUG is True email continue on console
2018-07-03T18:46:18
weni-ai/bothub-engine
150
weni-ai__bothub-engine-150
[ "149" ]
7d3fff80af4462991ecf70a4aa42b0e98494e24d
diff --git a/bothub/settings.py b/bothub/settings.py --- a/bothub/settings.py +++ b/bothub/settings.py @@ -122,7 +122,7 @@ # Static files (CSS, JavaScript, Images) -STATIC_URL = '/static/' +STATIC_URL = config('STATIC_URL', default='/static/') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Relative STATIC_URL in production broken email images
2018-07-04T13:18:58
weni-ai/bothub-engine
152
weni-ai__bothub-engine-152
[ "149" ]
6a1667e333157a9f6b16e964358ff44473e773ea
diff --git a/bothub/settings.py b/bothub/settings.py --- a/bothub/settings.py +++ b/bothub/settings.py @@ -122,7 +122,7 @@ # Static files (CSS, JavaScript, Images) -STATIC_URL = '/static/' +STATIC_URL = config('STATIC_URL', default='/static/') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ setup( name='bothub', - version='1.12.0', + version='1.12.1', description='bothub', packages=find_packages(), install_requires=[
Relative STATIC_URL in production broken email images
2018-07-04T13:23:02
weni-ai/bothub-engine
166
weni-ai__bothub-engine-166
[ "165", "161", "161" ]
97a86b57eb8e5cf8b37e50200e300eeaf5ba9225
diff --git a/bothub/health/checks.py b/bothub/health/checks.py --- a/bothub/health/checks.py +++ b/bothub/health/checks.py @@ -1,23 +1,37 @@ +import logging + +from rest_framework import status + + +logger = logging.getLogger('bothub.health.checks') + +CHECK_ACCESSIBLE_API_URL = '/api/repositories/' + + def check_database_connection(**kwargs): from django.db import connections from django.db.utils import OperationalError - db_conn = connections['default'] - if not db_conn: - return False - try: - db_conn.cursor() - return True - except OperationalError as e: + if len(connections.all()) is 0: return False + logger.info('found {} database connection'.format(len(connections.all()))) + for i, conn in enumerate(connections.all(), 1): + try: + conn.cursor() + logger.info('#{} db connection OKAY'.format(i)) + except OperationalError as e: + logger.warning('#{} db connection ERROR'.format(i)) + return False + return True def check_accessible_api(request, **kwargs): - import requests - HTTP_HOST = request.META.get('HTTP_HOST') - repositories_url = 'http://{}/api/repositories/'.format(HTTP_HOST) - request = requests.get(repositories_url) - try: - request.raise_for_status() + from django.test import Client + logger.info('making request to {}'.format(CHECK_ACCESSIBLE_API_URL)) + client = Client() + response = client.get(CHECK_ACCESSIBLE_API_URL) + logger.info('{} status code: {}'.format( + CHECK_ACCESSIBLE_API_URL, + response.status_code)) + if response.status_code is status.HTTP_200_OK: return True - except requests.HTTPError as e: - return False + return False diff --git a/bothub/settings.py b/bothub/settings.py --- a/bothub/settings.py +++ b/bothub/settings.py @@ -2,6 +2,7 @@ import dj_database_url from decouple import config +from django.utils.log import DEFAULT_LOGGING # Build paths inside the project like this: os.path.join(BASE_DIR, ...) @@ -191,7 +192,7 @@ BOTHUB_NLP_BASE_URL = config( 'BOTHUB_NLP_BASE_URL', - default='http://localhost:8001/') + default='http://localhost:2657/') # CSRF @@ -204,3 +205,21 @@ 'CSRF_COOKIE_SECURE', default=False, cast=bool) + + +# Logging + +LOGGING = DEFAULT_LOGGING +LOGGING['formatters']['bothub.health'] = { + 'format': '[bothub.health] {message}', + 'style': '{', +} +LOGGING['handlers']['bothub.health'] = { + 'level': 'DEBUG', + 'class': 'logging.StreamHandler', + 'formatter': 'bothub.health', +} +LOGGING['loggers']['bothub.health.checks'] = { + 'handlers': ['bothub.health'], + 'level': 'DEBUG', +}
Fix health checker /ping/ - infinite looping Improve check_database_connection function We can improve this code like that: ```python def check_database_connection(**kwargs): for conn in connections.all(): try: conn.cursor() return True except OperationalError: return False return False ``` reported by @eltonplima in #158 Improve check_database_connection function We can improve this code like that: ```python def check_database_connection(**kwargs): for conn in connections.all(): try: conn.cursor() return True except OperationalError: return False return False ``` reported by @eltonplima in #158
2018-07-10T15:13:01
weni-ai/bothub-engine
167
weni-ai__bothub-engine-167
[ "165", "161", "161" ]
421a084b894831573b53f28ff51e1166fa801260
diff --git a/bothub/health/checks.py b/bothub/health/checks.py --- a/bothub/health/checks.py +++ b/bothub/health/checks.py @@ -1,23 +1,37 @@ +import logging + +from rest_framework import status + + +logger = logging.getLogger('bothub.health.checks') + +CHECK_ACCESSIBLE_API_URL = '/api/repositories/' + + def check_database_connection(**kwargs): from django.db import connections from django.db.utils import OperationalError - db_conn = connections['default'] - if not db_conn: - return False - try: - db_conn.cursor() - return True - except OperationalError as e: + if len(connections.all()) is 0: return False + logger.info('found {} database connection'.format(len(connections.all()))) + for i, conn in enumerate(connections.all(), 1): + try: + conn.cursor() + logger.info('#{} db connection OKAY'.format(i)) + except OperationalError as e: + logger.warning('#{} db connection ERROR'.format(i)) + return False + return True def check_accessible_api(request, **kwargs): - import requests - HTTP_HOST = request.META.get('HTTP_HOST') - repositories_url = 'http://{}/api/repositories/'.format(HTTP_HOST) - request = requests.get(repositories_url) - try: - request.raise_for_status() + from django.test import Client + logger.info('making request to {}'.format(CHECK_ACCESSIBLE_API_URL)) + client = Client() + response = client.get(CHECK_ACCESSIBLE_API_URL) + logger.info('{} status code: {}'.format( + CHECK_ACCESSIBLE_API_URL, + response.status_code)) + if response.status_code is status.HTTP_200_OK: return True - except requests.HTTPError as e: - return False + return False diff --git a/bothub/settings.py b/bothub/settings.py --- a/bothub/settings.py +++ b/bothub/settings.py @@ -2,6 +2,7 @@ import dj_database_url from decouple import config +from django.utils.log import DEFAULT_LOGGING # Build paths inside the project like this: os.path.join(BASE_DIR, ...) @@ -191,7 +192,7 @@ BOTHUB_NLP_BASE_URL = config( 'BOTHUB_NLP_BASE_URL', - default='http://localhost:8001/') + default='http://localhost:2657/') # CSRF @@ -204,3 +205,21 @@ 'CSRF_COOKIE_SECURE', default=False, cast=bool) + + +# Logging + +LOGGING = DEFAULT_LOGGING +LOGGING['formatters']['bothub.health'] = { + 'format': '[bothub.health] {message}', + 'style': '{', +} +LOGGING['handlers']['bothub.health'] = { + 'level': 'DEBUG', + 'class': 'logging.StreamHandler', + 'formatter': 'bothub.health', +} +LOGGING['loggers']['bothub.health.checks'] = { + 'handlers': ['bothub.health'], + 'level': 'DEBUG', +} diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ setup( name='bothub', - version='1.13.3', + version='1.13.4', description='bothub', packages=find_packages(), install_requires=[
Fix health checker /ping/ - infinite looping Improve check_database_connection function We can improve this code like that: ```python def check_database_connection(**kwargs): for conn in connections.all(): try: conn.cursor() return True except OperationalError: return False return False ``` reported by @eltonplima in #158 Improve check_database_connection function We can improve this code like that: ```python def check_database_connection(**kwargs): for conn in connections.all(): try: conn.cursor() return True except OperationalError: return False return False ``` reported by @eltonplima in #158
2018-07-10T17:15:58
weni-ai/bothub-engine
170
weni-ai__bothub-engine-170
[ "169" ]
62eaead74d12496a4a7389d0202b491d13a988dd
diff --git a/bothub/health/checks.py b/bothub/health/checks.py --- a/bothub/health/checks.py +++ b/bothub/health/checks.py @@ -1,11 +1,14 @@ import logging +from decouple import config from rest_framework import status logger = logging.getLogger('bothub.health.checks') -CHECK_ACCESSIBLE_API_URL = '/api/repositories/' +CHECK_ACCESSIBLE_API_URL = config( + 'CHECK_ACCESSIBLE_API_URL', + default='http://localhost/api/repositories/') def check_database_connection(**kwargs): @@ -24,17 +27,13 @@ def check_database_connection(**kwargs): return True -def check_accessible_api(request, **kwargs): - from django.test import Client - logger.info('making request to {}'.format(CHECK_ACCESSIBLE_API_URL)) - client = Client() - response = client.get(CHECK_ACCESSIBLE_API_URL) - logger.info('{} status code: {}'.format( +def check_accessible_api(**kwargs): + import requests + logger.info('requesting {}'.format(CHECK_ACCESSIBLE_API_URL)) + response = requests.get(CHECK_ACCESSIBLE_API_URL) + logger.info('{} response status code {}'.format( CHECK_ACCESSIBLE_API_URL, response.status_code)) - if response.status_code is not status.HTTP_200_OK: - logger.info('{} returns {}'.format( - CHECK_ACCESSIBLE_API_URL, - response.content)) - return False - return True + if response.status_code is status.HTTP_200_OK: + return True + return False diff --git a/docker/gunicorn.conf.py b/docker/gunicorn.conf.py new file mode 100644 --- /dev/null +++ b/docker/gunicorn.conf.py @@ -0,0 +1,6 @@ +import multiprocessing + +bind = 'unix:/tmp/bothub.sock' +workers = multiprocessing.cpu_count() * 2 + 1 +raw_env = ['DJANGO_SETTINGS_MODULE=bothub.settings'] +daemon = True
check_accessible_api returns False in production
2018-07-10T19:49:36
weni-ai/bothub-engine
171
weni-ai__bothub-engine-171
[ "169" ]
256e104bb479b6d90a11cb8022ca3de0848e3764
diff --git a/bothub/health/checks.py b/bothub/health/checks.py --- a/bothub/health/checks.py +++ b/bothub/health/checks.py @@ -1,11 +1,14 @@ import logging +from decouple import config from rest_framework import status logger = logging.getLogger('bothub.health.checks') -CHECK_ACCESSIBLE_API_URL = '/api/repositories/' +CHECK_ACCESSIBLE_API_URL = config( + 'CHECK_ACCESSIBLE_API_URL', + default='http://localhost/api/repositories/') def check_database_connection(**kwargs): @@ -24,17 +27,13 @@ def check_database_connection(**kwargs): return True -def check_accessible_api(request, **kwargs): - from django.test import Client - logger.info('making request to {}'.format(CHECK_ACCESSIBLE_API_URL)) - client = Client() - response = client.get(CHECK_ACCESSIBLE_API_URL) - logger.info('{} status code: {}'.format( +def check_accessible_api(**kwargs): + import requests + logger.info('requesting {}'.format(CHECK_ACCESSIBLE_API_URL)) + response = requests.get(CHECK_ACCESSIBLE_API_URL) + logger.info('{} response status code {}'.format( CHECK_ACCESSIBLE_API_URL, response.status_code)) - if response.status_code is not status.HTTP_200_OK: - logger.info('{} returns {}'.format( - CHECK_ACCESSIBLE_API_URL, - response.content)) - return False - return True + if response.status_code is status.HTTP_200_OK: + return True + return False diff --git a/docker/gunicorn.conf.py b/docker/gunicorn.conf.py new file mode 100644 --- /dev/null +++ b/docker/gunicorn.conf.py @@ -0,0 +1,6 @@ +import multiprocessing + +bind = 'unix:/tmp/bothub.sock' +workers = multiprocessing.cpu_count() * 2 + 1 +raw_env = ['DJANGO_SETTINGS_MODULE=bothub.settings'] +daemon = True
check_accessible_api returns False in production
2018-07-10T20:03:18
weni-ai/bothub-engine
186
weni-ai__bothub-engine-186
[ "185" ]
c5114e918fe6b04882397f445036da4128fe7d0b
diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -333,7 +333,7 @@ def examples(self): models.Q(deleted_in=self) | models.Q(deleted_in__training_started_at__lt=t_started_at)) else: - examples = examples.exclude(deleted_in=self) + examples = examples.exclude(deleted_in__isnull=False) return examples @property
diff --git a/bothub/common/tests.py b/bothub/common/tests.py --- a/bothub/common/tests.py +++ b/bothub/common/tests.py @@ -352,7 +352,7 @@ def test_language(self): self.example.language, self.language) - def teste_delete(self): + def test_delete(self): self.example.delete() self.assertEqual( self.example.deleted_in, @@ -575,6 +575,11 @@ def setUp(self): repository_update=self.repository.current_update(), text='hi', intent='greet') + example = RepositoryExample.objects.create( + repository_update=self.repository.current_update(), + text='hello1', + intent='greet') + example.delete() self.update = self.repository.current_update() self.update.start_training(self.owner) @@ -604,6 +609,71 @@ def test_okay(self): new_update_2.examples.count(), 3) + def test_examples_deleted_consistency(self): + new_update_1 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_1, + text='hello', + intent='greet') + RepositoryExample.objects.create( + repository_update=new_update_1, + text='hello d1', + intent='greet').delete() + examples_1_count = new_update_1.examples.count() + new_update_1.start_training(self.owner) + + new_update_2 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_2, + text='hellow', + intent='greet') + examples_2_count = new_update_2.examples.count() + new_update_2.start_training(self.owner) + + new_update_3 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hellow', + intent='greet') + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hello d2', + intent='greet').delete() + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hello d3', + intent='greet').delete() + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hello d4', + intent='greet').delete() + examples_3_count = new_update_3.examples.count() + new_update_3.start_training(self.owner) + + new_update_4 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_4, + text='hellow', + intent='greet') + examples_4_count = new_update_4.examples.count() + new_update_4.start_training(self.owner) + + self.assertEqual( + examples_1_count, + new_update_1.examples.count()) + + self.assertEqual( + examples_2_count, + new_update_2.examples.count()) + + self.assertEqual( + examples_3_count, + new_update_3.examples.count()) + + self.assertEqual( + examples_4_count, + new_update_4.examples.count()) + class RepositoryReadyForTrain(TestCase): def setUp(self):
Repository examples method ignore deleted when language is setted Check this line.. https://github.com/Ilhasoft/bothub-engine/blob/master/bothub/common/models.py#L218
2018-07-19T21:13:20
weni-ai/bothub-engine
187
weni-ai__bothub-engine-187
[ "185" ]
bffc072dc13aa0e28dd99a6e6ae6bd44819eacd6
diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -333,7 +333,7 @@ def examples(self): models.Q(deleted_in=self) | models.Q(deleted_in__training_started_at__lt=t_started_at)) else: - examples = examples.exclude(deleted_in=self) + examples = examples.exclude(deleted_in__isnull=False) return examples @property diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ setup( name='bothub', - version='1.14.2', + version='1.14.3', description='bothub', packages=find_packages(), install_requires=[
diff --git a/bothub/common/tests.py b/bothub/common/tests.py --- a/bothub/common/tests.py +++ b/bothub/common/tests.py @@ -352,7 +352,7 @@ def test_language(self): self.example.language, self.language) - def teste_delete(self): + def test_delete(self): self.example.delete() self.assertEqual( self.example.deleted_in, @@ -575,6 +575,11 @@ def setUp(self): repository_update=self.repository.current_update(), text='hi', intent='greet') + example = RepositoryExample.objects.create( + repository_update=self.repository.current_update(), + text='hello1', + intent='greet') + example.delete() self.update = self.repository.current_update() self.update.start_training(self.owner) @@ -604,6 +609,71 @@ def test_okay(self): new_update_2.examples.count(), 3) + def test_examples_deleted_consistency(self): + new_update_1 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_1, + text='hello', + intent='greet') + RepositoryExample.objects.create( + repository_update=new_update_1, + text='hello d1', + intent='greet').delete() + examples_1_count = new_update_1.examples.count() + new_update_1.start_training(self.owner) + + new_update_2 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_2, + text='hellow', + intent='greet') + examples_2_count = new_update_2.examples.count() + new_update_2.start_training(self.owner) + + new_update_3 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hellow', + intent='greet') + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hello d2', + intent='greet').delete() + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hello d3', + intent='greet').delete() + RepositoryExample.objects.create( + repository_update=new_update_3, + text='hello d4', + intent='greet').delete() + examples_3_count = new_update_3.examples.count() + new_update_3.start_training(self.owner) + + new_update_4 = self.repository.current_update() + RepositoryExample.objects.create( + repository_update=new_update_4, + text='hellow', + intent='greet') + examples_4_count = new_update_4.examples.count() + new_update_4.start_training(self.owner) + + self.assertEqual( + examples_1_count, + new_update_1.examples.count()) + + self.assertEqual( + examples_2_count, + new_update_2.examples.count()) + + self.assertEqual( + examples_3_count, + new_update_3.examples.count()) + + self.assertEqual( + examples_4_count, + new_update_4.examples.count()) + class RepositoryReadyForTrain(TestCase): def setUp(self):
Repository examples method ignore deleted when language is setted Check this line.. https://github.com/Ilhasoft/bothub-engine/blob/master/bothub/common/models.py#L218
2018-07-19T21:18:39
weni-ai/bothub-engine
190
weni-ai__bothub-engine-190
[ "189" ]
2694d59dc37268acdcf06b6fe6e588e73b006f8c
diff --git a/bothub/common/models.py b/bothub/common/models.py --- a/bothub/common/models.py +++ b/bothub/common/models.py @@ -2,8 +2,6 @@ import base64 import requests -from functools import reduce - from django.db import models from django.utils.translation import gettext as _ from django.utils import timezone @@ -524,12 +522,8 @@ def same_entities_validator(cls, a, b): @classmethod def count_entities(cls, entities_list, to_str=False): r = {} - reduce( - lambda current, next: current.update({ - next.get('entity'): current.get('entity', 0) + 1, - }), - entities_list, - r) + for e in entities_list: + r.update({e.get('entity'): r.get('entity', 0) + 1}) if to_str: r = ', '.join(map( lambda x: '{} {}'.format(x[1], x[0]),
diff --git a/bothub/api/tests/test_translate.py b/bothub/api/tests/test_translate.py --- a/bothub/api/tests/test_translate.py +++ b/bothub/api/tests/test_translate.py @@ -163,6 +163,41 @@ def test_entities_no_valid(self): len(content_data.get('entities')), 1) + def test_entities_no_valid_2(self): + example = RepositoryExample.objects.create( + repository_update=self.repository.current_update(), + text='my name is douglas') + RepositoryExampleEntity.objects.create( + repository_example=self.example, + start=11, + end=18, + entity='name') + response, content_data = self.request( + { + 'original_example': example.id, + 'language': languages.LANGUAGE_PT, + 'text': 'meu nome é douglas', + 'entities': [ + { + 'start': 11, + 'end': 18, + 'entity': 'name', + }, + { + 'start': 0, + 'end': 3, + 'entity': 'my', + }, + ], + }, + self.owner_token) + self.assertEqual( + response.status_code, + status.HTTP_400_BAD_REQUEST) + self.assertEqual( + len(content_data.get('entities')), + 1) + def test_can_not_translate_to_same_language(self): response, content_data = self.request( { diff --git a/bothub/common/tests.py b/bothub/common/tests.py --- a/bothub/common/tests.py +++ b/bothub/common/tests.py @@ -159,6 +159,22 @@ def test_invalid_count_entities(self): translate.has_valid_entities, False) + RepositoryTranslatedExampleEntity.objects.create( + repository_translated_example=translate, + start=11, + end=18, + entity='name') + + RepositoryTranslatedExampleEntity.objects.create( + repository_translated_example=translate, + start=0, + end=3, + entity='my') + + self.assertEqual( + translate.has_valid_entities, + False) + def test_invalid_how_entities(self): RepositoryExampleEntity.objects.create( repository_example=self.example,
Bug in classmethod RepositoryTranslatedExample.count_entities reduce with multiple items in entities_list Replace "reduce" for "for" in this [line](https://github.com/Ilhasoft/bothub-engine/blob/develop/bothub/common/models.py#L527).
2018-08-14T16:36:01