diff --git a/.coveragerc b/.coveragerc index 010550c3..94110993 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,34 +1,12 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! [run] branch = True [report] -fail_under = 100 show_missing = True -omit = google/cloud/vision/__init__.py +omit = + google/cloud/vision/__init__.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound \ No newline at end of file diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 3815c983..fccaa8e8 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:7a40313731a7cb1454eef6b33d3446ebb121836738dc3ab3d2d3ded5268c35b6 + digest: sha256:3bf87e47c2173d7eed42714589dc4da2c07c3268610f1e47f8e1a30decbfc7f1 diff --git a/.github/release-please.yml b/.github/release-please.yml index 5161ab34..dbd2cc9d 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,5 +1,6 @@ releaseType: python handleGHRelease: true +manifest: true # NOTE: this section is generated by synthtool.languages.python # See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py branches: diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 7092a139..e97d89e4 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -12,7 +12,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.9" - name: Install nox run: | python -m pip install --upgrade setuptools pip wheel @@ -28,7 +28,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.9" - name: Install nox run: | python -m pip install --upgrade setuptools pip wheel diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index d2aee5b7..16d5a9e9 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -12,7 +12,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.8" - name: Install nox run: | python -m pip install --upgrade setuptools pip wheel diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 24e46555..c0dca034 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -41,7 +41,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v4 with: - python-version: "3.10" + python-version: "3.8" - name: Install coverage run: | python -m pip install --upgrade setuptools pip wheel diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile index 238b87b9..f8137d0a 100644 --- a/.kokoro/docker/docs/Dockerfile +++ b/.kokoro/docker/docs/Dockerfile @@ -60,16 +60,16 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* \ && rm -f /var/cache/apt/archives/*.deb -###################### Install python 3.8.11 +###################### Install python 3.9.13 -# Download python 3.8.11 -RUN wget https://www.python.org/ftp/python/3.8.11/Python-3.8.11.tgz +# Download python 3.9.13 +RUN wget https://www.python.org/ftp/python/3.9.13/Python-3.9.13.tgz # Extract files -RUN tar -xvf Python-3.8.11.tgz +RUN tar -xvf Python-3.9.13.tgz -# Install python 3.8.11 -RUN ./Python-3.8.11/configure --enable-optimizations +# Install python 3.9.13 +RUN ./Python-3.9.13/configure --enable-optimizations RUN make altinstall ###################### Install pip diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in index 7718391a..cbd7e77f 100644 --- a/.kokoro/requirements.in +++ b/.kokoro/requirements.in @@ -5,4 +5,6 @@ typing-extensions twine wheel setuptools -nox \ No newline at end of file +nox +charset-normalizer<3 +click<8.1.0 diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index d15994ba..05dc4672 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -20,9 +20,9 @@ cachetools==5.2.0 \ --hash=sha256:6a94c6402995a99c3970cc7e4884bb60b4a8639938157eeed436098bf9831757 \ --hash=sha256:f9f17d2aec496a9aa6b76f53e3b614c965223c061982d434d160f930c698a9db # via google-auth -certifi==2022.6.15 \ - --hash=sha256:84c85a9078b11105f04f3036a9482ae10e4621616db313fe045dd24743a0820d \ - --hash=sha256:fe86415d55e84719d75f8b69414f6438ac3547d2078ab91b67e779ef69378412 +certifi==2022.12.7 \ + --hash=sha256:35824b4c3a97115964b408844d64aa14db1cc518f6562e8d7261699d1350a9e3 \ + --hash=sha256:4ad3232f5e926d6718ec31cfc1fcadfde020920e278684144551c91769c7bc18 # via requests cffi==1.15.1 \ --hash=sha256:00a9ed42e88df81ffae7a8ab6d9356b371399b91dbdf0c3cb1e84c03a13aceb5 \ @@ -93,11 +93,14 @@ cffi==1.15.1 \ charset-normalizer==2.1.1 \ --hash=sha256:5a3d016c7c547f69d6f81fb0db9449ce888b418b5b9952cc5e6e66843e9dd845 \ --hash=sha256:83e9a75d1911279afd89352c68b45348559d1fc0506b054b346651b5e7fee29f - # via requests + # via + # -r requirements.in + # requests click==8.0.4 \ --hash=sha256:6a7a62563bbfabfda3a38f3023a1db4a35978c0abd76f6c9605ecd6554d6d9b1 \ --hash=sha256:8458d7b1287c5fb128c90e23381cf99dcde74beaf6c7ff6384ce84d6fe090adb # via + # -r requirements.in # gcp-docuploader # gcp-releasetool colorlog==6.7.0 \ @@ -110,29 +113,33 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==37.0.4 \ - --hash=sha256:190f82f3e87033821828f60787cfa42bff98404483577b591429ed99bed39d59 \ - --hash=sha256:2be53f9f5505673eeda5f2736bea736c40f051a739bfae2f92d18aed1eb54596 \ - --hash=sha256:30788e070800fec9bbcf9faa71ea6d8068f5136f60029759fd8c3efec3c9dcb3 \ - --hash=sha256:3d41b965b3380f10e4611dbae366f6dc3cefc7c9ac4e8842a806b9672ae9add5 \ - --hash=sha256:4c590ec31550a724ef893c50f9a97a0c14e9c851c85621c5650d699a7b88f7ab \ - --hash=sha256:549153378611c0cca1042f20fd9c5030d37a72f634c9326e225c9f666d472884 \ - --hash=sha256:63f9c17c0e2474ccbebc9302ce2f07b55b3b3fcb211ded18a42d5764f5c10a82 \ - --hash=sha256:6bc95ed67b6741b2607298f9ea4932ff157e570ef456ef7ff0ef4884a134cc4b \ - --hash=sha256:7099a8d55cd49b737ffc99c17de504f2257e3787e02abe6d1a6d136574873441 \ - --hash=sha256:75976c217f10d48a8b5a8de3d70c454c249e4b91851f6838a4e48b8f41eb71aa \ - --hash=sha256:7bc997818309f56c0038a33b8da5c0bfbb3f1f067f315f9abd6fc07ad359398d \ - --hash=sha256:80f49023dd13ba35f7c34072fa17f604d2f19bf0989f292cedf7ab5770b87a0b \ - --hash=sha256:91ce48d35f4e3d3f1d83e29ef4a9267246e6a3be51864a5b7d2247d5086fa99a \ - --hash=sha256:a958c52505c8adf0d3822703078580d2c0456dd1d27fabfb6f76fe63d2971cd6 \ - --hash=sha256:b62439d7cd1222f3da897e9a9fe53bbf5c104fff4d60893ad1355d4c14a24157 \ - --hash=sha256:b7f8dd0d4c1f21759695c05a5ec8536c12f31611541f8904083f3dc582604280 \ - --hash=sha256:d204833f3c8a33bbe11eda63a54b1aad7aa7456ed769a982f21ec599ba5fa282 \ - --hash=sha256:e007f052ed10cc316df59bc90fbb7ff7950d7e2919c9757fd42a2b8ecf8a5f67 \ - --hash=sha256:f2dcb0b3b63afb6df7fd94ec6fbddac81b5492513f7b0436210d390c14d46ee8 \ - --hash=sha256:f721d1885ecae9078c3f6bbe8a88bc0786b6e749bf32ccec1ef2b18929a05046 \ - --hash=sha256:f7a6de3e98771e183645181b3627e2563dcde3ce94a9e42a3f427d2255190327 \ - --hash=sha256:f8c0a6e9e1dd3eb0414ba320f85da6b0dcbd543126e30fcc546e7372a7fbf3b9 +cryptography==38.0.3 \ + --hash=sha256:068147f32fa662c81aebab95c74679b401b12b57494872886eb5c1139250ec5d \ + --hash=sha256:06fc3cc7b6f6cca87bd56ec80a580c88f1da5306f505876a71c8cfa7050257dd \ + --hash=sha256:25c1d1f19729fb09d42e06b4bf9895212292cb27bb50229f5aa64d039ab29146 \ + --hash=sha256:402852a0aea73833d982cabb6d0c3bb582c15483d29fb7085ef2c42bfa7e38d7 \ + --hash=sha256:4e269dcd9b102c5a3d72be3c45d8ce20377b8076a43cbed6f660a1afe365e436 \ + --hash=sha256:5419a127426084933076132d317911e3c6eb77568a1ce23c3ac1e12d111e61e0 \ + --hash=sha256:554bec92ee7d1e9d10ded2f7e92a5d70c1f74ba9524947c0ba0c850c7b011828 \ + --hash=sha256:5e89468fbd2fcd733b5899333bc54d0d06c80e04cd23d8c6f3e0542358c6060b \ + --hash=sha256:65535bc550b70bd6271984d9863a37741352b4aad6fb1b3344a54e6950249b55 \ + --hash=sha256:6ab9516b85bebe7aa83f309bacc5f44a61eeb90d0b4ec125d2d003ce41932d36 \ + --hash=sha256:6addc3b6d593cd980989261dc1cce38263c76954d758c3c94de51f1e010c9a50 \ + --hash=sha256:728f2694fa743a996d7784a6194da430f197d5c58e2f4e278612b359f455e4a2 \ + --hash=sha256:785e4056b5a8b28f05a533fab69febf5004458e20dad7e2e13a3120d8ecec75a \ + --hash=sha256:78cf5eefac2b52c10398a42765bfa981ce2372cbc0457e6bf9658f41ec3c41d8 \ + --hash=sha256:7f836217000342d448e1c9a342e9163149e45d5b5eca76a30e84503a5a96cab0 \ + --hash=sha256:8d41a46251bf0634e21fac50ffd643216ccecfaf3701a063257fe0b2be1b6548 \ + --hash=sha256:984fe150f350a3c91e84de405fe49e688aa6092b3525f407a18b9646f6612320 \ + --hash=sha256:9b24bcff7853ed18a63cfb0c2b008936a9554af24af2fb146e16d8e1aed75748 \ + --hash=sha256:b1b35d9d3a65542ed2e9d90115dfd16bbc027b3f07ee3304fc83580f26e43249 \ + --hash=sha256:b1b52c9e5f8aa2b802d48bd693190341fae201ea51c7a167d69fc48b60e8a959 \ + --hash=sha256:bbf203f1a814007ce24bd4d51362991d5cb90ba0c177a9c08825f2cc304d871f \ + --hash=sha256:be243c7e2bfcf6cc4cb350c0d5cdf15ca6383bbcb2a8ef51d3c9411a9d4386f0 \ + --hash=sha256:bfbe6ee19615b07a98b1d2287d6a6073f734735b49ee45b11324d85efc4d5cbd \ + --hash=sha256:c46837ea467ed1efea562bbeb543994c2d1f6e800785bd5a2c98bc096f5cb220 \ + --hash=sha256:dfb4f4dd568de1b6af9f4cda334adf7d72cf5bc052516e1b2608b683375dd95c \ + --hash=sha256:ed7b00096790213e09eb11c97cc6e2b757f15f3d2f85833cd2d3ec3fe37c1722 # via # gcp-releasetool # secretstorage @@ -148,23 +155,23 @@ filelock==3.8.0 \ --hash=sha256:55447caa666f2198c5b6b13a26d2084d26fa5b115c00d065664b2124680c4edc \ --hash=sha256:617eb4e5eedc82fc5f47b6d61e4d11cb837c56cb4544e39081099fa17ad109d4 # via virtualenv -gcp-docuploader==0.6.3 \ - --hash=sha256:ba8c9d76b3bbac54b0311c503a373b00edc2dc02d6d54ea9507045adb8e870f7 \ - --hash=sha256:c0f5aaa82ce1854a386197e4e359b120ad6d4e57ae2c812fce42219a3288026b +gcp-docuploader==0.6.4 \ + --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ + --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf # via -r requirements.in -gcp-releasetool==1.8.7 \ - --hash=sha256:3d2a67c9db39322194afb3b427e9cb0476ce8f2a04033695f0aeb63979fc2b37 \ - --hash=sha256:5e4d28f66e90780d77f3ecf1e9155852b0c3b13cbccb08ab07e66b2357c8da8d +gcp-releasetool==1.10.0 \ + --hash=sha256:72a38ca91b59c24f7e699e9227c90cbe4dd71b789383cb0164b088abae294c83 \ + --hash=sha256:8c7c99320208383d4bb2b808c6880eb7a81424afe7cdba3c8d84b25f4f0e097d # via -r requirements.in -google-api-core==2.8.2 \ - --hash=sha256:06f7244c640322b508b125903bb5701bebabce8832f85aba9335ec00b3d02edc \ - --hash=sha256:93c6a91ccac79079ac6bbf8b74ee75db970cc899278b97d53bc012f35908cf50 +google-api-core==2.10.2 \ + --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ + --hash=sha256:34f24bd1d5f72a8c4519773d99ca6bf080a6c4e041b4e9f024fe230191dda62e # via # google-cloud-core # google-cloud-storage -google-auth==2.11.0 \ - --hash=sha256:be62acaae38d0049c21ca90f27a23847245c9f161ff54ede13af2cb6afecbac9 \ - --hash=sha256:ed65ecf9f681832298e29328e1ef0a3676e3732b2e56f41532d45f70a22de0fb +google-auth==2.14.1 \ + --hash=sha256:ccaa901f31ad5cbb562615eb8b664b3dd0bf5404a67618e642307f00613eda4d \ + --hash=sha256:f5d8701633bebc12e0deea4df8abd8aff31c28b355360597f7f2ee60f2e4d016 # via # gcp-releasetool # google-api-core @@ -174,76 +181,102 @@ google-cloud-core==2.3.2 \ --hash=sha256:8417acf6466be2fa85123441696c4badda48db314c607cf1e5d543fa8bdc22fe \ --hash=sha256:b9529ee7047fd8d4bf4a2182de619154240df17fbe60ead399078c1ae152af9a # via google-cloud-storage -google-cloud-storage==2.5.0 \ - --hash=sha256:19a26c66c317ce542cea0830b7e787e8dac2588b6bfa4d3fd3b871ba16305ab0 \ - --hash=sha256:382f34b91de2212e3c2e7b40ec079d27ee2e3dbbae99b75b1bcd8c63063ce235 +google-cloud-storage==2.6.0 \ + --hash=sha256:104ca28ae61243b637f2f01455cc8a05e8f15a2a18ced96cb587241cdd3820f5 \ + --hash=sha256:4ad0415ff61abdd8bb2ae81c1f8f7ec7d91a1011613f2db87c614c550f97bfe9 # via gcp-docuploader -google-crc32c==1.3.0 \ - --hash=sha256:04e7c220798a72fd0f08242bc8d7a05986b2a08a0573396187fd32c1dcdd58b3 \ - --hash=sha256:05340b60bf05b574159e9bd940152a47d38af3fb43803ffe71f11d704b7696a6 \ - --hash=sha256:12674a4c3b56b706153a358eaa1018c4137a5a04635b92b4652440d3d7386206 \ - --hash=sha256:127f9cc3ac41b6a859bd9dc4321097b1a4f6aa7fdf71b4f9227b9e3ebffb4422 \ - --hash=sha256:13af315c3a0eec8bb8b8d80b8b128cb3fcd17d7e4edafc39647846345a3f003a \ - --hash=sha256:1926fd8de0acb9d15ee757175ce7242e235482a783cd4ec711cc999fc103c24e \ - --hash=sha256:226f2f9b8e128a6ca6a9af9b9e8384f7b53a801907425c9a292553a3a7218ce0 \ - --hash=sha256:276de6273eb074a35bc598f8efbc00c7869c5cf2e29c90748fccc8c898c244df \ - --hash=sha256:318f73f5484b5671f0c7f5f63741ab020a599504ed81d209b5c7129ee4667407 \ - --hash=sha256:3bbce1be3687bbfebe29abdb7631b83e6b25da3f4e1856a1611eb21854b689ea \ - --hash=sha256:42ae4781333e331a1743445931b08ebdad73e188fd554259e772556fc4937c48 \ - --hash=sha256:58be56ae0529c664cc04a9c76e68bb92b091e0194d6e3c50bea7e0f266f73713 \ - --hash=sha256:5da2c81575cc3ccf05d9830f9e8d3c70954819ca9a63828210498c0774fda1a3 \ - --hash=sha256:6311853aa2bba4064d0c28ca54e7b50c4d48e3de04f6770f6c60ebda1e975267 \ - --hash=sha256:650e2917660e696041ab3dcd7abac160b4121cd9a484c08406f24c5964099829 \ - --hash=sha256:6a4db36f9721fdf391646685ecffa404eb986cbe007a3289499020daf72e88a2 \ - --hash=sha256:779cbf1ce375b96111db98fca913c1f5ec11b1d870e529b1dc7354b2681a8c3a \ - --hash=sha256:7f6fe42536d9dcd3e2ffb9d3053f5d05221ae3bbcefbe472bdf2c71c793e3183 \ - --hash=sha256:891f712ce54e0d631370e1f4997b3f182f3368179198efc30d477c75d1f44942 \ - --hash=sha256:95c68a4b9b7828ba0428f8f7e3109c5d476ca44996ed9a5f8aac6269296e2d59 \ - --hash=sha256:96a8918a78d5d64e07c8ea4ed2bc44354e3f93f46a4866a40e8db934e4c0d74b \ - --hash=sha256:9c3cf890c3c0ecfe1510a452a165431b5831e24160c5fcf2071f0f85ca5a47cd \ - --hash=sha256:9f58099ad7affc0754ae42e6d87443299f15d739b0ce03c76f515153a5cda06c \ - --hash=sha256:a0b9e622c3b2b8d0ce32f77eba617ab0d6768b82836391e4f8f9e2074582bf02 \ - --hash=sha256:a7f9cbea4245ee36190f85fe1814e2d7b1e5f2186381b082f5d59f99b7f11328 \ - --hash=sha256:bab4aebd525218bab4ee615786c4581952eadc16b1ff031813a2fd51f0cc7b08 \ - --hash=sha256:c124b8c8779bf2d35d9b721e52d4adb41c9bfbde45e6a3f25f0820caa9aba73f \ - --hash=sha256:c9da0a39b53d2fab3e5467329ed50e951eb91386e9d0d5b12daf593973c3b168 \ - --hash=sha256:ca60076c388728d3b6ac3846842474f4250c91efbfe5afa872d3ffd69dd4b318 \ - --hash=sha256:cb6994fff247987c66a8a4e550ef374671c2b82e3c0d2115e689d21e511a652d \ - --hash=sha256:d1c1d6236feab51200272d79b3d3e0f12cf2cbb12b208c835b175a21efdb0a73 \ - --hash=sha256:dd7760a88a8d3d705ff562aa93f8445ead54f58fd482e4f9e2bafb7e177375d4 \ - --hash=sha256:dda4d8a3bb0b50f540f6ff4b6033f3a74e8bf0bd5320b70fab2c03e512a62812 \ - --hash=sha256:e0f1ff55dde0ebcfbef027edc21f71c205845585fffe30d4ec4979416613e9b3 \ - --hash=sha256:e7a539b9be7b9c00f11ef16b55486141bc2cdb0c54762f84e3c6fc091917436d \ - --hash=sha256:eb0b14523758e37802f27b7f8cd973f5f3d33be7613952c0df904b68c4842f0e \ - --hash=sha256:ed447680ff21c14aaceb6a9f99a5f639f583ccfe4ce1a5e1d48eb41c3d6b3217 \ - --hash=sha256:f52a4ad2568314ee713715b1e2d79ab55fab11e8b304fd1462ff5cccf4264b3e \ - --hash=sha256:fbd60c6aaa07c31d7754edbc2334aef50601b7f1ada67a96eb1eb57c7c72378f \ - --hash=sha256:fc28e0db232c62ca0c3600884933178f0825c99be4474cdd645e378a10588125 \ - --hash=sha256:fe31de3002e7b08eb20823b3735b97c86c5926dd0581c7710a680b418a8709d4 \ - --hash=sha256:fec221a051150eeddfdfcff162e6db92c65ecf46cb0f7bb1bf812a1520ec026b \ - --hash=sha256:ff71073ebf0e42258a42a0b34f2c09ec384977e7f6808999102eedd5b49920e3 +google-crc32c==1.5.0 \ + --hash=sha256:024894d9d3cfbc5943f8f230e23950cd4906b2fe004c72e29b209420a1e6b05a \ + --hash=sha256:02c65b9817512edc6a4ae7c7e987fea799d2e0ee40c53ec573a692bee24de876 \ + --hash=sha256:02ebb8bf46c13e36998aeaad1de9b48f4caf545e91d14041270d9dca767b780c \ + --hash=sha256:07eb3c611ce363c51a933bf6bd7f8e3878a51d124acfc89452a75120bc436289 \ + --hash=sha256:1034d91442ead5a95b5aaef90dbfaca8633b0247d1e41621d1e9f9db88c36298 \ + --hash=sha256:116a7c3c616dd14a3de8c64a965828b197e5f2d121fedd2f8c5585c547e87b02 \ + --hash=sha256:19e0a019d2c4dcc5e598cd4a4bc7b008546b0358bd322537c74ad47a5386884f \ + --hash=sha256:1c7abdac90433b09bad6c43a43af253e688c9cfc1c86d332aed13f9a7c7f65e2 \ + --hash=sha256:1e986b206dae4476f41bcec1faa057851f3889503a70e1bdb2378d406223994a \ + --hash=sha256:272d3892a1e1a2dbc39cc5cde96834c236d5327e2122d3aaa19f6614531bb6eb \ + --hash=sha256:278d2ed7c16cfc075c91378c4f47924c0625f5fc84b2d50d921b18b7975bd210 \ + --hash=sha256:2ad40e31093a4af319dadf503b2467ccdc8f67c72e4bcba97f8c10cb078207b5 \ + --hash=sha256:2e920d506ec85eb4ba50cd4228c2bec05642894d4c73c59b3a2fe20346bd00ee \ + --hash=sha256:3359fc442a743e870f4588fcf5dcbc1bf929df1fad8fb9905cd94e5edb02e84c \ + --hash=sha256:37933ec6e693e51a5b07505bd05de57eee12f3e8c32b07da7e73669398e6630a \ + --hash=sha256:398af5e3ba9cf768787eef45c803ff9614cc3e22a5b2f7d7ae116df8b11e3314 \ + --hash=sha256:3b747a674c20a67343cb61d43fdd9207ce5da6a99f629c6e2541aa0e89215bcd \ + --hash=sha256:461665ff58895f508e2866824a47bdee72497b091c730071f2b7575d5762ab65 \ + --hash=sha256:4c6fdd4fccbec90cc8a01fc00773fcd5fa28db683c116ee3cb35cd5da9ef6c37 \ + --hash=sha256:5829b792bf5822fd0a6f6eb34c5f81dd074f01d570ed7f36aa101d6fc7a0a6e4 \ + --hash=sha256:596d1f98fc70232fcb6590c439f43b350cb762fb5d61ce7b0e9db4539654cc13 \ + --hash=sha256:5ae44e10a8e3407dbe138984f21e536583f2bba1be9491239f942c2464ac0894 \ + --hash=sha256:635f5d4dd18758a1fbd1049a8e8d2fee4ffed124462d837d1a02a0e009c3ab31 \ + --hash=sha256:64e52e2b3970bd891309c113b54cf0e4384762c934d5ae56e283f9a0afcd953e \ + --hash=sha256:66741ef4ee08ea0b2cc3c86916ab66b6aef03768525627fd6a1b34968b4e3709 \ + --hash=sha256:67b741654b851abafb7bc625b6d1cdd520a379074e64b6a128e3b688c3c04740 \ + --hash=sha256:6ac08d24c1f16bd2bf5eca8eaf8304812f44af5cfe5062006ec676e7e1d50afc \ + --hash=sha256:6f998db4e71b645350b9ac28a2167e6632c239963ca9da411523bb439c5c514d \ + --hash=sha256:72218785ce41b9cfd2fc1d6a017dc1ff7acfc4c17d01053265c41a2c0cc39b8c \ + --hash=sha256:74dea7751d98034887dbd821b7aae3e1d36eda111d6ca36c206c44478035709c \ + --hash=sha256:759ce4851a4bb15ecabae28f4d2e18983c244eddd767f560165563bf9aefbc8d \ + --hash=sha256:77e2fd3057c9d78e225fa0a2160f96b64a824de17840351b26825b0848022906 \ + --hash=sha256:7c074fece789b5034b9b1404a1f8208fc2d4c6ce9decdd16e8220c5a793e6f61 \ + --hash=sha256:7c42c70cd1d362284289c6273adda4c6af8039a8ae12dc451dcd61cdabb8ab57 \ + --hash=sha256:7f57f14606cd1dd0f0de396e1e53824c371e9544a822648cd76c034d209b559c \ + --hash=sha256:83c681c526a3439b5cf94f7420471705bbf96262f49a6fe546a6db5f687a3d4a \ + --hash=sha256:8485b340a6a9e76c62a7dce3c98e5f102c9219f4cfbf896a00cf48caf078d438 \ + --hash=sha256:84e6e8cd997930fc66d5bb4fde61e2b62ba19d62b7abd7a69920406f9ecca946 \ + --hash=sha256:89284716bc6a5a415d4eaa11b1726d2d60a0cd12aadf5439828353662ede9dd7 \ + --hash=sha256:8b87e1a59c38f275c0e3676fc2ab6d59eccecfd460be267ac360cc31f7bcde96 \ + --hash=sha256:8f24ed114432de109aa9fd317278518a5af2d31ac2ea6b952b2f7782b43da091 \ + --hash=sha256:98cb4d057f285bd80d8778ebc4fde6b4d509ac3f331758fb1528b733215443ae \ + --hash=sha256:998679bf62b7fb599d2878aa3ed06b9ce688b8974893e7223c60db155f26bd8d \ + --hash=sha256:9ba053c5f50430a3fcfd36f75aff9caeba0440b2d076afdb79a318d6ca245f88 \ + --hash=sha256:9c99616c853bb585301df6de07ca2cadad344fd1ada6d62bb30aec05219c45d2 \ + --hash=sha256:a1fd716e7a01f8e717490fbe2e431d2905ab8aa598b9b12f8d10abebb36b04dd \ + --hash=sha256:a2355cba1f4ad8b6988a4ca3feed5bff33f6af2d7f134852cf279c2aebfde541 \ + --hash=sha256:b1f8133c9a275df5613a451e73f36c2aea4fe13c5c8997e22cf355ebd7bd0728 \ + --hash=sha256:b8667b48e7a7ef66afba2c81e1094ef526388d35b873966d8a9a447974ed9178 \ + --hash=sha256:ba1eb1843304b1e5537e1fca632fa894d6f6deca8d6389636ee5b4797affb968 \ + --hash=sha256:be82c3c8cfb15b30f36768797a640e800513793d6ae1724aaaafe5bf86f8f346 \ + --hash=sha256:c02ec1c5856179f171e032a31d6f8bf84e5a75c45c33b2e20a3de353b266ebd8 \ + --hash=sha256:c672d99a345849301784604bfeaeba4db0c7aae50b95be04dd651fd2a7310b93 \ + --hash=sha256:c6c777a480337ac14f38564ac88ae82d4cd238bf293f0a22295b66eb89ffced7 \ + --hash=sha256:cae0274952c079886567f3f4f685bcaf5708f0a23a5f5216fdab71f81a6c0273 \ + --hash=sha256:cd67cf24a553339d5062eff51013780a00d6f97a39ca062781d06b3a73b15462 \ + --hash=sha256:d3515f198eaa2f0ed49f8819d5732d70698c3fa37384146079b3799b97667a94 \ + --hash=sha256:d5280312b9af0976231f9e317c20e4a61cd2f9629b7bfea6a693d1878a264ebd \ + --hash=sha256:de06adc872bcd8c2a4e0dc51250e9e65ef2ca91be023b9d13ebd67c2ba552e1e \ + --hash=sha256:e1674e4307fa3024fc897ca774e9c7562c957af85df55efe2988ed9056dc4e57 \ + --hash=sha256:e2096eddb4e7c7bdae4bd69ad364e55e07b8316653234a56552d9c988bd2d61b \ + --hash=sha256:e560628513ed34759456a416bf86b54b2476c59144a9138165c9a1575801d0d9 \ + --hash=sha256:edfedb64740750e1a3b16152620220f51d58ff1b4abceb339ca92e934775c27a \ + --hash=sha256:f13cae8cc389a440def0c8c52057f37359014ccbc9dc1f0827936bcd367c6100 \ + --hash=sha256:f314013e7dcd5cf45ab1945d92e713eec788166262ae8deb2cfacd53def27325 \ + --hash=sha256:f583edb943cf2e09c60441b910d6a20b4d9d626c75a36c8fcac01a6c96c01183 \ + --hash=sha256:fd8536e902db7e365f49e7d9029283403974ccf29b13fc7028b97e2295b33556 \ + --hash=sha256:fe70e325aa68fa4b5edf7d1a4b6f691eb04bbccac0ace68e34820d283b5f80d4 # via google-resumable-media -google-resumable-media==2.3.3 \ - --hash=sha256:27c52620bd364d1c8116eaac4ea2afcbfb81ae9139fb3199652fcac1724bfb6c \ - --hash=sha256:5b52774ea7a829a8cdaa8bd2d4c3d4bc660c91b30857ab2668d0eb830f4ea8c5 +google-resumable-media==2.4.0 \ + --hash=sha256:2aa004c16d295c8f6c33b2b4788ba59d366677c0a25ae7382436cb30f776deaa \ + --hash=sha256:8d5518502f92b9ecc84ac46779bd4f09694ecb3ba38a3e7ca737a86d15cbca1f # via google-cloud-storage -googleapis-common-protos==1.56.4 \ - --hash=sha256:8eb2cbc91b69feaf23e32452a7ae60e791e09967d81d4fcc7fc388182d1bd394 \ - --hash=sha256:c25873c47279387cfdcbdafa36149887901d36202cb645a0e4f29686bf6e4417 +googleapis-common-protos==1.57.0 \ + --hash=sha256:27a849d6205838fb6cc3c1c21cb9800707a661bb21c6ce7fb13e99eb1f8a0c46 \ + --hash=sha256:a9f4a1d7f6d9809657b7f1316a1aa527f6664891531bcfcc13b6696e685f443c # via google-api-core -idna==3.3 \ - --hash=sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff \ - --hash=sha256:9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d +idna==3.4 \ + --hash=sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4 \ + --hash=sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2 # via requests -importlib-metadata==4.12.0 \ - --hash=sha256:637245b8bab2b6502fcbc752cc4b7a6f6243bb02b31c5c26156ad103d3d45670 \ - --hash=sha256:7401a975809ea1fdc658c3aa4f78cc2195a0e019c5cbc4c06122884e9ae80c23 +importlib-metadata==5.0.0 \ + --hash=sha256:da31db32b304314d044d3c12c79bd59e307889b287ad12ff387b3500835fc2ab \ + --hash=sha256:ddb0e35065e8938f867ed4928d0ae5bf2a53b7773871bfe6bcc7e4fcdc7dea43 # via # -r requirements.in + # keyring # twine -jaraco-classes==3.2.2 \ - --hash=sha256:6745f113b0b588239ceb49532aa09c3ebb947433ce311ef2f8e3ad64ebb74594 \ - --hash=sha256:e6ef6fd3fcf4579a7a019d87d1e56a883f4e4c35cfe925f86731abc58804e647 +jaraco-classes==3.2.3 \ + --hash=sha256:2353de3288bc6b82120752201c6b1c1a14b058267fa424ed5ce5984e3b922158 \ + --hash=sha256:89559fa5c1d3c34eff6f631ad80bb21f378dbcbb35dd161fd2c6b93f5be2f98a # via keyring jeepney==0.8.0 \ --hash=sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806 \ @@ -255,9 +288,9 @@ jinja2==3.1.2 \ --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 # via gcp-releasetool -keyring==23.9.0 \ - --hash=sha256:4c32a31174faaee48f43a7e2c7e9c3216ec5e95acf22a2bebfb4a1d05056ee44 \ - --hash=sha256:98f060ec95ada2ab910c195a2d4317be6ef87936a766b239c46aa3c7aac4f0db +keyring==23.11.0 \ + --hash=sha256:3dd30011d555f1345dec2c262f0153f2f0ca6bca041fb1dc4588349bb4c0ac1e \ + --hash=sha256:ad192263e2cdd5f12875dedc2da13534359a7e760e77f8d04b50968a821c2361 # via # gcp-releasetool # twine @@ -303,9 +336,9 @@ markupsafe==2.1.1 \ --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \ --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7 # via jinja2 -more-itertools==8.14.0 \ - --hash=sha256:1bc4f91ee5b1b31ac7ceacc17c09befe6a40a503907baf9c839c229b5095cfd2 \ - --hash=sha256:c09443cd3d5438b8dafccd867a6bc1cb0894389e90cb53d227456b0b0bccb750 +more-itertools==9.0.0 \ + --hash=sha256:250e83d7e81d0c87ca6bd942e6aeab8cc9daa6096d12c5308f3f92fa5e5c1f41 \ + --hash=sha256:5a6257e40878ef0520b1803990e3e22303a41b5714006c32a3fd8304b26ea1ab # via jaraco-classes nox==2022.8.7 \ --hash=sha256:1b894940551dc5c389f9271d197ca5d655d40bdc6ccf93ed6880e4042760a34b \ @@ -321,34 +354,33 @@ pkginfo==1.8.3 \ --hash=sha256:848865108ec99d4901b2f7e84058b6e7660aae8ae10164e015a6dcf5b242a594 \ --hash=sha256:a84da4318dd86f870a9447a8c98340aa06216bfc6f2b7bdc4b8766984ae1867c # via twine -platformdirs==2.5.2 \ - --hash=sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788 \ - --hash=sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19 +platformdirs==2.5.4 \ + --hash=sha256:1006647646d80f16130f052404c6b901e80ee4ed6bef6792e1f238a8969106f7 \ + --hash=sha256:af0276409f9a02373d540bf8480021a048711d572745aef4b7842dad245eba10 # via virtualenv -protobuf==3.20.2 \ - --hash=sha256:03d76b7bd42ac4a6e109742a4edf81ffe26ffd87c5993126d894fe48a120396a \ - --hash=sha256:09e25909c4297d71d97612f04f41cea8fa8510096864f2835ad2f3b3df5a5559 \ - --hash=sha256:18e34a10ae10d458b027d7638a599c964b030c1739ebd035a1dfc0e22baa3bfe \ - --hash=sha256:291fb4307094bf5ccc29f424b42268640e00d5240bf0d9b86bf3079f7576474d \ - --hash=sha256:2c0b040d0b5d5d207936ca2d02f00f765906622c07d3fa19c23a16a8ca71873f \ - --hash=sha256:384164994727f274cc34b8abd41a9e7e0562801361ee77437099ff6dfedd024b \ - --hash=sha256:3cb608e5a0eb61b8e00fe641d9f0282cd0eedb603be372f91f163cbfbca0ded0 \ - --hash=sha256:5d9402bf27d11e37801d1743eada54372f986a372ec9679673bfcc5c60441151 \ - --hash=sha256:712dca319eee507a1e7df3591e639a2b112a2f4a62d40fe7832a16fd19151750 \ - --hash=sha256:7a5037af4e76c975b88c3becdf53922b5ffa3f2cddf657574a4920a3b33b80f3 \ - --hash=sha256:8228e56a865c27163d5d1d1771d94b98194aa6917bcfb6ce139cbfa8e3c27334 \ - --hash=sha256:84a1544252a933ef07bb0b5ef13afe7c36232a774affa673fc3636f7cee1db6c \ - --hash=sha256:84fe5953b18a383fd4495d375fe16e1e55e0a3afe7b4f7b4d01a3a0649fcda9d \ - --hash=sha256:9c673c8bfdf52f903081816b9e0e612186684f4eb4c17eeb729133022d6032e3 \ - --hash=sha256:9f876a69ca55aed879b43c295a328970306e8e80a263ec91cf6e9189243c613b \ - --hash=sha256:a9e5ae5a8e8985c67e8944c23035a0dff2c26b0f5070b2f55b217a1c33bbe8b1 \ - --hash=sha256:b4fdb29c5a7406e3f7ef176b2a7079baa68b5b854f364c21abe327bbeec01cdb \ - --hash=sha256:c184485e0dfba4dfd451c3bd348c2e685d6523543a0f91b9fd4ae90eb09e8422 \ - --hash=sha256:c9cdf251c582c16fd6a9f5e95836c90828d51b0069ad22f463761d27c6c19019 \ - --hash=sha256:e39cf61bb8582bda88cdfebc0db163b774e7e03364bbf9ce1ead13863e81e359 \ - --hash=sha256:e8fbc522303e09036c752a0afcc5c0603e917222d8bedc02813fd73b4b4ed804 \ - --hash=sha256:f34464ab1207114e73bba0794d1257c150a2b89b7a9faf504e00af7c9fd58978 \ - --hash=sha256:f52dabc96ca99ebd2169dadbe018824ebda08a795c7684a0b7d203a290f3adb0 +protobuf==3.20.3 \ + --hash=sha256:03038ac1cfbc41aa21f6afcbcd357281d7521b4157926f30ebecc8d4ea59dcb7 \ + --hash=sha256:28545383d61f55b57cf4df63eebd9827754fd2dc25f80c5253f9184235db242c \ + --hash=sha256:2e3427429c9cffebf259491be0af70189607f365c2f41c7c3764af6f337105f2 \ + --hash=sha256:398a9e0c3eaceb34ec1aee71894ca3299605fa8e761544934378bbc6c97de23b \ + --hash=sha256:44246bab5dd4b7fbd3c0c80b6f16686808fab0e4aca819ade6e8d294a29c7050 \ + --hash=sha256:447d43819997825d4e71bf5769d869b968ce96848b6479397e29fc24c4a5dfe9 \ + --hash=sha256:67a3598f0a2dcbc58d02dd1928544e7d88f764b47d4a286202913f0b2801c2e7 \ + --hash=sha256:74480f79a023f90dc6e18febbf7b8bac7508420f2006fabd512013c0c238f454 \ + --hash=sha256:819559cafa1a373b7096a482b504ae8a857c89593cf3a25af743ac9ecbd23480 \ + --hash=sha256:899dc660cd599d7352d6f10d83c95df430a38b410c1b66b407a6b29265d66469 \ + --hash=sha256:8c0c984a1b8fef4086329ff8dd19ac77576b384079247c770f29cc8ce3afa06c \ + --hash=sha256:9aae4406ea63d825636cc11ffb34ad3379335803216ee3a856787bcf5ccc751e \ + --hash=sha256:a7ca6d488aa8ff7f329d4c545b2dbad8ac31464f1d8b1c87ad1346717731e4db \ + --hash=sha256:b6cc7ba72a8850621bfec987cb72623e703b7fe2b9127a161ce61e61558ad905 \ + --hash=sha256:bf01b5720be110540be4286e791db73f84a2b721072a3711efff6c324cdf074b \ + --hash=sha256:c02ce36ec760252242a33967d51c289fd0e1c0e6e5cc9397e2279177716add86 \ + --hash=sha256:d9e4432ff660d67d775c66ac42a67cf2453c27cb4d738fc22cb53b5d84c135d4 \ + --hash=sha256:daa564862dd0d39c00f8086f88700fdbe8bc717e993a21e90711acfed02f2402 \ + --hash=sha256:de78575669dddf6099a8a0f46a27e82a1783c557ccc38ee620ed8cc96d3be7d7 \ + --hash=sha256:e64857f395505ebf3d2569935506ae0dfc4a15cb80dc25261176c784662cdcc4 \ + --hash=sha256:f4bd856d702e5b0d96a00ec6b307b0f51c1982c2bf9c0052cf9019e9a544ba99 \ + --hash=sha256:f4c42102bc82a51108e449cbb32b19b180022941c727bac0cfd50170341f16ee # via # gcp-docuploader # gcp-releasetool @@ -377,9 +409,9 @@ pygments==2.13.0 \ # via # readme-renderer # rich -pyjwt==2.4.0 \ - --hash=sha256:72d1d253f32dbd4f5c88eaf1fdc62f3a19f676ccbadb9dbc5d07e951b2b26daf \ - --hash=sha256:d42908208c699b3b973cbeb01a969ba6a96c821eefb1c5bfe4c390c01d67abba +pyjwt==2.6.0 \ + --hash=sha256:69285c7e31fc44f68a1feb309e948e0df53259d579295e6cfe2b1792329f05fd \ + --hash=sha256:d83c3d892a77bbb74d3e1a2cfa90afaadb60945205d1095d9221f04466f64c14 # via gcp-releasetool pyparsing==3.0.9 \ --hash=sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb \ @@ -392,9 +424,9 @@ python-dateutil==2.8.2 \ --hash=sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86 \ --hash=sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9 # via gcp-releasetool -readme-renderer==37.0 \ - --hash=sha256:07b7ea234e03e58f77cc222e206e6abb8f4c0435becce5104794ee591f9301c5 \ - --hash=sha256:9fa416704703e509eeb900696751c908ddeb2011319d93700d8f18baff887a69 +readme-renderer==37.3 \ + --hash=sha256:cd653186dfc73055656f090f227f5cb22a046d7f71a841dfa305f55c9a513273 \ + --hash=sha256:f67a16caedfa71eef48a31b39708637a6f4664c4394801a7b0d6432d13907343 # via twine requests==2.28.1 \ --hash=sha256:7c5599b102feddaa661c826c56ab4fee28bfd17f5abca1ebbe3e7f19d7c97983 \ @@ -405,17 +437,17 @@ requests==2.28.1 \ # google-cloud-storage # requests-toolbelt # twine -requests-toolbelt==0.9.1 \ - --hash=sha256:380606e1d10dc85c3bd47bf5a6095f815ec007be7a8b69c878507068df059e6f \ - --hash=sha256:968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0 +requests-toolbelt==0.10.1 \ + --hash=sha256:18565aa58116d9951ac39baa288d3adb5b3ff975c4f25eee78555d89e8f247f7 \ + --hash=sha256:62e09f7ff5ccbda92772a29f394a49c3ad6cb181d568b1337626b2abb628a63d # via twine rfc3986==2.0.0 \ --hash=sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd \ --hash=sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c # via twine -rich==12.5.1 \ - --hash=sha256:2eb4e6894cde1e017976d2975ac210ef515d7548bc595ba20e195fb9628acdeb \ - --hash=sha256:63a5c5ce3673d3d5fbbf23cd87e11ab84b6b451436f1b7f19ec54b6bc36ed7ca +rich==12.6.0 \ + --hash=sha256:a4eb26484f2c82589bd9a17c73d32a010b1e29d89f1604cd9bf3a2097b81bb5e \ + --hash=sha256:ba3a3775974105c221d31141f2c116f4fd65c5ceb0698657a11e9f295ec93fd0 # via twine rsa==4.9 \ --hash=sha256:90260d9058e514786967344d0ef75fa8727eed8a7d2e43ce9f4bcf1b536174f7 \ @@ -437,9 +469,9 @@ twine==4.0.1 \ --hash=sha256:42026c18e394eac3e06693ee52010baa5313e4811d5a11050e7d48436cf41b9e \ --hash=sha256:96b1cf12f7ae611a4a40b6ae8e9570215daff0611828f5fe1f37a16255ab24a0 # via -r requirements.in -typing-extensions==4.3.0 \ - --hash=sha256:25642c956049920a5aa49edcdd6ab1e06d7e5d467fc00e0506c44ac86fbfca02 \ - --hash=sha256:e6d2677a32f47fc7eb2795db1dd15c1f34eff616bcaf2cfb5e997f854fa1c4a6 +typing-extensions==4.4.0 \ + --hash=sha256:1511434bb92bf8dd198c12b1cc812e800d4181cfcb867674e0f8279cc93087aa \ + --hash=sha256:16fa4864408f655d35ec496218b85f79b3437c829e93320c7c9215ccfd92489e # via -r requirements.in urllib3==1.26.12 \ --hash=sha256:3fa96cf423e6987997fc326ae8df396db2a8b7c667747d47ddd8ecba91f4a74e \ @@ -447,25 +479,25 @@ urllib3==1.26.12 \ # via # requests # twine -virtualenv==20.16.4 \ - --hash=sha256:014f766e4134d0008dcaa1f95bafa0fb0f575795d07cae50b1bee514185d6782 \ - --hash=sha256:035ed57acce4ac35c82c9d8802202b0e71adac011a511ff650cbcf9635006a22 +virtualenv==20.16.7 \ + --hash=sha256:8691e3ff9387f743e00f6bb20f70121f5e4f596cae754531f2b3b3a1b1ac696e \ + --hash=sha256:efd66b00386fdb7dbe4822d172303f40cd05e50e01740b19ea42425cbe653e29 # via nox webencodings==0.5.1 \ --hash=sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78 \ --hash=sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923 # via bleach -wheel==0.37.1 \ - --hash=sha256:4bdcd7d840138086126cd09254dc6195fb4fc6f01c050a1d7236f2630db1d22a \ - --hash=sha256:e9a504e793efbca1b8e0e9cb979a249cf4a0a7b5b8c9e8b65a5e39d49529c1c4 +wheel==0.38.4 \ + --hash=sha256:965f5259b566725405b05e7cf774052044b1ed30119b5d586b2703aafe8719ac \ + --hash=sha256:b60533f3f5d530e971d6737ca6d58681ee434818fab630c83a734bb10c083ce8 # via -r requirements.in -zipp==3.8.1 \ - --hash=sha256:05b45f1ee8f807d0cc928485ca40a07cb491cf092ff587c0df9cb1fd154848d2 \ - --hash=sha256:47c40d7fe183a6f21403a199b3e4192cca5774656965b0a4988ad2f8feb5f009 +zipp==3.10.0 \ + --hash=sha256:4fcb6f278987a6605757302a6e40e896257570d11c51628968ccb2a47e80c6c1 \ + --hash=sha256:7a7262fd930bd3e36c50b9a64897aec3fafff3dfdeec9623ae22b40e93f99bb8 # via importlib-metadata # The following packages are considered to be unsafe in a requirements file: -setuptools==65.2.0 \ - --hash=sha256:7f4bc85450898a09f76ebf28b72fa25bc7111f6c7d665d514a60bba9c75ef2a9 \ - --hash=sha256:a3ca5857c89f82f5c9410e8508cb32f4872a3bafd4aa7ae122a24ca33bccc750 +setuptools==65.5.1 \ + --hash=sha256:d0b9a8433464d5800cbe05094acf5c6d52a91bfac9b52bcfc4d41382be5d5d31 \ + --hash=sha256:e197a19aa8ec9722928f2206f8de752def0e4c9fc6953527360d1c36d94ddb2f # via -r requirements.in diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 46d23716..5405cc8f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -25,7 +25,7 @@ repos: rev: 22.3.0 hooks: - id: black -- repo: https://gitlab.com/pycqa/flake8 +- repo: https://github.com/pycqa/flake8 rev: 3.9.2 hooks: - id: flake8 diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 00000000..99f0d475 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,4 @@ +{ + ".": "3.2.0" +} + \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ee809c6..99ca2e0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,27 @@ [1]: https://pypi.org/project/google-cloud-vision/#history +## [3.2.0](https://github.com/googleapis/python-vision/compare/v3.1.4...v3.2.0) (2022-12-15) + + +### Features + +* Add typing to proto.Message based class attributes ([0e5a37b](https://github.com/googleapis/python-vision/commit/0e5a37b788ccc10688b6f23a46040880827b2b3e)) + + +### Bug Fixes + +* Add dict typing for client_options ([0e5a37b](https://github.com/googleapis/python-vision/commit/0e5a37b788ccc10688b6f23a46040880827b2b3e)) +* **deps:** Require google-api-core >=1.34.0, >=2.11.0 ([0e5a37b](https://github.com/googleapis/python-vision/commit/0e5a37b788ccc10688b6f23a46040880827b2b3e)) +* Drop usage of pkg_resources ([0e5a37b](https://github.com/googleapis/python-vision/commit/0e5a37b788ccc10688b6f23a46040880827b2b3e)) +* Fix timeout default values ([0e5a37b](https://github.com/googleapis/python-vision/commit/0e5a37b788ccc10688b6f23a46040880827b2b3e)) + + +### Documentation + +* **samples:** Snippetgen handling of repeated enum field ([0e5a37b](https://github.com/googleapis/python-vision/commit/0e5a37b788ccc10688b6f23a46040880827b2b3e)) +* **samples:** Snippetgen should call await on the operation coroutine before calling result ([0e5a37b](https://github.com/googleapis/python-vision/commit/0e5a37b788ccc10688b6f23a46040880827b2b3e)) + ## [3.1.4](https://github.com/googleapis/python-vision/compare/v3.1.3...v3.1.4) (2022-10-07) diff --git a/docs/vision_v1/types.rst b/docs/vision_v1/types.rst index 52d9869b..dbbb594c 100644 --- a/docs/vision_v1/types.rst +++ b/docs/vision_v1/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Vision v1 API .. automodule:: google.cloud.vision_v1.types :members: - :undoc-members: :show-inheritance: diff --git a/docs/vision_v1p2beta1/types.rst b/docs/vision_v1p2beta1/types.rst index 33ab32e0..898a797f 100644 --- a/docs/vision_v1p2beta1/types.rst +++ b/docs/vision_v1p2beta1/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Vision v1p2beta1 API .. automodule:: google.cloud.vision_v1p2beta1.types :members: - :undoc-members: :show-inheritance: diff --git a/docs/vision_v1p3beta1/types.rst b/docs/vision_v1p3beta1/types.rst index 5fdbaea1..8f60a298 100644 --- a/docs/vision_v1p3beta1/types.rst +++ b/docs/vision_v1p3beta1/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Vision v1p3beta1 API .. automodule:: google.cloud.vision_v1p3beta1.types :members: - :undoc-members: :show-inheritance: diff --git a/docs/vision_v1p4beta1/types.rst b/docs/vision_v1p4beta1/types.rst index a90d1fa2..214f01b1 100644 --- a/docs/vision_v1p4beta1/types.rst +++ b/docs/vision_v1p4beta1/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Vision v1p4beta1 API .. automodule:: google.cloud.vision_v1p4beta1.types :members: - :undoc-members: :show-inheritance: diff --git a/google/cloud/vision/__init__.py b/google/cloud/vision/__init__.py index d1fa357a..dcde754d 100644 --- a/google/cloud/vision/__init__.py +++ b/google/cloud/vision/__init__.py @@ -15,6 +15,11 @@ # limitations under the License. # +from google.cloud.vision import gapic_version as package_version + +__version__ = package_version.__version__ + + from google.cloud.vision_v1.services.image_annotator.async_client import ( ImageAnnotatorAsyncClient, ) diff --git a/samples/snippets/quickstart/quickstart_test.py b/google/cloud/vision/gapic_version.py similarity index 73% rename from samples/snippets/quickstart/quickstart_test.py rename to google/cloud/vision/gapic_version.py index d483d413..47c54531 100644 --- a/samples/snippets/quickstart/quickstart_test.py +++ b/google/cloud/vision/gapic_version.py @@ -1,4 +1,5 @@ -# Copyright 2016 Google Inc. All Rights Reserved. +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,11 +12,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -import quickstart - - -def test_quickstart(capsys): - quickstart.run_quickstart() - out, _ = capsys.readouterr() - assert 'Labels' in out +# +__version__ = "3.2.0" # {x-release-please-version} diff --git a/google/cloud/vision_v1/__init__.py b/google/cloud/vision_v1/__init__.py index bfe927d2..402f1a2e 100644 --- a/google/cloud/vision_v1/__init__.py +++ b/google/cloud/vision_v1/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.vision import gapic_version as package_version + +__version__ = package_version.__version__ + from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers diff --git a/google/cloud/vision_v1/gapic_metadata.json b/google/cloud/vision_v1/gapic_metadata.json new file mode 100644 index 00000000..71b189b5 --- /dev/null +++ b/google/cloud/vision_v1/gapic_metadata.json @@ -0,0 +1,267 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.vision_v1", + "protoPackage": "google.cloud.vision.v1", + "schema": "1.0", + "services": { + "ImageAnnotator": { + "clients": { + "grpc": { + "libraryClient": "ImageAnnotatorClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "AsyncBatchAnnotateImages": { + "methods": [ + "async_batch_annotate_images" + ] + }, + "BatchAnnotateFiles": { + "methods": [ + "batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ImageAnnotatorAsyncClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "AsyncBatchAnnotateImages": { + "methods": [ + "async_batch_annotate_images" + ] + }, + "BatchAnnotateFiles": { + "methods": [ + "batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + } + } + }, + "ProductSearch": { + "clients": { + "grpc": { + "libraryClient": "ProductSearchClient", + "rpcs": { + "AddProductToProductSet": { + "methods": [ + "add_product_to_product_set" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "CreateProductSet": { + "methods": [ + "create_product_set" + ] + }, + "CreateReferenceImage": { + "methods": [ + "create_reference_image" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "DeleteProductSet": { + "methods": [ + "delete_product_set" + ] + }, + "DeleteReferenceImage": { + "methods": [ + "delete_reference_image" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "GetProductSet": { + "methods": [ + "get_product_set" + ] + }, + "GetReferenceImage": { + "methods": [ + "get_reference_image" + ] + }, + "ImportProductSets": { + "methods": [ + "import_product_sets" + ] + }, + "ListProductSets": { + "methods": [ + "list_product_sets" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "ListProductsInProductSet": { + "methods": [ + "list_products_in_product_set" + ] + }, + "ListReferenceImages": { + "methods": [ + "list_reference_images" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveProductFromProductSet": { + "methods": [ + "remove_product_from_product_set" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + }, + "UpdateProductSet": { + "methods": [ + "update_product_set" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductSearchAsyncClient", + "rpcs": { + "AddProductToProductSet": { + "methods": [ + "add_product_to_product_set" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "CreateProductSet": { + "methods": [ + "create_product_set" + ] + }, + "CreateReferenceImage": { + "methods": [ + "create_reference_image" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "DeleteProductSet": { + "methods": [ + "delete_product_set" + ] + }, + "DeleteReferenceImage": { + "methods": [ + "delete_reference_image" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "GetProductSet": { + "methods": [ + "get_product_set" + ] + }, + "GetReferenceImage": { + "methods": [ + "get_reference_image" + ] + }, + "ImportProductSets": { + "methods": [ + "import_product_sets" + ] + }, + "ListProductSets": { + "methods": [ + "list_product_sets" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "ListProductsInProductSet": { + "methods": [ + "list_products_in_product_set" + ] + }, + "ListReferenceImages": { + "methods": [ + "list_reference_images" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveProductFromProductSet": { + "methods": [ + "remove_product_from_product_set" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + }, + "UpdateProductSet": { + "methods": [ + "update_product_set" + ] + } + } + } + } + } + } +} diff --git a/samples/snippets/detect/set_endpoint_test.py b/google/cloud/vision_v1/gapic_version.py similarity index 72% rename from samples/snippets/detect/set_endpoint_test.py rename to google/cloud/vision_v1/gapic_version.py index 37bd590c..47c54531 100644 --- a/samples/snippets/detect/set_endpoint_test.py +++ b/google/cloud/vision_v1/gapic_version.py @@ -1,4 +1,5 @@ -# Copyright 2019 Google LLC +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,13 +12,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -import set_endpoint - - -def test_set_endpoint(capsys): - set_endpoint.set_endpoint() - - out, _ = capsys.readouterr() - assert 'System' in out - assert 'bounds:' in out +# +__version__ = "3.2.0" # {x-release-please-version} diff --git a/google/cloud/vision_v1/services/image_annotator/async_client.py b/google/cloud/vision_v1/services/image_annotator/async_client.py index eb69e574..792fd43d 100644 --- a/google/cloud/vision_v1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1/services/image_annotator/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -165,9 +176,9 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -211,11 +222,15 @@ def __init__( async def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -247,10 +262,10 @@ async def sample_batch_annotate_images(): print(response) Args: - request (Union[google.cloud.vision_v1.types.BatchAnnotateImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.BatchAnnotateImagesRequest, dict]]): The request object. Multiple image annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]`): Required. Individual image annotation requests for this batch. @@ -317,11 +332,13 @@ async def sample_batch_annotate_images(): async def batch_annotate_files( self, - request: Union[image_annotator.BatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateFileRequest] = None, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation @@ -359,10 +376,10 @@ async def sample_batch_annotate_files(): print(response) Args: - request (Union[google.cloud.vision_v1.types.BatchAnnotateFilesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.BatchAnnotateFilesRequest, dict]]): The request object. A list of requests to annotate files using the BatchAnnotateFiles API. - requests (:class:`Sequence[google.cloud.vision_v1.types.AnnotateFileRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1.types.AnnotateFileRequest]`): Required. The list of file annotation requests. Right now we support only one AnnotateFileRequest in @@ -429,12 +446,16 @@ async def sample_batch_annotate_files(): async def async_batch_annotate_images( self, - request: Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, - output_config: image_annotator.OutputConfig = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, + output_config: Optional[image_annotator.OutputConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of @@ -474,16 +495,16 @@ async def sample_async_batch_annotate_images(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1.types.AsyncBatchAnnotateImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.AsyncBatchAnnotateImagesRequest, dict]]): The request object. Request for async image annotation for a list of images. - requests (:class:`Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]`): Required. Individual image annotation requests for this batch. @@ -570,11 +591,15 @@ async def sample_async_batch_annotate_images(): async def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of @@ -609,16 +634,16 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1.types.AsyncBatchAnnotateFilesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.AsyncBatchAnnotateFilesRequest, dict]]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]`): Required. Individual async file annotation requests for this batch. @@ -701,14 +726,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1/services/image_annotator/client.py b/google/cloud/vision_v1/services/image_annotator/client.py index 2aa8c280..e2307929 100644 --- a/google/cloud/vision_v1/services/image_annotator/client.py +++ b/google/cloud/vision_v1/services/image_annotator/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -58,7 +70,7 @@ class ImageAnnotatorClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. @@ -361,8 +373,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageAnnotatorTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ImageAnnotatorTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -376,7 +388,7 @@ def __init__( transport (Union[str, ImageAnnotatorTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -406,6 +418,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -458,11 +471,15 @@ def __init__( def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -497,7 +514,7 @@ def sample_batch_annotate_images(): request (Union[google.cloud.vision_v1.types.BatchAnnotateImagesRequest, dict]): The request object. Multiple image annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. @@ -557,11 +574,13 @@ def sample_batch_annotate_images(): def batch_annotate_files( self, - request: Union[image_annotator.BatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateFileRequest] = None, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation @@ -602,7 +621,7 @@ def sample_batch_annotate_files(): request (Union[google.cloud.vision_v1.types.BatchAnnotateFilesRequest, dict]): The request object. A list of requests to annotate files using the BatchAnnotateFiles API. - requests (Sequence[google.cloud.vision_v1.types.AnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AnnotateFileRequest]): Required. The list of file annotation requests. Right now we support only one AnnotateFileRequest in @@ -662,12 +681,16 @@ def sample_batch_annotate_files(): def async_batch_annotate_images( self, - request: Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, - output_config: image_annotator.OutputConfig = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, + output_config: Optional[image_annotator.OutputConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of @@ -716,7 +739,7 @@ def sample_async_batch_annotate_images(): request (Union[google.cloud.vision_v1.types.AsyncBatchAnnotateImagesRequest, dict]): The request object. Request for async image annotation for a list of images. - requests (Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. @@ -798,11 +821,15 @@ def sample_async_batch_annotate_images(): def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of @@ -846,7 +873,7 @@ def sample_async_batch_annotate_files(): request (Union[google.cloud.vision_v1.types.AsyncBatchAnnotateFilesRequest, dict]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. @@ -931,14 +958,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1/services/image_annotator/transports/base.py b/google/cloud/vision_v1/services/image_annotator/transports/base.py index 2ca9c1fa..5de3670f 100644 --- a/google/cloud/vision_v1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1/services/image_annotator/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -29,14 +30,9 @@ from google.cloud.vision_v1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ImageAnnotatorTransport(abc.ABC): @@ -53,7 +49,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1/services/image_annotator/transports/grpc.py index d5ff3a88..a65d749b 100644 --- a/google/cloud/vision_v1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1/services/image_annotator/transports/grpc.py @@ -52,14 +52,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -187,8 +187,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py index 43860430..cbba09f5 100644 --- a/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py @@ -54,7 +54,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -97,15 +97,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1/services/product_search/async_client.py b/google/cloud/vision_v1/services/product_search/async_client.py index b8f9acfa..c29303af 100644 --- a/google/cloud/vision_v1/services/product_search/async_client.py +++ b/google/cloud/vision_v1/services/product_search/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -189,9 +200,9 @@ def transport(self) -> ProductSearchTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ProductSearchTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the product search client. @@ -235,13 +246,15 @@ def __init__( async def create_product_set( self, - request: Union[product_search_service.CreateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductSetRequest, dict] + ] = None, *, - parent: str = None, - product_set: product_search_service.ProductSet = None, - product_set_id: str = None, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. @@ -278,7 +291,7 @@ async def sample_create_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1.types.CreateProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.CreateProductSetRequest, dict]]): The request object. Request message for the `CreateProductSet` method. parent (:class:`str`): @@ -375,11 +388,13 @@ async def sample_create_product_set(): async def list_product_sets( self, - request: Union[product_search_service.ListProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductSetsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductSetsAsyncPager: r"""Lists ProductSets in an unspecified order. @@ -417,7 +432,7 @@ async def sample_list_product_sets(): print(response) Args: - request (Union[google.cloud.vision_v1.types.ListProductSetsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.ListProductSetsRequest, dict]]): The request object. Request message for the `ListProductSets` method. parent (:class:`str`): @@ -506,11 +521,13 @@ async def sample_list_product_sets(): async def get_product_set( self, - request: Union[product_search_service.GetProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. @@ -546,7 +563,7 @@ async def sample_get_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1.types.GetProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.GetProductSetRequest, dict]]): The request object. Request message for the `GetProductSet` method. name (:class:`str`): @@ -627,12 +644,14 @@ async def sample_get_product_set(): async def update_product_set( self, - request: Union[product_search_service.UpdateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductSetRequest, dict] + ] = None, *, - product_set: product_search_service.ProductSet = None, - update_mask: field_mask_pb2.FieldMask = None, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be @@ -671,7 +690,7 @@ async def sample_update_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1.types.UpdateProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.UpdateProductSetRequest, dict]]): The request object. Request message for the `UpdateProductSet` method. product_set (:class:`google.cloud.vision_v1.types.ProductSet`): @@ -763,11 +782,13 @@ async def sample_update_product_set(): async def delete_product_set( self, - request: Union[product_search_service.DeleteProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a ProductSet. Products and @@ -799,7 +820,7 @@ async def sample_delete_product_set(): await client.delete_product_set(request=request) Args: - request (Union[google.cloud.vision_v1.types.DeleteProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.DeleteProductSetRequest, dict]]): The request object. Request message for the `DeleteProductSet` method. name (:class:`str`): @@ -868,13 +889,15 @@ async def sample_delete_product_set(): async def create_product( self, - request: Union[product_search_service.CreateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductRequest, dict] + ] = None, *, - parent: str = None, - product: product_search_service.Product = None, - product_id: str = None, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Creates and returns a new product resource. @@ -915,7 +938,7 @@ async def sample_create_product(): print(response) Args: - request (Union[google.cloud.vision_v1.types.CreateProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.CreateProductRequest, dict]]): The request object. Request message for the `CreateProduct` method. parent (:class:`str`): @@ -1007,11 +1030,13 @@ async def sample_create_product(): async def list_products( self, - request: Union[product_search_service.ListProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsAsyncPager: r"""Lists products in an unspecified order. @@ -1049,7 +1074,7 @@ async def sample_list_products(): print(response) Args: - request (Union[google.cloud.vision_v1.types.ListProductsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.ListProductsRequest, dict]]): The request object. Request message for the `ListProducts` method. parent (:class:`str`): @@ -1138,11 +1163,11 @@ async def sample_list_products(): async def get_product( self, - request: Union[product_search_service.GetProductRequest, dict] = None, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Gets information associated with a Product. @@ -1178,7 +1203,7 @@ async def sample_get_product(): print(response) Args: - request (Union[google.cloud.vision_v1.types.GetProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.GetProductRequest, dict]]): The request object. Request message for the `GetProduct` method. name (:class:`str`): @@ -1254,12 +1279,14 @@ async def sample_get_product(): async def update_product( self, - request: Union[product_search_service.UpdateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductRequest, dict] + ] = None, *, - product: product_search_service.Product = None, - update_mask: field_mask_pb2.FieldMask = None, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, @@ -1305,7 +1332,7 @@ async def sample_update_product(): print(response) Args: - request (Union[google.cloud.vision_v1.types.UpdateProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.UpdateProductRequest, dict]]): The request object. Request message for the `UpdateProduct` method. product (:class:`google.cloud.vision_v1.types.Product`): @@ -1394,11 +1421,13 @@ async def sample_update_product(): async def delete_product( self, - request: Union[product_search_service.DeleteProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a product and its reference @@ -1432,7 +1461,7 @@ async def sample_delete_product(): await client.delete_product(request=request) Args: - request (Union[google.cloud.vision_v1.types.DeleteProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.DeleteProductRequest, dict]]): The request object. Request message for the `DeleteProduct` method. name (:class:`str`): @@ -1501,13 +1530,15 @@ async def sample_delete_product(): async def create_reference_image( self, - request: Union[product_search_service.CreateReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateReferenceImageRequest, dict] + ] = None, *, - parent: str = None, - reference_image: product_search_service.ReferenceImage = None, - reference_image_id: str = None, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. @@ -1564,7 +1595,7 @@ async def sample_create_reference_image(): print(response) Args: - request (Union[google.cloud.vision_v1.types.CreateReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.CreateReferenceImageRequest, dict]]): The request object. Request message for the `CreateReferenceImage` method. parent (:class:`str`): @@ -1662,11 +1693,13 @@ async def sample_create_reference_image(): async def delete_reference_image( self, - request: Union[product_search_service.DeleteReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a reference image. @@ -1701,7 +1734,7 @@ async def sample_delete_reference_image(): await client.delete_reference_image(request=request) Args: - request (Union[google.cloud.vision_v1.types.DeleteReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.DeleteReferenceImageRequest, dict]]): The request object. Request message for the `DeleteReferenceImage` method. name (:class:`str`): @@ -1771,11 +1804,13 @@ async def sample_delete_reference_image(): async def list_reference_images( self, - request: Union[product_search_service.ListReferenceImagesRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListReferenceImagesRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListReferenceImagesAsyncPager: r"""Lists reference images. @@ -1814,7 +1849,7 @@ async def sample_list_reference_images(): print(response) Args: - request (Union[google.cloud.vision_v1.types.ListReferenceImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.ListReferenceImagesRequest, dict]]): The request object. Request message for the `ListReferenceImages` method. parent (:class:`str`): @@ -1904,11 +1939,13 @@ async def sample_list_reference_images(): async def get_reference_image( self, - request: Union[product_search_service.GetReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. @@ -1944,7 +1981,7 @@ async def sample_get_reference_image(): print(response) Args: - request (Union[google.cloud.vision_v1.types.GetReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.GetReferenceImageRequest, dict]]): The request object. Request message for the `GetReferenceImage` method. name (:class:`str`): @@ -2023,14 +2060,14 @@ async def sample_get_reference_image(): async def add_product_to_product_set( self, - request: Union[ - product_search_service.AddProductToProductSetRequest, dict + request: Optional[ + Union[product_search_service.AddProductToProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is @@ -2068,7 +2105,7 @@ async def sample_add_product_to_product_set(): await client.add_product_to_product_set(request=request) Args: - request (Union[google.cloud.vision_v1.types.AddProductToProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.AddProductToProductSetRequest, dict]]): The request object. Request message for the `AddProductToProductSet` method. name (:class:`str`): @@ -2150,14 +2187,14 @@ async def sample_add_product_to_product_set(): async def remove_product_from_product_set( self, - request: Union[ - product_search_service.RemoveProductFromProductSetRequest, dict + request: Optional[ + Union[product_search_service.RemoveProductFromProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Removes a Product from the specified ProductSet. @@ -2187,7 +2224,7 @@ async def sample_remove_product_from_product_set(): await client.remove_product_from_product_set(request=request) Args: - request (Union[google.cloud.vision_v1.types.RemoveProductFromProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.RemoveProductFromProductSetRequest, dict]]): The request object. Request message for the `RemoveProductFromProductSet` method. name (:class:`str`): @@ -2269,13 +2306,13 @@ async def sample_remove_product_from_product_set(): async def list_products_in_product_set( self, - request: Union[ - product_search_service.ListProductsInProductSetRequest, dict + request: Optional[ + Union[product_search_service.ListProductsInProductSetRequest, dict] ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsInProductSetAsyncPager: r"""Lists the Products in a ProductSet, in an unspecified order. If @@ -2315,7 +2352,7 @@ async def sample_list_products_in_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1.types.ListProductsInProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.ListProductsInProductSetRequest, dict]]): The request object. Request message for the `ListProductsInProductSet` method. name (:class:`str`): @@ -2406,12 +2443,16 @@ async def sample_list_products_in_product_set(): async def import_product_sets( self, - request: Union[product_search_service.ImportProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ImportProductSetsRequest, dict] + ] = None, *, - parent: str = None, - input_config: product_search_service.ImportProductSetsInputConfig = None, + parent: Optional[str] = None, + input_config: Optional[ + product_search_service.ImportProductSetsInputConfig + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Asynchronous API that imports a list of reference images to @@ -2452,13 +2493,13 @@ async def sample_import_product_sets(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1.types.ImportProductSetsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.ImportProductSetsRequest, dict]]): The request object. Request message for the `ImportProductSets` method. parent (:class:`str`): @@ -2559,11 +2600,13 @@ async def sample_import_product_sets(): async def purge_products( self, - request: Union[product_search_service.PurgeProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.PurgeProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Asynchronous API to delete all Products in a ProductSet or all @@ -2619,13 +2662,13 @@ async def sample_purge_products(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1.types.PurgeProductsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1.types.PurgeProductsRequest, dict]]): The request object. Request message for the `PurgeProducts` method. parent (:class:`str`): @@ -2723,14 +2766,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ProductSearchAsyncClient",) diff --git a/google/cloud/vision_v1/services/product_search/client.py b/google/cloud/vision_v1/services/product_search/client.py index 9d974b6e..77a2c4da 100644 --- a/google/cloud/vision_v1/services/product_search/client.py +++ b/google/cloud/vision_v1/services/product_search/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -62,7 +74,7 @@ class ProductSearchClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ProductSearchTransport]: """Returns an appropriate transport class. @@ -403,8 +415,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductSearchTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ProductSearchTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the product search client. @@ -418,7 +430,7 @@ def __init__( transport (Union[str, ProductSearchTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -448,6 +460,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -500,13 +513,15 @@ def __init__( def create_product_set( self, - request: Union[product_search_service.CreateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductSetRequest, dict] + ] = None, *, - parent: str = None, - product_set: product_search_service.ProductSet = None, - product_set_id: str = None, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. @@ -633,11 +648,13 @@ def sample_create_product_set(): def list_product_sets( self, - request: Union[product_search_service.ListProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductSetsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductSetsPager: r"""Lists ProductSets in an unspecified order. @@ -754,11 +771,13 @@ def sample_list_product_sets(): def get_product_set( self, - request: Union[product_search_service.GetProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. @@ -865,12 +884,14 @@ def sample_get_product_set(): def update_product_set( self, - request: Union[product_search_service.UpdateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductSetRequest, dict] + ] = None, *, - product_set: product_search_service.ProductSet = None, - update_mask: field_mask_pb2.FieldMask = None, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be @@ -991,11 +1012,13 @@ def sample_update_product_set(): def delete_product_set( self, - request: Union[product_search_service.DeleteProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a ProductSet. Products and @@ -1086,13 +1109,15 @@ def sample_delete_product_set(): def create_product( self, - request: Union[product_search_service.CreateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductRequest, dict] + ] = None, *, - parent: str = None, - product: product_search_service.Product = None, - product_id: str = None, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Creates and returns a new product resource. @@ -1218,11 +1243,13 @@ def sample_create_product(): def list_products( self, - request: Union[product_search_service.ListProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsPager: r"""Lists products in an unspecified order. @@ -1339,11 +1366,11 @@ def sample_list_products(): def get_product( self, - request: Union[product_search_service.GetProductRequest, dict] = None, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Gets information associated with a Product. @@ -1445,12 +1472,14 @@ def sample_get_product(): def update_product( self, - request: Union[product_search_service.UpdateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductRequest, dict] + ] = None, *, - product: product_search_service.Product = None, - update_mask: field_mask_pb2.FieldMask = None, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, @@ -1575,11 +1604,13 @@ def sample_update_product(): def delete_product( self, - request: Union[product_search_service.DeleteProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a product and its reference @@ -1672,13 +1703,15 @@ def sample_delete_product(): def create_reference_image( self, - request: Union[product_search_service.CreateReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateReferenceImageRequest, dict] + ] = None, *, - parent: str = None, - reference_image: product_search_service.ReferenceImage = None, - reference_image_id: str = None, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. @@ -1826,11 +1859,13 @@ def sample_create_reference_image(): def delete_reference_image( self, - request: Union[product_search_service.DeleteReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a reference image. @@ -1925,11 +1960,13 @@ def sample_delete_reference_image(): def list_reference_images( self, - request: Union[product_search_service.ListReferenceImagesRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListReferenceImagesRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListReferenceImagesPager: r"""Lists reference images. @@ -2048,11 +2085,13 @@ def sample_list_reference_images(): def get_reference_image( self, - request: Union[product_search_service.GetReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. @@ -2157,14 +2196,14 @@ def sample_get_reference_image(): def add_product_to_product_set( self, - request: Union[ - product_search_service.AddProductToProductSetRequest, dict + request: Optional[ + Union[product_search_service.AddProductToProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is @@ -2278,14 +2317,14 @@ def sample_add_product_to_product_set(): def remove_product_from_product_set( self, - request: Union[ - product_search_service.RemoveProductFromProductSetRequest, dict + request: Optional[ + Union[product_search_service.RemoveProductFromProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Removes a Product from the specified ProductSet. @@ -2391,13 +2430,13 @@ def sample_remove_product_from_product_set(): def list_products_in_product_set( self, - request: Union[ - product_search_service.ListProductsInProductSetRequest, dict + request: Optional[ + Union[product_search_service.ListProductsInProductSetRequest, dict] ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsInProductSetPager: r"""Lists the Products in a ProductSet, in an unspecified order. If @@ -2522,12 +2561,16 @@ def sample_list_products_in_product_set(): def import_product_sets( self, - request: Union[product_search_service.ImportProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ImportProductSetsRequest, dict] + ] = None, *, - parent: str = None, - input_config: product_search_service.ImportProductSetsInputConfig = None, + parent: Optional[str] = None, + input_config: Optional[ + product_search_service.ImportProductSetsInputConfig + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Asynchronous API that imports a list of reference images to @@ -2668,11 +2711,13 @@ def sample_import_product_sets(): def purge_products( self, - request: Union[product_search_service.PurgeProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.PurgeProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Asynchronous API to delete all Products in a ProductSet or all @@ -2832,14 +2877,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ProductSearchClient",) diff --git a/google/cloud/vision_v1/services/product_search/transports/base.py b/google/cloud/vision_v1/services/product_search/transports/base.py index ba81cee9..d885e52c 100644 --- a/google/cloud/vision_v1/services/product_search/transports/base.py +++ b/google/cloud/vision_v1/services/product_search/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -30,14 +31,9 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ProductSearchTransport(abc.ABC): @@ -54,7 +50,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1/services/product_search/transports/grpc.py b/google/cloud/vision_v1/services/product_search/transports/grpc.py index d6cd534a..7c196698 100644 --- a/google/cloud/vision_v1/services/product_search/transports/grpc.py +++ b/google/cloud/vision_v1/services/product_search/transports/grpc.py @@ -67,14 +67,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -202,8 +202,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py b/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py index d440d690..8b8087ad 100644 --- a/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py @@ -69,7 +69,7 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -112,15 +112,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1/types/geometry.py b/google/cloud/vision_v1/types/geometry.py index f03e3551..800f18bd 100644 --- a/google/cloud/vision_v1/types/geometry.py +++ b/google/cloud/vision_v1/types/geometry.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -39,11 +41,11 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: int = proto.Field( proto.INT32, number=1, ) - y = proto.Field( + y: int = proto.Field( proto.INT32, number=2, ) @@ -61,11 +63,11 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) @@ -75,18 +77,18 @@ class BoundingPoly(proto.Message): r"""A bounding polygon for the detected image annotation. Attributes: - vertices (Sequence[google.cloud.vision_v1.types.Vertex]): + vertices (MutableSequence[google.cloud.vision_v1.types.Vertex]): The bounding polygon vertices. - normalized_vertices (Sequence[google.cloud.vision_v1.types.NormalizedVertex]): + normalized_vertices (MutableSequence[google.cloud.vision_v1.types.NormalizedVertex]): The bounding polygon normalized vertices. """ - vertices = proto.RepeatedField( + vertices: MutableSequence["Vertex"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Vertex", ) - normalized_vertices = proto.RepeatedField( + normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", @@ -108,15 +110,15 @@ class Position(proto.Message): Z coordinate (or depth). """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) - z = proto.Field( + z: float = proto.Field( proto.FLOAT, number=3, ) diff --git a/google/cloud/vision_v1/types/image_annotator.py b/google/cloud/vision_v1/types/image_annotator.py index d14ff8c4..371727b4 100644 --- a/google/cloud/vision_v1/types/image_annotator.py +++ b/google/cloud/vision_v1/types/image_annotator.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1.types import geometry @@ -120,16 +122,16 @@ class Type(proto.Enum): PRODUCT_SEARCH = 12 OBJECT_LOCALIZATION = 19 - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=1, enum=Type, ) - max_results = proto.Field( + max_results: int = proto.Field( proto.INT32, number=2, ) - model = proto.Field( + model: str = proto.Field( proto.STRING, number=3, ) @@ -170,11 +172,11 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field( + gcs_image_uri: str = proto.Field( proto.STRING, number=1, ) - image_uri = proto.Field( + image_uri: str = proto.Field( proto.STRING, number=2, ) @@ -199,11 +201,11 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field( + content: bytes = proto.Field( proto.BYTES, number=1, ) - source = proto.Field( + source: "ImageSource" = proto.Field( proto.MESSAGE, number=2, message="ImageSource", @@ -231,7 +233,7 @@ class FaceAnnotation(proto.Message): an image. It is not based on the landmarker results, only on the initial face detection, hence the fd (face detection) prefix. - landmarks (Sequence[google.cloud.vision_v1.types.FaceAnnotation.Landmark]): + landmarks (MutableSequence[google.cloud.vision_v1.types.FaceAnnotation.Landmark]): Detected face landmarks. roll_angle (float): Roll angle, which indicates the amount of @@ -320,83 +322,83 @@ class Type(proto.Enum): LEFT_CHEEK_CENTER = 35 RIGHT_CHEEK_CENTER = 36 - type_ = proto.Field( + type_: "FaceAnnotation.Landmark.Type" = proto.Field( proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type", ) - position = proto.Field( + position: geometry.Position = proto.Field( proto.MESSAGE, number=4, message=geometry.Position, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - fd_bounding_poly = proto.Field( + fd_bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - landmarks = proto.RepeatedField( + landmarks: MutableSequence[Landmark] = proto.RepeatedField( proto.MESSAGE, number=3, message=Landmark, ) - roll_angle = proto.Field( + roll_angle: float = proto.Field( proto.FLOAT, number=4, ) - pan_angle = proto.Field( + pan_angle: float = proto.Field( proto.FLOAT, number=5, ) - tilt_angle = proto.Field( + tilt_angle: float = proto.Field( proto.FLOAT, number=6, ) - detection_confidence = proto.Field( + detection_confidence: float = proto.Field( proto.FLOAT, number=7, ) - landmarking_confidence = proto.Field( + landmarking_confidence: float = proto.Field( proto.FLOAT, number=8, ) - joy_likelihood = proto.Field( + joy_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", ) - sorrow_likelihood = proto.Field( + sorrow_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=10, enum="Likelihood", ) - anger_likelihood = proto.Field( + anger_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=11, enum="Likelihood", ) - surprise_likelihood = proto.Field( + surprise_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=12, enum="Likelihood", ) - under_exposed_likelihood = proto.Field( + under_exposed_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=13, enum="Likelihood", ) - blurred_likelihood = proto.Field( + blurred_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=14, enum="Likelihood", ) - headwear_likelihood = proto.Field( + headwear_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=15, enum="Likelihood", @@ -411,7 +413,7 @@ class LocationInfo(proto.Message): lat/long location coordinates. """ - lat_lng = proto.Field( + lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, @@ -430,15 +432,15 @@ class Property(proto.Message): Value of numeric properties. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - uint64_value = proto.Field( + uint64_value: int = proto.Field( proto.UINT64, number=3, ) @@ -476,54 +478,54 @@ class EntityAnnotation(proto.Message): bounding_poly (google.cloud.vision_v1.types.BoundingPoly): Image region to which this entity belongs. Not produced for ``LABEL_DETECTION`` features. - locations (Sequence[google.cloud.vision_v1.types.LocationInfo]): + locations (MutableSequence[google.cloud.vision_v1.types.LocationInfo]): The location information for the detected entity. Multiple ``LocationInfo`` elements can be present because one location may indicate the location of the scene in the image, and another location may indicate the location of the place where the image was taken. Location information is usually present for landmarks. - properties (Sequence[google.cloud.vision_v1.types.Property]): + properties (MutableSequence[google.cloud.vision_v1.types.Property]): Some entities may have optional user-supplied ``Property`` (name/value) fields, such a score or string that qualifies the entity. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - locale = proto.Field( + locale: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) - topicality = proto.Field( + topicality: float = proto.Field( proto.FLOAT, number=6, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=7, message=geometry.BoundingPoly, ) - locations = proto.RepeatedField( + locations: MutableSequence["LocationInfo"] = proto.RepeatedField( proto.MESSAGE, number=8, message="LocationInfo", ) - properties = proto.RepeatedField( + properties: MutableSequence["Property"] = proto.RepeatedField( proto.MESSAGE, number=9, message="Property", @@ -550,23 +552,23 @@ class LocalizedObjectAnnotation(proto.Message): This must be populated. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=5, message=geometry.BoundingPoly, @@ -602,27 +604,27 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult = proto.Field( + adult: "Likelihood" = proto.Field( proto.ENUM, number=1, enum="Likelihood", ) - spoof = proto.Field( + spoof: "Likelihood" = proto.Field( proto.ENUM, number=2, enum="Likelihood", ) - medical = proto.Field( + medical: "Likelihood" = proto.Field( proto.ENUM, number=3, enum="Likelihood", ) - violence = proto.Field( + violence: "Likelihood" = proto.Field( proto.ENUM, number=4, enum="Likelihood", ) - racy = proto.Field( + racy: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", @@ -639,12 +641,12 @@ class LatLongRect(proto.Message): Max lat/long pair. """ - min_lat_lng = proto.Field( + min_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, ) - max_lat_lng = proto.Field( + max_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=2, message=latlng_pb2.LatLng, @@ -665,16 +667,16 @@ class ColorInfo(proto.Message): Value in range [0, 1]. """ - color = proto.Field( + color: color_pb2.Color = proto.Field( proto.MESSAGE, number=1, message=color_pb2.Color, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - pixel_fraction = proto.Field( + pixel_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -684,12 +686,12 @@ class DominantColorsAnnotation(proto.Message): r"""Set of dominant colors and their corresponding scores. Attributes: - colors (Sequence[google.cloud.vision_v1.types.ColorInfo]): + colors (MutableSequence[google.cloud.vision_v1.types.ColorInfo]): RGB color values with their score and pixel fraction. """ - colors = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ColorInfo", @@ -705,7 +707,7 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, message="DominantColorsAnnotation", @@ -728,16 +730,16 @@ class CropHint(proto.Message): with respect to the original image. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) - importance_fraction = proto.Field( + importance_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -748,11 +750,11 @@ class CropHintsAnnotation(proto.Message): serving images. Attributes: - crop_hints (Sequence[google.cloud.vision_v1.types.CropHint]): + crop_hints (MutableSequence[google.cloud.vision_v1.types.CropHint]): Crop hint results. """ - crop_hints = proto.RepeatedField( + crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( proto.MESSAGE, number=1, message="CropHint", @@ -763,7 +765,7 @@ class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. Attributes: - aspect_ratios (Sequence[float]): + aspect_ratios (MutableSequence[float]): Aspect ratios in floats, representing the ratio of the width to the height of the image. For example, if the desired aspect ratio is 4/3, @@ -774,7 +776,7 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField( + aspect_ratios: MutableSequence[float] = proto.RepeatedField( proto.FLOAT, number=1, ) @@ -789,7 +791,7 @@ class WebDetectionParams(proto.Message): geo information in the image. """ - include_geo_results = proto.Field( + include_geo_results: bool = proto.Field( proto.BOOL, number=2, ) @@ -804,16 +806,16 @@ class TextDetectionParams(proto.Message): By default, Cloud Vision API only includes confidence score for DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence score for TEXT_DETECTION as well. - advanced_ocr_options (Sequence[str]): + advanced_ocr_options (MutableSequence[str]): A list of advanced OCR options to fine-tune OCR behavior. """ - enable_text_detection_confidence_score = proto.Field( + enable_text_detection_confidence_score: bool = proto.Field( proto.BOOL, number=9, ) - advanced_ocr_options = proto.RepeatedField( + advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=11, ) @@ -825,7 +827,7 @@ class ImageContext(proto.Message): Attributes: lat_long_rect (google.cloud.vision_v1.types.LatLongRect): Not used. - language_hints (Sequence[str]): + language_hints (MutableSequence[str]): List of languages to use for TEXT_DETECTION. In most cases, an empty value yields the best results since it enables automatic language detection. For languages based on the @@ -847,31 +849,31 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect = proto.Field( + lat_long_rect: "LatLongRect" = proto.Field( proto.MESSAGE, number=1, message="LatLongRect", ) - language_hints = proto.RepeatedField( + language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params = proto.Field( + crop_hints_params: "CropHintsParams" = proto.Field( proto.MESSAGE, number=4, message="CropHintsParams", ) - product_search_params = proto.Field( + product_search_params: product_search.ProductSearchParams = proto.Field( proto.MESSAGE, number=5, message=product_search.ProductSearchParams, ) - web_detection_params = proto.Field( + web_detection_params: "WebDetectionParams" = proto.Field( proto.MESSAGE, number=6, message="WebDetectionParams", ) - text_detection_params = proto.Field( + text_detection_params: "TextDetectionParams" = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", @@ -886,24 +888,24 @@ class AnnotateImageRequest(proto.Message): Attributes: image (google.cloud.vision_v1.types.Image): The image to be processed. - features (Sequence[google.cloud.vision_v1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1.types.Feature]): Requested features. image_context (google.cloud.vision_v1.types.ImageContext): Additional context that may accompany the image. """ - image = proto.Field( + image: "Image" = proto.Field( proto.MESSAGE, number=1, message="Image", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", @@ -924,11 +926,11 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) - page_number = proto.Field( + page_number: int = proto.Field( proto.INT32, number=2, ) @@ -938,23 +940,23 @@ class AnnotateImageResponse(proto.Message): r"""Response to an image annotation request. Attributes: - face_annotations (Sequence[google.cloud.vision_v1.types.FaceAnnotation]): + face_annotations (MutableSequence[google.cloud.vision_v1.types.FaceAnnotation]): If present, face detection has completed successfully. - landmark_annotations (Sequence[google.cloud.vision_v1.types.EntityAnnotation]): + landmark_annotations (MutableSequence[google.cloud.vision_v1.types.EntityAnnotation]): If present, landmark detection has completed successfully. - logo_annotations (Sequence[google.cloud.vision_v1.types.EntityAnnotation]): + logo_annotations (MutableSequence[google.cloud.vision_v1.types.EntityAnnotation]): If present, logo detection has completed successfully. - label_annotations (Sequence[google.cloud.vision_v1.types.EntityAnnotation]): + label_annotations (MutableSequence[google.cloud.vision_v1.types.EntityAnnotation]): If present, label detection has completed successfully. - localized_object_annotations (Sequence[google.cloud.vision_v1.types.LocalizedObjectAnnotation]): + localized_object_annotations (MutableSequence[google.cloud.vision_v1.types.LocalizedObjectAnnotation]): If present, localized object detection has completed successfully. This will be sorted descending by confidence score. - text_annotations (Sequence[google.cloud.vision_v1.types.EntityAnnotation]): + text_annotations (MutableSequence[google.cloud.vision_v1.types.EntityAnnotation]): If present, text (OCR) detection has completed successfully. full_text_annotation (google.cloud.vision_v1.types.TextAnnotation): @@ -986,72 +988,74 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations = proto.RepeatedField( + face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FaceAnnotation", ) - landmark_annotations = proto.RepeatedField( + landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityAnnotation", ) - logo_annotations = proto.RepeatedField( + logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=3, message="EntityAnnotation", ) - label_annotations = proto.RepeatedField( + label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=4, message="EntityAnnotation", ) - localized_object_annotations = proto.RepeatedField( + localized_object_annotations: MutableSequence[ + "LocalizedObjectAnnotation" + ] = proto.RepeatedField( proto.MESSAGE, number=22, message="LocalizedObjectAnnotation", ) - text_annotations = proto.RepeatedField( + text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=5, message="EntityAnnotation", ) - full_text_annotation = proto.Field( + full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation = proto.Field( + safe_search_annotation: "SafeSearchAnnotation" = proto.Field( proto.MESSAGE, number=6, message="SafeSearchAnnotation", ) - image_properties_annotation = proto.Field( + image_properties_annotation: "ImageProperties" = proto.Field( proto.MESSAGE, number=8, message="ImageProperties", ) - crop_hints_annotation = proto.Field( + crop_hints_annotation: "CropHintsAnnotation" = proto.Field( proto.MESSAGE, number=11, message="CropHintsAnnotation", ) - web_detection = proto.Field( + web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, ) - product_search_results = proto.Field( + product_search_results: product_search.ProductSearchResults = proto.Field( proto.MESSAGE, number=14, message=product_search.ProductSearchResults, ) - error = proto.Field( + error: status_pb2.Status = proto.Field( proto.MESSAGE, number=9, message=status_pb2.Status, ) - context = proto.Field( + context: "ImageAnnotationContext" = proto.Field( proto.MESSAGE, number=21, message="ImageAnnotationContext", @@ -1063,7 +1067,7 @@ class BatchAnnotateImagesRequest(proto.Message): service call. Attributes: - requests (Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. parent (str): @@ -1081,12 +1085,12 @@ class BatchAnnotateImagesRequest(proto.Message): Example: ``projects/project-A/locations/eu``. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", ) - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=4, ) @@ -1096,12 +1100,12 @@ class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1.types.AnnotateImageResponse]): Individual responses to image annotation requests within the batch. """ - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageResponse", @@ -1115,12 +1119,12 @@ class AnnotateFileRequest(proto.Message): Attributes: input_config (google.cloud.vision_v1.types.InputConfig): Required. Information about the input file. - features (Sequence[google.cloud.vision_v1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1.types.Feature]): Required. Requested features. image_context (google.cloud.vision_v1.types.ImageContext): Additional context that may accompany the image(s) in the file. - pages (Sequence[int]): + pages (MutableSequence[int]): Pages of the file to perform image annotation. Pages starts from 1, we assume the first page of @@ -1138,22 +1142,22 @@ class AnnotateFileRequest(proto.Message): of the file. """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", ) - pages = proto.RepeatedField( + pages: MutableSequence[int] = proto.RepeatedField( proto.INT32, number=4, ) @@ -1168,7 +1172,7 @@ class AnnotateFileResponse(proto.Message): input_config (google.cloud.vision_v1.types.InputConfig): Information about the file for which this response is generated. - responses (Sequence[google.cloud.vision_v1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1.types.AnnotateImageResponse]): Individual responses to images found within the file. This field will be empty if the ``error`` field is set. total_pages (int): @@ -1179,21 +1183,21 @@ class AnnotateFileResponse(proto.Message): The ``responses`` field will not be set in this case. """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=2, message="AnnotateImageResponse", ) - total_pages = proto.Field( + total_pages: int = proto.Field( proto.INT32, number=3, ) - error = proto.Field( + error: status_pb2.Status = proto.Field( proto.MESSAGE, number=4, message=status_pb2.Status, @@ -1205,7 +1209,7 @@ class BatchAnnotateFilesRequest(proto.Message): BatchAnnotateFiles API. Attributes: - requests (Sequence[google.cloud.vision_v1.types.AnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AnnotateFileRequest]): Required. The list of file annotation requests. Right now we support only one AnnotateFileRequest in @@ -1225,12 +1229,12 @@ class BatchAnnotateFilesRequest(proto.Message): Example: ``projects/project-A/locations/eu``. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateFileRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateFileRequest", ) - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=3, ) @@ -1240,14 +1244,14 @@ class BatchAnnotateFilesResponse(proto.Message): r"""A list of file annotation responses. Attributes: - responses (Sequence[google.cloud.vision_v1.types.AnnotateFileResponse]): + responses (MutableSequence[google.cloud.vision_v1.types.AnnotateFileResponse]): The list of file annotation responses, each response corresponding to each AnnotateFileRequest in BatchAnnotateFilesRequest. """ - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateFileResponse", @@ -1260,7 +1264,7 @@ class AsyncAnnotateFileRequest(proto.Message): Attributes: input_config (google.cloud.vision_v1.types.InputConfig): Required. Information about the input file. - features (Sequence[google.cloud.vision_v1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1.types.Feature]): Required. Requested features. image_context (google.cloud.vision_v1.types.ImageContext): Additional context that may accompany the @@ -1270,22 +1274,22 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", ) - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=4, message="OutputConfig", @@ -1301,7 +1305,7 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, message="OutputConfig", @@ -1312,7 +1316,7 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): r"""Request for async image annotation for a list of images. Attributes: - requests (Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. output_config (google.cloud.vision_v1.types.OutputConfig): @@ -1333,17 +1337,17 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): Example: ``projects/project-A/locations/eu``. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", ) - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=2, message="OutputConfig", ) - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=4, ) @@ -1358,7 +1362,7 @@ class AsyncBatchAnnotateImagesResponse(proto.Message): AsyncBatchAnnotateImagesRequest. """ - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, message="OutputConfig", @@ -1370,7 +1374,7 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): single service call. Attributes: - requests (Sequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. parent (str): @@ -1388,12 +1392,12 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): Example: ``projects/project-A/locations/eu``. """ - requests = proto.RepeatedField( + requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileRequest", ) - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=4, ) @@ -1403,13 +1407,13 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1.types.AsyncAnnotateFileResponse]): + responses (MutableSequence[google.cloud.vision_v1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one for each request in AsyncBatchAnnotateFilesRequest. """ - responses = proto.RepeatedField( + responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileResponse", @@ -1437,16 +1441,16 @@ class InputConfig(proto.Message): are supported. Wildcards are not supported. """ - gcs_source = proto.Field( + gcs_source: "GcsSource" = proto.Field( proto.MESSAGE, number=1, message="GcsSource", ) - content = proto.Field( + content: bytes = proto.Field( proto.BYTES, number=3, ) - mime_type = proto.Field( + mime_type: str = proto.Field( proto.STRING, number=2, ) @@ -1473,12 +1477,12 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination = proto.Field( + gcs_destination: "GcsDestination" = proto.Field( proto.MESSAGE, number=1, message="GcsDestination", ) - batch_size = proto.Field( + batch_size: int = proto.Field( proto.INT32, number=2, ) @@ -1495,7 +1499,7 @@ class GcsSource(proto.Message): Wildcards are not currently supported. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1535,7 +1539,7 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1562,17 +1566,17 @@ class State(proto.Enum): DONE = 3 CANCELLED = 4 - state = proto.Field( + state: State = proto.Field( proto.ENUM, number=1, enum=State, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, diff --git a/google/cloud/vision_v1/types/product_search.py b/google/cloud/vision_v1/types/product_search.py index a2aa375b..425de883 100644 --- a/google/cloud/vision_v1/types/product_search.py +++ b/google/cloud/vision_v1/types/product_search.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1.types import geometry @@ -44,7 +46,7 @@ class ProductSearchParams(proto.Message): Format is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. - product_categories (Sequence[str]): + product_categories (MutableSequence[str]): The list of product categories to search in. Currently, we only consider the first category, and either "homegoods-v2", "apparel-v2", @@ -70,20 +72,20 @@ class ProductSearchParams(proto.Message): instead of an '='. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=9, message=geometry.BoundingPoly, ) - product_set = proto.Field( + product_set: str = proto.Field( proto.STRING, number=6, ) - product_categories = proto.RepeatedField( + product_categories: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=7, ) - filter = proto.Field( + filter: str = proto.Field( proto.STRING, number=8, ) @@ -98,9 +100,9 @@ class ProductSearchResults(proto.Message): results. Products added to the product set and products removed from the product set after this time are not reflected in the current results. - results (Sequence[google.cloud.vision_v1.types.ProductSearchResults.Result]): + results (MutableSequence[google.cloud.vision_v1.types.ProductSearchResults.Result]): List of results, one for each product match. - product_grouped_results (Sequence[google.cloud.vision_v1.types.ProductSearchResults.GroupedResult]): + product_grouped_results (MutableSequence[google.cloud.vision_v1.types.ProductSearchResults.GroupedResult]): List of results grouped by products detected in the query image. Each entry corresponds to one bounding polygon in the query image, and @@ -123,16 +125,16 @@ class Result(proto.Message): product that is the closest match to the query. """ - product = proto.Field( + product: product_search_service.Product = proto.Field( proto.MESSAGE, number=1, message=product_search_service.Product, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - image = proto.Field( + image: str = proto.Field( proto.STRING, number=3, ) @@ -154,19 +156,19 @@ class ObjectAnnotation(proto.Message): Score of the result. Range [0, 1]. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) @@ -179,40 +181,42 @@ class GroupedResult(proto.Message): bounding_poly (google.cloud.vision_v1.types.BoundingPoly): The bounding polygon around the product detected in the query image. - results (Sequence[google.cloud.vision_v1.types.ProductSearchResults.Result]): + results (MutableSequence[google.cloud.vision_v1.types.ProductSearchResults.Result]): List of results, one for each product match. - object_annotations (Sequence[google.cloud.vision_v1.types.ProductSearchResults.ObjectAnnotation]): + object_annotations (MutableSequence[google.cloud.vision_v1.types.ProductSearchResults.ObjectAnnotation]): List of generic predictions for the object in the bounding box. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - results = proto.RepeatedField( + results: MutableSequence["ProductSearchResults.Result"] = proto.RepeatedField( proto.MESSAGE, number=2, message="ProductSearchResults.Result", ) - object_annotations = proto.RepeatedField( + object_annotations: MutableSequence[ + "ProductSearchResults.ObjectAnnotation" + ] = proto.RepeatedField( proto.MESSAGE, number=3, message="ProductSearchResults.ObjectAnnotation", ) - index_time = proto.Field( + index_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - results = proto.RepeatedField( + results: MutableSequence[Result] = proto.RepeatedField( proto.MESSAGE, number=5, message=Result, ) - product_grouped_results = proto.RepeatedField( + product_grouped_results: MutableSequence[GroupedResult] = proto.RepeatedField( proto.MESSAGE, number=6, message=GroupedResult, diff --git a/google/cloud/vision_v1/types/product_search_service.py b/google/cloud/vision_v1/types/product_search_service.py index 3825f723..3b91b3e7 100644 --- a/google/cloud/vision_v1/types/product_search_service.py +++ b/google/cloud/vision_v1/types/product_search_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1.types import geometry @@ -85,7 +87,7 @@ class Product(proto.Message): The legacy categories "homegoods", "apparel", and "toys" are still supported, but these should not be used for new products. - product_labels (Sequence[google.cloud.vision_v1.types.Product.KeyValue]): + product_labels (MutableSequence[google.cloud.vision_v1.types.Product.KeyValue]): Key-value pairs that can be attached to a product. At query time, constraints can be specified based on the product_labels. @@ -116,32 +118,32 @@ class KeyValue(proto.Message): bytes. """ - key = proto.Field( + key: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - display_name = proto.Field( + display_name: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - product_category = proto.Field( + product_category: str = proto.Field( proto.STRING, number=4, ) - product_labels = proto.RepeatedField( + product_labels: MutableSequence[KeyValue] = proto.RepeatedField( proto.MESSAGE, number=5, message=KeyValue, @@ -183,20 +185,20 @@ class ProductSet(proto.Message): ProductSet. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - display_name = proto.Field( + display_name: str = proto.Field( proto.STRING, number=2, ) - index_time = proto.Field( + index_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - index_error = proto.Field( + index_error: status_pb2.Status = proto.Field( proto.MESSAGE, number=4, message=status_pb2.Status, @@ -220,7 +222,7 @@ class ReferenceImage(proto.Message): image. The URI must start with ``gs://``. - bounding_polys (Sequence[google.cloud.vision_v1.types.BoundingPoly]): + bounding_polys (MutableSequence[google.cloud.vision_v1.types.BoundingPoly]): Optional. Bounding polygons around the areas of interest in the reference image. If this field is empty, the system will try to detect @@ -233,15 +235,15 @@ class ReferenceImage(proto.Message): 1:4 or less (i.e. 1:3 is ok; 1:5 is not). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=2, ) - bounding_polys = proto.RepeatedField( + bounding_polys: MutableSequence[geometry.BoundingPoly] = proto.RepeatedField( proto.MESSAGE, number=3, message=geometry.BoundingPoly, @@ -267,16 +269,16 @@ class CreateProductRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: "Product" = proto.Field( proto.MESSAGE, number=2, message="Product", ) - product_id = proto.Field( + product_id: str = proto.Field( proto.STRING, number=3, ) @@ -299,15 +301,15 @@ class ListProductsRequest(proto.Message): if any. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -317,7 +319,7 @@ class ListProductsResponse(proto.Message): r"""Response message for the ``ListProducts`` method. Attributes: - products (Sequence[google.cloud.vision_v1.types.Product]): + products (MutableSequence[google.cloud.vision_v1.types.Product]): List of products. next_page_token (str): Token to retrieve the next page of results, @@ -329,12 +331,12 @@ class ListProductsResponse(proto.Message): def raw_page(self): return self - products = proto.RepeatedField( + products: MutableSequence["Product"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Product", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -351,7 +353,7 @@ class GetProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -372,12 +374,12 @@ class UpdateProductRequest(proto.Message): ``product_labels``, ``display_name``, and ``description``. """ - product = proto.Field( + product: "Product" = proto.Field( proto.MESSAGE, number=1, message="Product", ) - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, @@ -395,7 +397,7 @@ class DeleteProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -420,16 +422,16 @@ class CreateProductSetRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - product_set = proto.Field( + product_set: "ProductSet" = proto.Field( proto.MESSAGE, number=2, message="ProductSet", ) - product_set_id = proto.Field( + product_set_id: str = proto.Field( proto.STRING, number=3, ) @@ -452,15 +454,15 @@ class ListProductSetsRequest(proto.Message): if any. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -470,7 +472,7 @@ class ListProductSetsResponse(proto.Message): r"""Response message for the ``ListProductSets`` method. Attributes: - product_sets (Sequence[google.cloud.vision_v1.types.ProductSet]): + product_sets (MutableSequence[google.cloud.vision_v1.types.ProductSet]): List of ProductSets. next_page_token (str): Token to retrieve the next page of results, @@ -482,12 +484,12 @@ class ListProductSetsResponse(proto.Message): def raw_page(self): return self - product_sets = proto.RepeatedField( + product_sets: MutableSequence["ProductSet"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ProductSet", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -504,7 +506,7 @@ class GetProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -524,12 +526,12 @@ class UpdateProductSetRequest(proto.Message): ``display_name``. """ - product_set = proto.Field( + product_set: "ProductSet" = proto.Field( proto.MESSAGE, number=1, message="ProductSet", ) - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, @@ -547,7 +549,7 @@ class DeleteProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -574,16 +576,16 @@ class CreateReferenceImageRequest(proto.Message): characters long. It cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - reference_image = proto.Field( + reference_image: "ReferenceImage" = proto.Field( proto.MESSAGE, number=2, message="ReferenceImage", ) - reference_image_id = proto.Field( + reference_image_id: str = proto.Field( proto.STRING, number=3, ) @@ -610,15 +612,15 @@ class ListReferenceImagesRequest(proto.Message): Defaults to the first page if not specified. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -628,7 +630,7 @@ class ListReferenceImagesResponse(proto.Message): r"""Response message for the ``ListReferenceImages`` method. Attributes: - reference_images (Sequence[google.cloud.vision_v1.types.ReferenceImage]): + reference_images (MutableSequence[google.cloud.vision_v1.types.ReferenceImage]): The list of reference images. page_size (int): The maximum number of items to return. @@ -642,16 +644,16 @@ class ListReferenceImagesResponse(proto.Message): def raw_page(self): return self - reference_images = proto.RepeatedField( + reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=3, ) @@ -668,7 +670,7 @@ class GetReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -686,7 +688,7 @@ class DeleteReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -709,11 +711,11 @@ class AddProductToProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: str = proto.Field( proto.STRING, number=2, ) @@ -736,11 +738,11 @@ class RemoveProductFromProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: str = proto.Field( proto.STRING, number=2, ) @@ -764,15 +766,15 @@ class ListProductsInProductSetRequest(proto.Message): if any. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -782,7 +784,7 @@ class ListProductsInProductSetResponse(proto.Message): r"""Response message for the ``ListProductsInProductSet`` method. Attributes: - products (Sequence[google.cloud.vision_v1.types.Product]): + products (MutableSequence[google.cloud.vision_v1.types.Product]): The list of Products. next_page_token (str): Token to retrieve the next page of results, @@ -794,12 +796,12 @@ class ListProductsInProductSetResponse(proto.Message): def raw_page(self): return self - products = proto.RepeatedField( + products: MutableSequence["Product"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Product", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -886,7 +888,7 @@ class ImportProductSetsGcsSource(proto.Message): too large to process (larger than 20MP). """ - csv_file_uri = proto.Field( + csv_file_uri: str = proto.Field( proto.STRING, number=1, ) @@ -906,7 +908,7 @@ class ImportProductSetsInputConfig(proto.Message): This field is a member of `oneof`_ ``source``. """ - gcs_source = proto.Field( + gcs_source: "ImportProductSetsGcsSource" = proto.Field( proto.MESSAGE, number=1, oneof="source", @@ -928,11 +930,11 @@ class ImportProductSetsRequest(proto.Message): requests. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - input_config = proto.Field( + input_config: "ImportProductSetsInputConfig" = proto.Field( proto.MESSAGE, number=2, message="ImportProductSetsInputConfig", @@ -949,9 +951,9 @@ class ImportProductSetsResponse(proto.Message): field. Attributes: - reference_images (Sequence[google.cloud.vision_v1.types.ReferenceImage]): + reference_images (MutableSequence[google.cloud.vision_v1.types.ReferenceImage]): The list of reference_images that are imported successfully. - statuses (Sequence[google.rpc.status_pb2.Status]): + statuses (MutableSequence[google.rpc.status_pb2.Status]): The rpc status for each ImportProductSet request, including both successes and errors. @@ -961,12 +963,12 @@ class ImportProductSetsResponse(proto.Message): line 0. """ - reference_images = proto.RepeatedField( + reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - statuses = proto.RepeatedField( + statuses: MutableSequence[status_pb2.Status] = proto.RepeatedField( proto.MESSAGE, number=2, message=status_pb2.Status, @@ -1002,17 +1004,17 @@ class State(proto.Enum): FAILED = 3 CANCELLED = 4 - state = proto.Field( + state: State = proto.Field( proto.ENUM, number=1, enum=State, ) - submit_time = proto.Field( + submit_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - end_time = proto.Field( + end_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, @@ -1030,7 +1032,7 @@ class ProductSetPurgeConfig(proto.Message): ProductSets, the Product will still be deleted. """ - product_set_id = proto.Field( + product_set_id: str = proto.Field( proto.STRING, number=1, ) @@ -1067,22 +1069,22 @@ class PurgeProductsRequest(proto.Message): value to true to actually perform the purge. """ - product_set_purge_config = proto.Field( + product_set_purge_config: "ProductSetPurgeConfig" = proto.Field( proto.MESSAGE, number=2, oneof="target", message="ProductSetPurgeConfig", ) - delete_orphan_products = proto.Field( + delete_orphan_products: bool = proto.Field( proto.BOOL, number=3, oneof="target", ) - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - force = proto.Field( + force: bool = proto.Field( proto.BOOL, number=4, ) diff --git a/google/cloud/vision_v1/types/text_annotation.py b/google/cloud/vision_v1/types/text_annotation.py index 9d56f34d..2298ad0b 100644 --- a/google/cloud/vision_v1/types/text_annotation.py +++ b/google/cloud/vision_v1/types/text_annotation.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1.types import geometry @@ -42,7 +44,7 @@ class TextAnnotation(proto.Message): message definition below for more detail. Attributes: - pages (Sequence[google.cloud.vision_v1.types.Page]): + pages (MutableSequence[google.cloud.vision_v1.types.Page]): List of pages detected by OCR. text (str): UTF-8 text detected on the pages. @@ -60,11 +62,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=1, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) @@ -88,12 +90,12 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_ = proto.Field( + type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - is_prefix = proto.Field( + is_prefix: bool = proto.Field( proto.BOOL, number=2, ) @@ -102,30 +104,32 @@ class TextProperty(proto.Message): r"""Additional information detected on the structural component. Attributes: - detected_languages (Sequence[google.cloud.vision_v1.types.TextAnnotation.DetectedLanguage]): + detected_languages (MutableSequence[google.cloud.vision_v1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with confidence. detected_break (google.cloud.vision_v1.types.TextAnnotation.DetectedBreak): Detected start or end of a text segment. """ - detected_languages = proto.RepeatedField( + detected_languages: MutableSequence[ + "TextAnnotation.DetectedLanguage" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", ) - detected_break = proto.Field( + detected_break: "TextAnnotation.DetectedBreak" = proto.Field( proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", ) - pages = proto.RepeatedField( + pages: MutableSequence["Page"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Page", ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=2, ) @@ -143,32 +147,32 @@ class Page(proto.Message): height (int): Page height. For PDFs the unit is points. For images (including TIFFs) the unit is pixels. - blocks (Sequence[google.cloud.vision_v1.types.Block]): + blocks (MutableSequence[google.cloud.vision_v1.types.Block]): List of blocks of text, images etc on this page. confidence (float): Confidence of the OCR results on the page. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - width = proto.Field( + width: int = proto.Field( proto.INT32, number=2, ) - height = proto.Field( + height: int = proto.Field( proto.INT32, number=3, ) - blocks = proto.RepeatedField( + blocks: MutableSequence["Block"] = proto.RepeatedField( proto.MESSAGE, number=4, message="Block", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -206,7 +210,7 @@ class Block(proto.Message): 1----0 and the vertex order will still be (0, 1, 2, 3). - paragraphs (Sequence[google.cloud.vision_v1.types.Paragraph]): + paragraphs (MutableSequence[google.cloud.vision_v1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). block_type (google.cloud.vision_v1.types.Block.BlockType): @@ -225,27 +229,27 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs = proto.RepeatedField( + paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Paragraph", ) - block_type = proto.Field( + block_type: BlockType = proto.Field( proto.ENUM, number=4, enum=BlockType, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -271,29 +275,29 @@ class Paragraph(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertex order will still be (0, 1, 2, 3). - words (Sequence[google.cloud.vision_v1.types.Word]): + words (MutableSequence[google.cloud.vision_v1.types.Word]): List of all words in this paragraph. confidence (float): Confidence of the OCR results for the paragraph. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words = proto.RepeatedField( + words: MutableSequence["Word"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Word", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -317,7 +321,7 @@ class Word(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertex order will still be (0, 1, 2, 3). - symbols (Sequence[google.cloud.vision_v1.types.Symbol]): + symbols (MutableSequence[google.cloud.vision_v1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural reading order. @@ -325,22 +329,22 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols = proto.RepeatedField( + symbols: MutableSequence["Symbol"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Symbol", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -372,21 +376,21 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=3, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) diff --git a/google/cloud/vision_v1/types/web_detection.py b/google/cloud/vision_v1/types/web_detection.py index 0c8acb91..83e72d60 100644 --- a/google/cloud/vision_v1/types/web_detection.py +++ b/google/cloud/vision_v1/types/web_detection.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -28,24 +30,24 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. Attributes: - web_entities (Sequence[google.cloud.vision_v1.types.WebDetection.WebEntity]): + web_entities (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebEntity]): Deduced entities from similar images on the Internet. - full_matching_images (Sequence[google.cloud.vision_v1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebImage]): Fully matching images from the Internet. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebImage]): Partial matching images from the Internet. Those images are similar enough to share some key-point features. For example an original image will likely have partial matching for its crops. - pages_with_matching_images (Sequence[google.cloud.vision_v1.types.WebDetection.WebPage]): + pages_with_matching_images (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebPage]): Web pages containing the matching images from the Internet. - visually_similar_images (Sequence[google.cloud.vision_v1.types.WebDetection.WebImage]): + visually_similar_images (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebImage]): The visually similar image results. - best_guess_labels (Sequence[google.cloud.vision_v1.types.WebDetection.WebLabel]): + best_guess_labels (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebLabel]): The service's best guess as to the topic of the request image. Inferred from similar images on the open web. @@ -66,15 +68,15 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field( + entity_id: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) @@ -90,11 +92,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) @@ -111,10 +113,10 @@ class WebPage(proto.Message): page_title (str): Title for the web page, may contain HTML markups. - full_matching_images (Sequence[google.cloud.vision_v1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebImage]): Fully matching images on the page. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1.types.WebDetection.WebImage]): Partial matching images on the page. Those images are similar enough to share some key-point features. For example an original @@ -122,24 +124,28 @@ class WebPage(proto.Message): crops. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - page_title = proto.Field( + page_title: str = proto.Field( proto.STRING, number=3, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=4, message="WebDetection.WebImage", ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=5, message="WebDetection.WebImage", @@ -157,41 +163,41 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field( + label: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - web_entities = proto.RepeatedField( + web_entities: MutableSequence[WebEntity] = proto.RepeatedField( proto.MESSAGE, number=1, message=WebEntity, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=2, message=WebImage, ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=3, message=WebImage, ) - pages_with_matching_images = proto.RepeatedField( + pages_with_matching_images: MutableSequence[WebPage] = proto.RepeatedField( proto.MESSAGE, number=4, message=WebPage, ) - visually_similar_images = proto.RepeatedField( + visually_similar_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=6, message=WebImage, ) - best_guess_labels = proto.RepeatedField( + best_guess_labels: MutableSequence[WebLabel] = proto.RepeatedField( proto.MESSAGE, number=8, message=WebLabel, diff --git a/google/cloud/vision_v1p1beta1/__init__.py b/google/cloud/vision_v1p1beta1/__init__.py index 757507fe..7821a449 100644 --- a/google/cloud/vision_v1p1beta1/__init__.py +++ b/google/cloud/vision_v1p1beta1/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.vision import gapic_version as package_version + +__version__ = package_version.__version__ + from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers diff --git a/google/cloud/vision_v1p1beta1/gapic_metadata.json b/google/cloud/vision_v1p1beta1/gapic_metadata.json new file mode 100644 index 00000000..b198d92f --- /dev/null +++ b/google/cloud/vision_v1p1beta1/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.vision_v1p1beta1", + "protoPackage": "google.cloud.vision.v1p1beta1", + "schema": "1.0", + "services": { + "ImageAnnotator": { + "clients": { + "grpc": { + "libraryClient": "ImageAnnotatorClient", + "rpcs": { + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ImageAnnotatorAsyncClient", + "rpcs": { + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + } + } + } + } +} diff --git a/samples/snippets/document_text/doctext_test.py b/google/cloud/vision_v1p1beta1/gapic_version.py similarity index 62% rename from samples/snippets/document_text/doctext_test.py rename to google/cloud/vision_v1p1beta1/gapic_version.py index cb881e31..47c54531 100644 --- a/samples/snippets/document_text/doctext_test.py +++ b/google/cloud/vision_v1p1beta1/gapic_version.py @@ -1,4 +1,5 @@ -# Copyright 2017 Google Inc. All Rights Reserved. +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,14 +12,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -import os - -import doctext - - -def test_text(capsys): - """Checks the output image for drawing the crop hint is created.""" - doctext.render_doc_text('resources/text_menu.jpg', 'output-text.jpg') - out, _ = capsys.readouterr() - assert os.path.isfile('output-text.jpg') +# +__version__ = "3.2.0" # {x-release-please-version} diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py index 9d0ef92a..3ce5fe58 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1p1beta1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -159,9 +170,9 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -205,11 +216,15 @@ def __init__( async def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -241,10 +256,10 @@ async def sample_batch_annotate_images(): print(response) Args: - request (Union[google.cloud.vision_v1p1beta1.types.BatchAnnotateImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p1beta1.types.BatchAnnotateImagesRequest, dict]]): The request object. Multiple image annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]`): Required. Individual image annotation requests for this batch. @@ -316,14 +331,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/client.py b/google/cloud/vision_v1p1beta1/services/image_annotator/client.py index bc54a51b..0f227861 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1p1beta1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -56,7 +68,7 @@ class ImageAnnotatorClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. @@ -313,8 +325,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageAnnotatorTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ImageAnnotatorTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -328,7 +340,7 @@ def __init__( transport (Union[str, ImageAnnotatorTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -358,6 +370,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -410,11 +423,15 @@ def __init__( def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -449,7 +466,7 @@ def sample_batch_annotate_images(): request (Union[google.cloud.vision_v1p1beta1.types.BatchAnnotateImagesRequest, dict]): The request object. Multiple image annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. @@ -521,14 +538,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py index 423fd104..7704ea53 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1p1beta1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -27,14 +28,9 @@ from google.cloud.vision_v1p1beta1.types import image_annotator -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ImageAnnotatorTransport(abc.ABC): @@ -51,7 +47,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py index 3b7aa307..6e2c7349 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py @@ -50,14 +50,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -184,8 +184,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py index b8c5a7e7..31910a34 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py @@ -52,7 +52,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -95,15 +95,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1p1beta1/types/geometry.py b/google/cloud/vision_v1p1beta1/types/geometry.py index ecb4d164..235d97d1 100644 --- a/google/cloud/vision_v1p1beta1/types/geometry.py +++ b/google/cloud/vision_v1p1beta1/types/geometry.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -38,11 +40,11 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: int = proto.Field( proto.INT32, number=1, ) - y = proto.Field( + y: int = proto.Field( proto.INT32, number=2, ) @@ -52,11 +54,11 @@ class BoundingPoly(proto.Message): r"""A bounding polygon for the detected image annotation. Attributes: - vertices (Sequence[google.cloud.vision_v1p1beta1.types.Vertex]): + vertices (MutableSequence[google.cloud.vision_v1p1beta1.types.Vertex]): The bounding polygon vertices. """ - vertices = proto.RepeatedField( + vertices: MutableSequence["Vertex"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Vertex", @@ -78,15 +80,15 @@ class Position(proto.Message): Z coordinate (or depth). """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) - z = proto.Field( + z: float = proto.Field( proto.FLOAT, number=3, ) diff --git a/google/cloud/vision_v1p1beta1/types/image_annotator.py b/google/cloud/vision_v1p1beta1/types/image_annotator.py index 2633fac1..c2d0d464 100644 --- a/google/cloud/vision_v1p1beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p1beta1/types/image_annotator.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p1beta1.types import geometry @@ -99,16 +101,16 @@ class Type(proto.Enum): CROP_HINTS = 9 WEB_DETECTION = 10 - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=1, enum=Type, ) - max_results = proto.Field( + max_results: int = proto.Field( proto.INT32, number=2, ) - model = proto.Field( + model: str = proto.Field( proto.STRING, number=3, ) @@ -139,11 +141,11 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field( + gcs_image_uri: str = proto.Field( proto.STRING, number=1, ) - image_uri = proto.Field( + image_uri: str = proto.Field( proto.STRING, number=2, ) @@ -164,11 +166,11 @@ class Image(proto.Message): request. """ - content = proto.Field( + content: bytes = proto.Field( proto.BYTES, number=1, ) - source = proto.Field( + source: "ImageSource" = proto.Field( proto.MESSAGE, number=2, message="ImageSource", @@ -197,7 +199,7 @@ class FaceAnnotation(proto.Message): an image. It is not based on the landmarker results, only on the initial face detection, hence the fd (face detection) prefix. - landmarks (Sequence[google.cloud.vision_v1p1beta1.types.FaceAnnotation.Landmark]): + landmarks (MutableSequence[google.cloud.vision_v1p1beta1.types.FaceAnnotation.Landmark]): Detected face landmarks. roll_angle (float): Roll angle, which indicates the amount of @@ -284,83 +286,83 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_ = proto.Field( + type_: "FaceAnnotation.Landmark.Type" = proto.Field( proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type", ) - position = proto.Field( + position: geometry.Position = proto.Field( proto.MESSAGE, number=4, message=geometry.Position, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - fd_bounding_poly = proto.Field( + fd_bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - landmarks = proto.RepeatedField( + landmarks: MutableSequence[Landmark] = proto.RepeatedField( proto.MESSAGE, number=3, message=Landmark, ) - roll_angle = proto.Field( + roll_angle: float = proto.Field( proto.FLOAT, number=4, ) - pan_angle = proto.Field( + pan_angle: float = proto.Field( proto.FLOAT, number=5, ) - tilt_angle = proto.Field( + tilt_angle: float = proto.Field( proto.FLOAT, number=6, ) - detection_confidence = proto.Field( + detection_confidence: float = proto.Field( proto.FLOAT, number=7, ) - landmarking_confidence = proto.Field( + landmarking_confidence: float = proto.Field( proto.FLOAT, number=8, ) - joy_likelihood = proto.Field( + joy_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", ) - sorrow_likelihood = proto.Field( + sorrow_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=10, enum="Likelihood", ) - anger_likelihood = proto.Field( + anger_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=11, enum="Likelihood", ) - surprise_likelihood = proto.Field( + surprise_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=12, enum="Likelihood", ) - under_exposed_likelihood = proto.Field( + under_exposed_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=13, enum="Likelihood", ) - blurred_likelihood = proto.Field( + blurred_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=14, enum="Likelihood", ) - headwear_likelihood = proto.Field( + headwear_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=15, enum="Likelihood", @@ -375,7 +377,7 @@ class LocationInfo(proto.Message): lat/long location coordinates. """ - lat_lng = proto.Field( + lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, @@ -394,15 +396,15 @@ class Property(proto.Message): Value of numeric properties. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - uint64_value = proto.Field( + uint64_value: int = proto.Field( proto.UINT64, number=3, ) @@ -439,54 +441,54 @@ class EntityAnnotation(proto.Message): bounding_poly (google.cloud.vision_v1p1beta1.types.BoundingPoly): Image region to which this entity belongs. Not produced for ``LABEL_DETECTION`` features. - locations (Sequence[google.cloud.vision_v1p1beta1.types.LocationInfo]): + locations (MutableSequence[google.cloud.vision_v1p1beta1.types.LocationInfo]): The location information for the detected entity. Multiple ``LocationInfo`` elements can be present because one location may indicate the location of the scene in the image, and another location may indicate the location of the place where the image was taken. Location information is usually present for landmarks. - properties (Sequence[google.cloud.vision_v1p1beta1.types.Property]): + properties (MutableSequence[google.cloud.vision_v1p1beta1.types.Property]): Some entities may have optional user-supplied ``Property`` (name/value) fields, such a score or string that qualifies the entity. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - locale = proto.Field( + locale: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) - topicality = proto.Field( + topicality: float = proto.Field( proto.FLOAT, number=6, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=7, message=geometry.BoundingPoly, ) - locations = proto.RepeatedField( + locations: MutableSequence["LocationInfo"] = proto.RepeatedField( proto.MESSAGE, number=8, message="LocationInfo", ) - properties = proto.RepeatedField( + properties: MutableSequence["Property"] = proto.RepeatedField( proto.MESSAGE, number=9, message="Property", @@ -522,27 +524,27 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult = proto.Field( + adult: "Likelihood" = proto.Field( proto.ENUM, number=1, enum="Likelihood", ) - spoof = proto.Field( + spoof: "Likelihood" = proto.Field( proto.ENUM, number=2, enum="Likelihood", ) - medical = proto.Field( + medical: "Likelihood" = proto.Field( proto.ENUM, number=3, enum="Likelihood", ) - violence = proto.Field( + violence: "Likelihood" = proto.Field( proto.ENUM, number=4, enum="Likelihood", ) - racy = proto.Field( + racy: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", @@ -559,12 +561,12 @@ class LatLongRect(proto.Message): Max lat/long pair. """ - min_lat_lng = proto.Field( + min_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, ) - max_lat_lng = proto.Field( + max_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=2, message=latlng_pb2.LatLng, @@ -585,16 +587,16 @@ class ColorInfo(proto.Message): Value in range [0, 1]. """ - color = proto.Field( + color: color_pb2.Color = proto.Field( proto.MESSAGE, number=1, message=color_pb2.Color, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - pixel_fraction = proto.Field( + pixel_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -604,12 +606,12 @@ class DominantColorsAnnotation(proto.Message): r"""Set of dominant colors and their corresponding scores. Attributes: - colors (Sequence[google.cloud.vision_v1p1beta1.types.ColorInfo]): + colors (MutableSequence[google.cloud.vision_v1p1beta1.types.ColorInfo]): RGB color values with their score and pixel fraction. """ - colors = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ColorInfo", @@ -625,7 +627,7 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, message="DominantColorsAnnotation", @@ -648,16 +650,16 @@ class CropHint(proto.Message): with respect to the original image. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) - importance_fraction = proto.Field( + importance_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -668,11 +670,11 @@ class CropHintsAnnotation(proto.Message): serving images. Attributes: - crop_hints (Sequence[google.cloud.vision_v1p1beta1.types.CropHint]): + crop_hints (MutableSequence[google.cloud.vision_v1p1beta1.types.CropHint]): Crop hint results. """ - crop_hints = proto.RepeatedField( + crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( proto.MESSAGE, number=1, message="CropHint", @@ -683,7 +685,7 @@ class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. Attributes: - aspect_ratios (Sequence[float]): + aspect_ratios (MutableSequence[float]): Aspect ratios in floats, representing the ratio of the width to the height of the image. For example, if the desired aspect ratio is 4/3, @@ -694,7 +696,7 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField( + aspect_ratios: MutableSequence[float] = proto.RepeatedField( proto.FLOAT, number=1, ) @@ -709,7 +711,7 @@ class WebDetectionParams(proto.Message): geo information in the image. """ - include_geo_results = proto.Field( + include_geo_results: bool = proto.Field( proto.BOOL, number=2, ) @@ -724,16 +726,16 @@ class TextDetectionParams(proto.Message): By default, Cloud Vision API only includes confidence score for DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence score for TEXT_DETECTION as well. - advanced_ocr_options (Sequence[str]): + advanced_ocr_options (MutableSequence[str]): A list of advanced OCR options to fine-tune OCR behavior. """ - enable_text_detection_confidence_score = proto.Field( + enable_text_detection_confidence_score: bool = proto.Field( proto.BOOL, number=9, ) - advanced_ocr_options = proto.RepeatedField( + advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=11, ) @@ -746,7 +748,7 @@ class ImageContext(proto.Message): lat_long_rect (google.cloud.vision_v1p1beta1.types.LatLongRect): lat/long rectangle that specifies the location of the image. - language_hints (Sequence[str]): + language_hints (MutableSequence[str]): List of languages to use for TEXT_DETECTION. In most cases, an empty value yields the best results since it enables automatic language detection. For languages based on the @@ -766,26 +768,26 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect = proto.Field( + lat_long_rect: "LatLongRect" = proto.Field( proto.MESSAGE, number=1, message="LatLongRect", ) - language_hints = proto.RepeatedField( + language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params = proto.Field( + crop_hints_params: "CropHintsParams" = proto.Field( proto.MESSAGE, number=4, message="CropHintsParams", ) - web_detection_params = proto.Field( + web_detection_params: "WebDetectionParams" = proto.Field( proto.MESSAGE, number=6, message="WebDetectionParams", ) - text_detection_params = proto.Field( + text_detection_params: "TextDetectionParams" = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", @@ -799,24 +801,24 @@ class AnnotateImageRequest(proto.Message): Attributes: image (google.cloud.vision_v1p1beta1.types.Image): The image to be processed. - features (Sequence[google.cloud.vision_v1p1beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p1beta1.types.Feature]): Requested features. image_context (google.cloud.vision_v1p1beta1.types.ImageContext): Additional context that may accompany the image. """ - image = proto.Field( + image: "Image" = proto.Field( proto.MESSAGE, number=1, message="Image", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", @@ -827,19 +829,19 @@ class AnnotateImageResponse(proto.Message): r"""Response to an image annotation request. Attributes: - face_annotations (Sequence[google.cloud.vision_v1p1beta1.types.FaceAnnotation]): + face_annotations (MutableSequence[google.cloud.vision_v1p1beta1.types.FaceAnnotation]): If present, face detection has completed successfully. - landmark_annotations (Sequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): + landmark_annotations (MutableSequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): If present, landmark detection has completed successfully. - logo_annotations (Sequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): + logo_annotations (MutableSequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): If present, logo detection has completed successfully. - label_annotations (Sequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): + label_annotations (MutableSequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): If present, label detection has completed successfully. - text_annotations (Sequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): + text_annotations (MutableSequence[google.cloud.vision_v1p1beta1.types.EntityAnnotation]): If present, text (OCR) detection has completed successfully. full_text_annotation (google.cloud.vision_v1p1beta1.types.TextAnnotation): @@ -865,57 +867,57 @@ class AnnotateImageResponse(proto.Message): correct, even when ``error`` is set. """ - face_annotations = proto.RepeatedField( + face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FaceAnnotation", ) - landmark_annotations = proto.RepeatedField( + landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityAnnotation", ) - logo_annotations = proto.RepeatedField( + logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=3, message="EntityAnnotation", ) - label_annotations = proto.RepeatedField( + label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=4, message="EntityAnnotation", ) - text_annotations = proto.RepeatedField( + text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=5, message="EntityAnnotation", ) - full_text_annotation = proto.Field( + full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation = proto.Field( + safe_search_annotation: "SafeSearchAnnotation" = proto.Field( proto.MESSAGE, number=6, message="SafeSearchAnnotation", ) - image_properties_annotation = proto.Field( + image_properties_annotation: "ImageProperties" = proto.Field( proto.MESSAGE, number=8, message="ImageProperties", ) - crop_hints_annotation = proto.Field( + crop_hints_annotation: "CropHintsAnnotation" = proto.Field( proto.MESSAGE, number=11, message="CropHintsAnnotation", ) - web_detection = proto.Field( + web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, ) - error = proto.Field( + error: status_pb2.Status = proto.Field( proto.MESSAGE, number=9, message=status_pb2.Status, @@ -927,12 +929,12 @@ class BatchAnnotateImagesRequest(proto.Message): service call. Attributes: - requests (Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", @@ -943,12 +945,12 @@ class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1p1beta1.types.AnnotateImageResponse]): Individual responses to image annotation requests within the batch. """ - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageResponse", diff --git a/google/cloud/vision_v1p1beta1/types/text_annotation.py b/google/cloud/vision_v1p1beta1/types/text_annotation.py index 2680638a..2b307133 100644 --- a/google/cloud/vision_v1p1beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p1beta1/types/text_annotation.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p1beta1.types import geometry @@ -42,7 +44,7 @@ class TextAnnotation(proto.Message): message definition below for more detail. Attributes: - pages (Sequence[google.cloud.vision_v1p1beta1.types.Page]): + pages (MutableSequence[google.cloud.vision_v1p1beta1.types.Page]): List of pages detected by OCR. text (str): UTF-8 text detected on the pages. @@ -60,11 +62,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=1, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) @@ -88,12 +90,12 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_ = proto.Field( + type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - is_prefix = proto.Field( + is_prefix: bool = proto.Field( proto.BOOL, number=2, ) @@ -102,30 +104,32 @@ class TextProperty(proto.Message): r"""Additional information detected on the structural component. Attributes: - detected_languages (Sequence[google.cloud.vision_v1p1beta1.types.TextAnnotation.DetectedLanguage]): + detected_languages (MutableSequence[google.cloud.vision_v1p1beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with confidence. detected_break (google.cloud.vision_v1p1beta1.types.TextAnnotation.DetectedBreak): Detected start or end of a text segment. """ - detected_languages = proto.RepeatedField( + detected_languages: MutableSequence[ + "TextAnnotation.DetectedLanguage" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", ) - detected_break = proto.Field( + detected_break: "TextAnnotation.DetectedBreak" = proto.Field( proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", ) - pages = proto.RepeatedField( + pages: MutableSequence["Page"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Page", ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=2, ) @@ -141,32 +145,32 @@ class Page(proto.Message): Page width in pixels. height (int): Page height in pixels. - blocks (Sequence[google.cloud.vision_v1p1beta1.types.Block]): + blocks (MutableSequence[google.cloud.vision_v1p1beta1.types.Block]): List of blocks of text, images etc on this page. confidence (float): Confidence of the OCR results on the page. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - width = proto.Field( + width: int = proto.Field( proto.INT32, number=2, ) - height = proto.Field( + height: int = proto.Field( proto.INT32, number=3, ) - blocks = proto.RepeatedField( + blocks: MutableSequence["Block"] = proto.RepeatedField( proto.MESSAGE, number=4, message="Block", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -191,7 +195,7 @@ class Block(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). - paragraphs (Sequence[google.cloud.vision_v1p1beta1.types.Paragraph]): + paragraphs (MutableSequence[google.cloud.vision_v1p1beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). block_type (google.cloud.vision_v1p1beta1.types.Block.BlockType): @@ -210,27 +214,27 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs = proto.RepeatedField( + paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Paragraph", ) - block_type = proto.Field( + block_type: BlockType = proto.Field( proto.ENUM, number=4, enum=BlockType, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -256,29 +260,29 @@ class Paragraph(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). - words (Sequence[google.cloud.vision_v1p1beta1.types.Word]): + words (MutableSequence[google.cloud.vision_v1p1beta1.types.Word]): List of words in this paragraph. confidence (float): Confidence of the OCR results for the paragraph. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words = proto.RepeatedField( + words: MutableSequence["Word"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Word", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -302,7 +306,7 @@ class Word(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). - symbols (Sequence[google.cloud.vision_v1p1beta1.types.Symbol]): + symbols (MutableSequence[google.cloud.vision_v1p1beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural reading order. @@ -310,22 +314,22 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols = proto.RepeatedField( + symbols: MutableSequence["Symbol"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Symbol", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -357,21 +361,21 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=3, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) diff --git a/google/cloud/vision_v1p1beta1/types/web_detection.py b/google/cloud/vision_v1p1beta1/types/web_detection.py index c07b563a..8602736b 100644 --- a/google/cloud/vision_v1p1beta1/types/web_detection.py +++ b/google/cloud/vision_v1p1beta1/types/web_detection.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -28,24 +30,24 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. Attributes: - web_entities (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebEntity]): + web_entities (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the Internet. - full_matching_images (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): Fully matching images from the Internet. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): Partial matching images from the Internet. Those images are similar enough to share some key-point features. For example an original image will likely have partial matching for its crops. - pages_with_matching_images (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebPage]): + pages_with_matching_images (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebPage]): Web pages containing the matching images from the Internet. - visually_similar_images (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): + visually_similar_images (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): The visually similar image results. - best_guess_labels (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebLabel]): + best_guess_labels (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebLabel]): Best guess text labels for the request image. """ @@ -64,15 +66,15 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field( + entity_id: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) @@ -88,11 +90,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) @@ -109,10 +111,10 @@ class WebPage(proto.Message): page_title (str): Title for the web page, may contain HTML markups. - full_matching_images (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): Fully matching images on the page. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebImage]): Partial matching images on the page. Those images are similar enough to share some key-point features. For example an original @@ -120,24 +122,28 @@ class WebPage(proto.Message): crops. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - page_title = proto.Field( + page_title: str = proto.Field( proto.STRING, number=3, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=4, message="WebDetection.WebImage", ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=5, message="WebDetection.WebImage", @@ -155,41 +161,41 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field( + label: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - web_entities = proto.RepeatedField( + web_entities: MutableSequence[WebEntity] = proto.RepeatedField( proto.MESSAGE, number=1, message=WebEntity, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=2, message=WebImage, ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=3, message=WebImage, ) - pages_with_matching_images = proto.RepeatedField( + pages_with_matching_images: MutableSequence[WebPage] = proto.RepeatedField( proto.MESSAGE, number=4, message=WebPage, ) - visually_similar_images = proto.RepeatedField( + visually_similar_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=6, message=WebImage, ) - best_guess_labels = proto.RepeatedField( + best_guess_labels: MutableSequence[WebLabel] = proto.RepeatedField( proto.MESSAGE, number=8, message=WebLabel, diff --git a/google/cloud/vision_v1p2beta1/__init__.py b/google/cloud/vision_v1p2beta1/__init__.py index 2410b40f..2fd7224f 100644 --- a/google/cloud/vision_v1p2beta1/__init__.py +++ b/google/cloud/vision_v1p2beta1/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.vision import gapic_version as package_version + +__version__ = package_version.__version__ + from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers diff --git a/google/cloud/vision_v1p2beta1/gapic_metadata.json b/google/cloud/vision_v1p2beta1/gapic_metadata.json new file mode 100644 index 00000000..3e166a99 --- /dev/null +++ b/google/cloud/vision_v1p2beta1/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.vision_v1p2beta1", + "protoPackage": "google.cloud.vision.v1p2beta1", + "schema": "1.0", + "services": { + "ImageAnnotator": { + "clients": { + "grpc": { + "libraryClient": "ImageAnnotatorClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ImageAnnotatorAsyncClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + } + } + } + } +} diff --git a/samples/snippets/detect/vision_batch_annotate_files_test.py b/google/cloud/vision_v1p2beta1/gapic_version.py similarity index 56% rename from samples/snippets/detect/vision_batch_annotate_files_test.py rename to google/cloud/vision_v1p2beta1/gapic_version.py index db07c42f..47c54531 100644 --- a/samples/snippets/detect/vision_batch_annotate_files_test.py +++ b/google/cloud/vision_v1p2beta1/gapic_version.py @@ -1,4 +1,5 @@ -# Copyright 2020 Google +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,20 +12,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -import os - -import vision_batch_annotate_files - -RESOURCES = os.path.join(os.path.dirname(__file__), "resources") - - -def test_sample_batch_annotate_files(capsys): - file_path = os.path.join(RESOURCES, "kafka.pdf") - - vision_batch_annotate_files.sample_batch_annotate_files(file_path=file_path) - - out, _ = capsys.readouterr() - - assert "Full text" in out - assert "Block confidence" in out +# +__version__ = "3.2.0" # {x-release-please-version} diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py index 74840fa6..b7646c26 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1p2beta1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -161,9 +172,9 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -207,11 +218,15 @@ def __init__( async def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -243,10 +258,10 @@ async def sample_batch_annotate_images(): print(response) Args: - request (Union[google.cloud.vision_v1p2beta1.types.BatchAnnotateImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p2beta1.types.BatchAnnotateImagesRequest, dict]]): The request object. Multiple image annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]`): Required. Individual image annotation requests for this batch. @@ -313,11 +328,15 @@ async def sample_batch_annotate_images(): async def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Run async image detection and annotation for a list of generic @@ -352,16 +371,16 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1p2beta1.types.AsyncBatchAnnotateFilesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p2beta1.types.AsyncBatchAnnotateFilesRequest, dict]]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]`): Required. Individual async file annotation requests for this batch. @@ -444,14 +463,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/client.py b/google/cloud/vision_v1p2beta1/services/image_annotator/client.py index 89a69fa9..750685cc 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1p2beta1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -58,7 +70,7 @@ class ImageAnnotatorClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. @@ -315,8 +327,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageAnnotatorTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ImageAnnotatorTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -330,7 +342,7 @@ def __init__( transport (Union[str, ImageAnnotatorTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -360,6 +372,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -412,11 +425,15 @@ def __init__( def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -451,7 +468,7 @@ def sample_batch_annotate_images(): request (Union[google.cloud.vision_v1p2beta1.types.BatchAnnotateImagesRequest, dict]): The request object. Multiple image annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. @@ -511,11 +528,15 @@ def sample_batch_annotate_images(): def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Run async image detection and annotation for a list of generic @@ -559,7 +580,7 @@ def sample_async_batch_annotate_files(): request (Union[google.cloud.vision_v1p2beta1.types.AsyncBatchAnnotateFilesRequest, dict]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. @@ -644,14 +665,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py index 6de4782d..cf5ae0b1 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1p2beta1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -29,14 +30,9 @@ from google.cloud.vision_v1p2beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ImageAnnotatorTransport(abc.ABC): @@ -53,7 +49,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py index 88dee301..1635a9c7 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py @@ -52,14 +52,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -187,8 +187,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py index 6b4c566a..52806f46 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py @@ -54,7 +54,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -97,15 +97,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1p2beta1/types/geometry.py b/google/cloud/vision_v1p2beta1/types/geometry.py index 494de04e..f5343d4b 100644 --- a/google/cloud/vision_v1p2beta1/types/geometry.py +++ b/google/cloud/vision_v1p2beta1/types/geometry.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -39,11 +41,11 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: int = proto.Field( proto.INT32, number=1, ) - y = proto.Field( + y: int = proto.Field( proto.INT32, number=2, ) @@ -61,11 +63,11 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) @@ -75,18 +77,18 @@ class BoundingPoly(proto.Message): r"""A bounding polygon for the detected image annotation. Attributes: - vertices (Sequence[google.cloud.vision_v1p2beta1.types.Vertex]): + vertices (MutableSequence[google.cloud.vision_v1p2beta1.types.Vertex]): The bounding polygon vertices. - normalized_vertices (Sequence[google.cloud.vision_v1p2beta1.types.NormalizedVertex]): + normalized_vertices (MutableSequence[google.cloud.vision_v1p2beta1.types.NormalizedVertex]): The bounding polygon normalized vertices. """ - vertices = proto.RepeatedField( + vertices: MutableSequence["Vertex"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Vertex", ) - normalized_vertices = proto.RepeatedField( + normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", @@ -108,15 +110,15 @@ class Position(proto.Message): Z coordinate (or depth). """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) - z = proto.Field( + z: float = proto.Field( proto.FLOAT, number=3, ) diff --git a/google/cloud/vision_v1p2beta1/types/image_annotator.py b/google/cloud/vision_v1p2beta1/types/image_annotator.py index cea218d1..a0ca57ad 100644 --- a/google/cloud/vision_v1p2beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p2beta1/types/image_annotator.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p2beta1.types import geometry @@ -111,16 +113,16 @@ class Type(proto.Enum): CROP_HINTS = 9 WEB_DETECTION = 10 - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=1, enum=Type, ) - max_results = proto.Field( + max_results: int = proto.Field( proto.INT32, number=2, ) - model = proto.Field( + model: str = proto.Field( proto.STRING, number=3, ) @@ -161,11 +163,11 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field( + gcs_image_uri: str = proto.Field( proto.STRING, number=1, ) - image_uri = proto.Field( + image_uri: str = proto.Field( proto.STRING, number=2, ) @@ -186,11 +188,11 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field( + content: bytes = proto.Field( proto.BYTES, number=1, ) - source = proto.Field( + source: "ImageSource" = proto.Field( proto.MESSAGE, number=2, message="ImageSource", @@ -219,7 +221,7 @@ class FaceAnnotation(proto.Message): an image. It is not based on the landmarker results, only on the initial face detection, hence the fd (face detection) prefix. - landmarks (Sequence[google.cloud.vision_v1p2beta1.types.FaceAnnotation.Landmark]): + landmarks (MutableSequence[google.cloud.vision_v1p2beta1.types.FaceAnnotation.Landmark]): Detected face landmarks. roll_angle (float): Roll angle, which indicates the amount of @@ -306,83 +308,83 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_ = proto.Field( + type_: "FaceAnnotation.Landmark.Type" = proto.Field( proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type", ) - position = proto.Field( + position: geometry.Position = proto.Field( proto.MESSAGE, number=4, message=geometry.Position, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - fd_bounding_poly = proto.Field( + fd_bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - landmarks = proto.RepeatedField( + landmarks: MutableSequence[Landmark] = proto.RepeatedField( proto.MESSAGE, number=3, message=Landmark, ) - roll_angle = proto.Field( + roll_angle: float = proto.Field( proto.FLOAT, number=4, ) - pan_angle = proto.Field( + pan_angle: float = proto.Field( proto.FLOAT, number=5, ) - tilt_angle = proto.Field( + tilt_angle: float = proto.Field( proto.FLOAT, number=6, ) - detection_confidence = proto.Field( + detection_confidence: float = proto.Field( proto.FLOAT, number=7, ) - landmarking_confidence = proto.Field( + landmarking_confidence: float = proto.Field( proto.FLOAT, number=8, ) - joy_likelihood = proto.Field( + joy_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", ) - sorrow_likelihood = proto.Field( + sorrow_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=10, enum="Likelihood", ) - anger_likelihood = proto.Field( + anger_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=11, enum="Likelihood", ) - surprise_likelihood = proto.Field( + surprise_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=12, enum="Likelihood", ) - under_exposed_likelihood = proto.Field( + under_exposed_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=13, enum="Likelihood", ) - blurred_likelihood = proto.Field( + blurred_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=14, enum="Likelihood", ) - headwear_likelihood = proto.Field( + headwear_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=15, enum="Likelihood", @@ -397,7 +399,7 @@ class LocationInfo(proto.Message): lat/long location coordinates. """ - lat_lng = proto.Field( + lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, @@ -416,15 +418,15 @@ class Property(proto.Message): Value of numeric properties. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - uint64_value = proto.Field( + uint64_value: int = proto.Field( proto.UINT64, number=3, ) @@ -462,54 +464,54 @@ class EntityAnnotation(proto.Message): bounding_poly (google.cloud.vision_v1p2beta1.types.BoundingPoly): Image region to which this entity belongs. Not produced for ``LABEL_DETECTION`` features. - locations (Sequence[google.cloud.vision_v1p2beta1.types.LocationInfo]): + locations (MutableSequence[google.cloud.vision_v1p2beta1.types.LocationInfo]): The location information for the detected entity. Multiple ``LocationInfo`` elements can be present because one location may indicate the location of the scene in the image, and another location may indicate the location of the place where the image was taken. Location information is usually present for landmarks. - properties (Sequence[google.cloud.vision_v1p2beta1.types.Property]): + properties (MutableSequence[google.cloud.vision_v1p2beta1.types.Property]): Some entities may have optional user-supplied ``Property`` (name/value) fields, such a score or string that qualifies the entity. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - locale = proto.Field( + locale: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) - topicality = proto.Field( + topicality: float = proto.Field( proto.FLOAT, number=6, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=7, message=geometry.BoundingPoly, ) - locations = proto.RepeatedField( + locations: MutableSequence["LocationInfo"] = proto.RepeatedField( proto.MESSAGE, number=8, message="LocationInfo", ) - properties = proto.RepeatedField( + properties: MutableSequence["Property"] = proto.RepeatedField( proto.MESSAGE, number=9, message="Property", @@ -545,27 +547,27 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult = proto.Field( + adult: "Likelihood" = proto.Field( proto.ENUM, number=1, enum="Likelihood", ) - spoof = proto.Field( + spoof: "Likelihood" = proto.Field( proto.ENUM, number=2, enum="Likelihood", ) - medical = proto.Field( + medical: "Likelihood" = proto.Field( proto.ENUM, number=3, enum="Likelihood", ) - violence = proto.Field( + violence: "Likelihood" = proto.Field( proto.ENUM, number=4, enum="Likelihood", ) - racy = proto.Field( + racy: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", @@ -582,12 +584,12 @@ class LatLongRect(proto.Message): Max lat/long pair. """ - min_lat_lng = proto.Field( + min_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, ) - max_lat_lng = proto.Field( + max_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=2, message=latlng_pb2.LatLng, @@ -608,16 +610,16 @@ class ColorInfo(proto.Message): Value in range [0, 1]. """ - color = proto.Field( + color: color_pb2.Color = proto.Field( proto.MESSAGE, number=1, message=color_pb2.Color, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - pixel_fraction = proto.Field( + pixel_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -627,12 +629,12 @@ class DominantColorsAnnotation(proto.Message): r"""Set of dominant colors and their corresponding scores. Attributes: - colors (Sequence[google.cloud.vision_v1p2beta1.types.ColorInfo]): + colors (MutableSequence[google.cloud.vision_v1p2beta1.types.ColorInfo]): RGB color values with their score and pixel fraction. """ - colors = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ColorInfo", @@ -648,7 +650,7 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, message="DominantColorsAnnotation", @@ -671,16 +673,16 @@ class CropHint(proto.Message): with respect to the original image. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) - importance_fraction = proto.Field( + importance_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -691,11 +693,11 @@ class CropHintsAnnotation(proto.Message): serving images. Attributes: - crop_hints (Sequence[google.cloud.vision_v1p2beta1.types.CropHint]): + crop_hints (MutableSequence[google.cloud.vision_v1p2beta1.types.CropHint]): Crop hint results. """ - crop_hints = proto.RepeatedField( + crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( proto.MESSAGE, number=1, message="CropHint", @@ -706,7 +708,7 @@ class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. Attributes: - aspect_ratios (Sequence[float]): + aspect_ratios (MutableSequence[float]): Aspect ratios in floats, representing the ratio of the width to the height of the image. For example, if the desired aspect ratio is 4/3, @@ -717,7 +719,7 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField( + aspect_ratios: MutableSequence[float] = proto.RepeatedField( proto.FLOAT, number=1, ) @@ -732,7 +734,7 @@ class WebDetectionParams(proto.Message): geo information in the image. """ - include_geo_results = proto.Field( + include_geo_results: bool = proto.Field( proto.BOOL, number=2, ) @@ -747,16 +749,16 @@ class TextDetectionParams(proto.Message): By default, Cloud Vision API only includes confidence score for DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence score for TEXT_DETECTION as well. - advanced_ocr_options (Sequence[str]): + advanced_ocr_options (MutableSequence[str]): A list of advanced OCR options to fine-tune OCR behavior. """ - enable_text_detection_confidence_score = proto.Field( + enable_text_detection_confidence_score: bool = proto.Field( proto.BOOL, number=9, ) - advanced_ocr_options = proto.RepeatedField( + advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=11, ) @@ -768,7 +770,7 @@ class ImageContext(proto.Message): Attributes: lat_long_rect (google.cloud.vision_v1p2beta1.types.LatLongRect): Not used. - language_hints (Sequence[str]): + language_hints (MutableSequence[str]): List of languages to use for TEXT_DETECTION. In most cases, an empty value yields the best results since it enables automatic language detection. For languages based on the @@ -788,26 +790,26 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect = proto.Field( + lat_long_rect: "LatLongRect" = proto.Field( proto.MESSAGE, number=1, message="LatLongRect", ) - language_hints = proto.RepeatedField( + language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params = proto.Field( + crop_hints_params: "CropHintsParams" = proto.Field( proto.MESSAGE, number=4, message="CropHintsParams", ) - web_detection_params = proto.Field( + web_detection_params: "WebDetectionParams" = proto.Field( proto.MESSAGE, number=6, message="WebDetectionParams", ) - text_detection_params = proto.Field( + text_detection_params: "TextDetectionParams" = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", @@ -821,24 +823,24 @@ class AnnotateImageRequest(proto.Message): Attributes: image (google.cloud.vision_v1p2beta1.types.Image): The image to be processed. - features (Sequence[google.cloud.vision_v1p2beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p2beta1.types.Feature]): Requested features. image_context (google.cloud.vision_v1p2beta1.types.ImageContext): Additional context that may accompany the image. """ - image = proto.Field( + image: "Image" = proto.Field( proto.MESSAGE, number=1, message="Image", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", @@ -859,11 +861,11 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) - page_number = proto.Field( + page_number: int = proto.Field( proto.INT32, number=2, ) @@ -873,19 +875,19 @@ class AnnotateImageResponse(proto.Message): r"""Response to an image annotation request. Attributes: - face_annotations (Sequence[google.cloud.vision_v1p2beta1.types.FaceAnnotation]): + face_annotations (MutableSequence[google.cloud.vision_v1p2beta1.types.FaceAnnotation]): If present, face detection has completed successfully. - landmark_annotations (Sequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): + landmark_annotations (MutableSequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): If present, landmark detection has completed successfully. - logo_annotations (Sequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): + logo_annotations (MutableSequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): If present, logo detection has completed successfully. - label_annotations (Sequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): + label_annotations (MutableSequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): If present, label detection has completed successfully. - text_annotations (Sequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): + text_annotations (MutableSequence[google.cloud.vision_v1p2beta1.types.EntityAnnotation]): If present, text (OCR) detection has completed successfully. full_text_annotation (google.cloud.vision_v1p2beta1.types.TextAnnotation): @@ -914,62 +916,62 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations = proto.RepeatedField( + face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FaceAnnotation", ) - landmark_annotations = proto.RepeatedField( + landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityAnnotation", ) - logo_annotations = proto.RepeatedField( + logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=3, message="EntityAnnotation", ) - label_annotations = proto.RepeatedField( + label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=4, message="EntityAnnotation", ) - text_annotations = proto.RepeatedField( + text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=5, message="EntityAnnotation", ) - full_text_annotation = proto.Field( + full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation = proto.Field( + safe_search_annotation: "SafeSearchAnnotation" = proto.Field( proto.MESSAGE, number=6, message="SafeSearchAnnotation", ) - image_properties_annotation = proto.Field( + image_properties_annotation: "ImageProperties" = proto.Field( proto.MESSAGE, number=8, message="ImageProperties", ) - crop_hints_annotation = proto.Field( + crop_hints_annotation: "CropHintsAnnotation" = proto.Field( proto.MESSAGE, number=11, message="CropHintsAnnotation", ) - web_detection = proto.Field( + web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, ) - error = proto.Field( + error: status_pb2.Status = proto.Field( proto.MESSAGE, number=9, message=status_pb2.Status, ) - context = proto.Field( + context: "ImageAnnotationContext" = proto.Field( proto.MESSAGE, number=21, message="ImageAnnotationContext", @@ -985,17 +987,17 @@ class AnnotateFileResponse(proto.Message): input_config (google.cloud.vision_v1p2beta1.types.InputConfig): Information about the file for which this response is generated. - responses (Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1p2beta1.types.AnnotateImageResponse]): Individual responses to images found within the file. """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=2, message="AnnotateImageResponse", @@ -1007,12 +1009,12 @@ class BatchAnnotateImagesRequest(proto.Message): service call. Attributes: - requests (Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", @@ -1023,12 +1025,12 @@ class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1p2beta1.types.AnnotateImageResponse]): Individual responses to image annotation requests within the batch. """ - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageResponse", @@ -1041,7 +1043,7 @@ class AsyncAnnotateFileRequest(proto.Message): Attributes: input_config (google.cloud.vision_v1p2beta1.types.InputConfig): Required. Information about the input file. - features (Sequence[google.cloud.vision_v1p2beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p2beta1.types.Feature]): Required. Requested features. image_context (google.cloud.vision_v1p2beta1.types.ImageContext): Additional context that may accompany the @@ -1051,22 +1053,22 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", ) - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=4, message="OutputConfig", @@ -1082,7 +1084,7 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, message="OutputConfig", @@ -1094,12 +1096,12 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): single service call. Attributes: - requests (Sequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. """ - requests = proto.RepeatedField( + requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileRequest", @@ -1110,13 +1112,13 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileResponse]): + responses (MutableSequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one for each request in AsyncBatchAnnotateFilesRequest. """ - responses = proto.RepeatedField( + responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileResponse", @@ -1136,12 +1138,12 @@ class InputConfig(proto.Message): supported. Wildcards are not supported. """ - gcs_source = proto.Field( + gcs_source: "GcsSource" = proto.Field( proto.MESSAGE, number=1, message="GcsSource", ) - mime_type = proto.Field( + mime_type: str = proto.Field( proto.STRING, number=2, ) @@ -1168,12 +1170,12 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination = proto.Field( + gcs_destination: "GcsDestination" = proto.Field( proto.MESSAGE, number=1, message="GcsDestination", ) - batch_size = proto.Field( + batch_size: int = proto.Field( proto.INT32, number=2, ) @@ -1190,7 +1192,7 @@ class GcsSource(proto.Message): not currently supported. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1221,7 +1223,7 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1248,17 +1250,17 @@ class State(proto.Enum): DONE = 3 CANCELLED = 4 - state = proto.Field( + state: State = proto.Field( proto.ENUM, number=1, enum=State, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, diff --git a/google/cloud/vision_v1p2beta1/types/text_annotation.py b/google/cloud/vision_v1p2beta1/types/text_annotation.py index 636e6e01..9ab0d967 100644 --- a/google/cloud/vision_v1p2beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p2beta1/types/text_annotation.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p2beta1.types import geometry @@ -42,7 +44,7 @@ class TextAnnotation(proto.Message): message definition below for more detail. Attributes: - pages (Sequence[google.cloud.vision_v1p2beta1.types.Page]): + pages (MutableSequence[google.cloud.vision_v1p2beta1.types.Page]): List of pages detected by OCR. text (str): UTF-8 text detected on the pages. @@ -60,11 +62,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=1, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) @@ -88,12 +90,12 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_ = proto.Field( + type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - is_prefix = proto.Field( + is_prefix: bool = proto.Field( proto.BOOL, number=2, ) @@ -102,30 +104,32 @@ class TextProperty(proto.Message): r"""Additional information detected on the structural component. Attributes: - detected_languages (Sequence[google.cloud.vision_v1p2beta1.types.TextAnnotation.DetectedLanguage]): + detected_languages (MutableSequence[google.cloud.vision_v1p2beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with confidence. detected_break (google.cloud.vision_v1p2beta1.types.TextAnnotation.DetectedBreak): Detected start or end of a text segment. """ - detected_languages = proto.RepeatedField( + detected_languages: MutableSequence[ + "TextAnnotation.DetectedLanguage" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", ) - detected_break = proto.Field( + detected_break: "TextAnnotation.DetectedBreak" = proto.Field( proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", ) - pages = proto.RepeatedField( + pages: MutableSequence["Page"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Page", ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=2, ) @@ -143,32 +147,32 @@ class Page(proto.Message): height (int): Page height. For PDFs the unit is points. For images (including TIFFs) the unit is pixels. - blocks (Sequence[google.cloud.vision_v1p2beta1.types.Block]): + blocks (MutableSequence[google.cloud.vision_v1p2beta1.types.Block]): List of blocks of text, images etc on this page. confidence (float): Confidence of the OCR results on the page. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - width = proto.Field( + width: int = proto.Field( proto.INT32, number=2, ) - height = proto.Field( + height: int = proto.Field( proto.INT32, number=3, ) - blocks = proto.RepeatedField( + blocks: MutableSequence["Block"] = proto.RepeatedField( proto.MESSAGE, number=4, message="Block", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -206,7 +210,7 @@ class Block(proto.Message): 1----0 and the vertice order will still be (0, 1, 2, 3). - paragraphs (Sequence[google.cloud.vision_v1p2beta1.types.Paragraph]): + paragraphs (MutableSequence[google.cloud.vision_v1p2beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). block_type (google.cloud.vision_v1p2beta1.types.Block.BlockType): @@ -225,27 +229,27 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs = proto.RepeatedField( + paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Paragraph", ) - block_type = proto.Field( + block_type: BlockType = proto.Field( proto.ENUM, number=4, enum=BlockType, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -271,29 +275,29 @@ class Paragraph(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). - words (Sequence[google.cloud.vision_v1p2beta1.types.Word]): + words (MutableSequence[google.cloud.vision_v1p2beta1.types.Word]): List of words in this paragraph. confidence (float): Confidence of the OCR results for the paragraph. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words = proto.RepeatedField( + words: MutableSequence["Word"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Word", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -317,7 +321,7 @@ class Word(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). - symbols (Sequence[google.cloud.vision_v1p2beta1.types.Symbol]): + symbols (MutableSequence[google.cloud.vision_v1p2beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural reading order. @@ -325,22 +329,22 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols = proto.RepeatedField( + symbols: MutableSequence["Symbol"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Symbol", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -372,21 +376,21 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=3, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) diff --git a/google/cloud/vision_v1p2beta1/types/web_detection.py b/google/cloud/vision_v1p2beta1/types/web_detection.py index 4fca0f68..d5b0db7b 100644 --- a/google/cloud/vision_v1p2beta1/types/web_detection.py +++ b/google/cloud/vision_v1p2beta1/types/web_detection.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -28,24 +30,24 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. Attributes: - web_entities (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebEntity]): + web_entities (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the Internet. - full_matching_images (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): Fully matching images from the Internet. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): Partial matching images from the Internet. Those images are similar enough to share some key-point features. For example an original image will likely have partial matching for its crops. - pages_with_matching_images (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebPage]): + pages_with_matching_images (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebPage]): Web pages containing the matching images from the Internet. - visually_similar_images (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): + visually_similar_images (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): The visually similar image results. - best_guess_labels (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebLabel]): + best_guess_labels (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebLabel]): Best guess text labels for the request image. """ @@ -64,15 +66,15 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field( + entity_id: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) @@ -88,11 +90,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) @@ -109,10 +111,10 @@ class WebPage(proto.Message): page_title (str): Title for the web page, may contain HTML markups. - full_matching_images (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): Fully matching images on the page. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebImage]): Partial matching images on the page. Those images are similar enough to share some key-point features. For example an original @@ -120,24 +122,28 @@ class WebPage(proto.Message): crops. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - page_title = proto.Field( + page_title: str = proto.Field( proto.STRING, number=3, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=4, message="WebDetection.WebImage", ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=5, message="WebDetection.WebImage", @@ -155,41 +161,41 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field( + label: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - web_entities = proto.RepeatedField( + web_entities: MutableSequence[WebEntity] = proto.RepeatedField( proto.MESSAGE, number=1, message=WebEntity, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=2, message=WebImage, ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=3, message=WebImage, ) - pages_with_matching_images = proto.RepeatedField( + pages_with_matching_images: MutableSequence[WebPage] = proto.RepeatedField( proto.MESSAGE, number=4, message=WebPage, ) - visually_similar_images = proto.RepeatedField( + visually_similar_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=6, message=WebImage, ) - best_guess_labels = proto.RepeatedField( + best_guess_labels: MutableSequence[WebLabel] = proto.RepeatedField( proto.MESSAGE, number=8, message=WebLabel, diff --git a/google/cloud/vision_v1p3beta1/__init__.py b/google/cloud/vision_v1p3beta1/__init__.py index 226819d9..ff480b2a 100644 --- a/google/cloud/vision_v1p3beta1/__init__.py +++ b/google/cloud/vision_v1p3beta1/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.vision import gapic_version as package_version + +__version__ = package_version.__version__ + from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers diff --git a/google/cloud/vision_v1p3beta1/gapic_metadata.json b/google/cloud/vision_v1p3beta1/gapic_metadata.json new file mode 100644 index 00000000..a1425044 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/gapic_metadata.json @@ -0,0 +1,237 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.vision_v1p3beta1", + "protoPackage": "google.cloud.vision.v1p3beta1", + "schema": "1.0", + "services": { + "ImageAnnotator": { + "clients": { + "grpc": { + "libraryClient": "ImageAnnotatorClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ImageAnnotatorAsyncClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + } + } + }, + "ProductSearch": { + "clients": { + "grpc": { + "libraryClient": "ProductSearchClient", + "rpcs": { + "AddProductToProductSet": { + "methods": [ + "add_product_to_product_set" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "CreateProductSet": { + "methods": [ + "create_product_set" + ] + }, + "CreateReferenceImage": { + "methods": [ + "create_reference_image" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "DeleteProductSet": { + "methods": [ + "delete_product_set" + ] + }, + "DeleteReferenceImage": { + "methods": [ + "delete_reference_image" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "GetProductSet": { + "methods": [ + "get_product_set" + ] + }, + "GetReferenceImage": { + "methods": [ + "get_reference_image" + ] + }, + "ImportProductSets": { + "methods": [ + "import_product_sets" + ] + }, + "ListProductSets": { + "methods": [ + "list_product_sets" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "ListProductsInProductSet": { + "methods": [ + "list_products_in_product_set" + ] + }, + "ListReferenceImages": { + "methods": [ + "list_reference_images" + ] + }, + "RemoveProductFromProductSet": { + "methods": [ + "remove_product_from_product_set" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + }, + "UpdateProductSet": { + "methods": [ + "update_product_set" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductSearchAsyncClient", + "rpcs": { + "AddProductToProductSet": { + "methods": [ + "add_product_to_product_set" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "CreateProductSet": { + "methods": [ + "create_product_set" + ] + }, + "CreateReferenceImage": { + "methods": [ + "create_reference_image" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "DeleteProductSet": { + "methods": [ + "delete_product_set" + ] + }, + "DeleteReferenceImage": { + "methods": [ + "delete_reference_image" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "GetProductSet": { + "methods": [ + "get_product_set" + ] + }, + "GetReferenceImage": { + "methods": [ + "get_reference_image" + ] + }, + "ImportProductSets": { + "methods": [ + "import_product_sets" + ] + }, + "ListProductSets": { + "methods": [ + "list_product_sets" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "ListProductsInProductSet": { + "methods": [ + "list_products_in_product_set" + ] + }, + "ListReferenceImages": { + "methods": [ + "list_reference_images" + ] + }, + "RemoveProductFromProductSet": { + "methods": [ + "remove_product_from_product_set" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + }, + "UpdateProductSet": { + "methods": [ + "update_product_set" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/vision_v1p3beta1/gapic_version.py b/google/cloud/vision_v1p3beta1/gapic_version.py new file mode 100644 index 00000000..47c54531 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "3.2.0" # {x-release-please-version} diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py index 159bea06..fa36c97c 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -165,9 +176,9 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -211,11 +222,15 @@ def __init__( async def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -247,10 +262,10 @@ async def sample_batch_annotate_images(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.BatchAnnotateImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.BatchAnnotateImagesRequest, dict]]): The request object. Multiple image annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]`): Individual image annotation requests for this batch. @@ -317,11 +332,15 @@ async def sample_batch_annotate_images(): async def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of @@ -356,16 +375,16 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.AsyncBatchAnnotateFilesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.AsyncBatchAnnotateFilesRequest, dict]]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]`): Required. Individual async file annotation requests for this batch. @@ -445,14 +464,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/client.py b/google/cloud/vision_v1p3beta1/services/image_annotator/client.py index 1512723a..b40159c4 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -58,7 +70,7 @@ class ImageAnnotatorClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. @@ -361,8 +373,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageAnnotatorTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ImageAnnotatorTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -376,7 +388,7 @@ def __init__( transport (Union[str, ImageAnnotatorTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -406,6 +418,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -458,11 +471,15 @@ def __init__( def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -497,7 +514,7 @@ def sample_batch_annotate_images(): request (Union[google.cloud.vision_v1p3beta1.types.BatchAnnotateImagesRequest, dict]): The request object. Multiple image annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]): Individual image annotation requests for this batch. @@ -557,11 +574,15 @@ def sample_batch_annotate_images(): def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of @@ -605,7 +626,7 @@ def sample_async_batch_annotate_files(): request (Union[google.cloud.vision_v1p3beta1.types.AsyncBatchAnnotateFilesRequest, dict]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. @@ -690,14 +711,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py index 70c93fcf..74cefe1c 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1p3beta1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -29,14 +30,9 @@ from google.cloud.vision_v1p3beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ImageAnnotatorTransport(abc.ABC): @@ -53,7 +49,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py index f3b44f41..40c02866 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py @@ -52,14 +52,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -187,8 +187,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py index b664e535..d98ae534 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py @@ -54,7 +54,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -97,15 +97,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1p3beta1/services/product_search/async_client.py b/google/cloud/vision_v1p3beta1/services/product_search/async_client.py index a6c8f05c..fc40404f 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/async_client.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -190,9 +201,9 @@ def transport(self) -> ProductSearchTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ProductSearchTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the product search client. @@ -236,13 +247,15 @@ def __init__( async def create_product_set( self, - request: Union[product_search_service.CreateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductSetRequest, dict] + ] = None, *, - parent: str = None, - product_set: product_search_service.ProductSet = None, - product_set_id: str = None, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. @@ -279,7 +292,7 @@ async def sample_create_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.CreateProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.CreateProductSetRequest, dict]]): The request object. Request message for the `CreateProductSet` method. parent (:class:`str`): @@ -376,11 +389,13 @@ async def sample_create_product_set(): async def list_product_sets( self, - request: Union[product_search_service.ListProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductSetsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductSetsAsyncPager: r"""Lists ProductSets in an unspecified order. @@ -418,7 +433,7 @@ async def sample_list_product_sets(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.ListProductSetsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.ListProductSetsRequest, dict]]): The request object. Request message for the `ListProductSets` method. parent (:class:`str`): @@ -507,11 +522,13 @@ async def sample_list_product_sets(): async def get_product_set( self, - request: Union[product_search_service.GetProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. @@ -547,7 +564,7 @@ async def sample_get_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.GetProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.GetProductSetRequest, dict]]): The request object. Request message for the `GetProductSet` method. name (:class:`str`): @@ -628,12 +645,14 @@ async def sample_get_product_set(): async def update_product_set( self, - request: Union[product_search_service.UpdateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductSetRequest, dict] + ] = None, *, - product_set: product_search_service.ProductSet = None, - update_mask: field_mask_pb2.FieldMask = None, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be @@ -672,7 +691,7 @@ async def sample_update_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.UpdateProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.UpdateProductSetRequest, dict]]): The request object. Request message for the `UpdateProductSet` method. product_set (:class:`google.cloud.vision_v1p3beta1.types.ProductSet`): @@ -761,11 +780,13 @@ async def sample_update_product_set(): async def delete_product_set( self, - request: Union[product_search_service.DeleteProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a ProductSet. All Products and @@ -802,7 +823,7 @@ async def sample_delete_product_set(): await client.delete_product_set(request=request) Args: - request (Union[google.cloud.vision_v1p3beta1.types.DeleteProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.DeleteProductSetRequest, dict]]): The request object. Request message for the `DeleteProductSet` method. name (:class:`str`): @@ -871,13 +892,15 @@ async def sample_delete_product_set(): async def create_product( self, - request: Union[product_search_service.CreateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductRequest, dict] + ] = None, *, - parent: str = None, - product: product_search_service.Product = None, - product_id: str = None, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Creates and returns a new product resource. @@ -918,7 +941,7 @@ async def sample_create_product(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.CreateProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.CreateProductRequest, dict]]): The request object. Request message for the `CreateProduct` method. parent (:class:`str`): @@ -1010,11 +1033,13 @@ async def sample_create_product(): async def list_products( self, - request: Union[product_search_service.ListProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsAsyncPager: r"""Lists products in an unspecified order. @@ -1052,7 +1077,7 @@ async def sample_list_products(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.ListProductsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.ListProductsRequest, dict]]): The request object. Request message for the `ListProducts` method. parent (:class:`str`): @@ -1141,11 +1166,11 @@ async def sample_list_products(): async def get_product( self, - request: Union[product_search_service.GetProductRequest, dict] = None, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Gets information associated with a Product. @@ -1181,7 +1206,7 @@ async def sample_get_product(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.GetProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.GetProductRequest, dict]]): The request object. Request message for the `GetProduct` method. name (:class:`str`): @@ -1257,12 +1282,14 @@ async def sample_get_product(): async def update_product( self, - request: Union[product_search_service.UpdateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductRequest, dict] + ] = None, *, - product: product_search_service.Product = None, - update_mask: field_mask_pb2.FieldMask = None, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only display_name, @@ -1308,7 +1335,7 @@ async def sample_update_product(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.UpdateProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.UpdateProductRequest, dict]]): The request object. Request message for the `UpdateProduct` method. product (:class:`google.cloud.vision_v1p3beta1.types.Product`): @@ -1394,11 +1421,13 @@ async def sample_update_product(): async def delete_product( self, - request: Union[product_search_service.DeleteProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a product and its reference images. @@ -1435,7 +1464,7 @@ async def sample_delete_product(): await client.delete_product(request=request) Args: - request (Union[google.cloud.vision_v1p3beta1.types.DeleteProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.DeleteProductRequest, dict]]): The request object. Request message for the `DeleteProduct` method. name (:class:`str`): @@ -1504,13 +1533,15 @@ async def sample_delete_product(): async def create_reference_image( self, - request: Union[product_search_service.CreateReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateReferenceImageRequest, dict] + ] = None, *, - parent: str = None, - reference_image: product_search_service.ReferenceImage = None, - reference_image_id: str = None, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. @@ -1567,7 +1598,7 @@ async def sample_create_reference_image(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.CreateReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.CreateReferenceImageRequest, dict]]): The request object. Request message for the `CreateReferenceImage` method. parent (:class:`str`): @@ -1665,11 +1696,13 @@ async def sample_create_reference_image(): async def delete_reference_image( self, - request: Union[product_search_service.DeleteReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a reference image. @@ -1709,7 +1742,7 @@ async def sample_delete_reference_image(): await client.delete_reference_image(request=request) Args: - request (Union[google.cloud.vision_v1p3beta1.types.DeleteReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.DeleteReferenceImageRequest, dict]]): The request object. Request message for the `DeleteReferenceImage` method. name (:class:`str`): @@ -1780,11 +1813,13 @@ async def sample_delete_reference_image(): async def list_reference_images( self, - request: Union[product_search_service.ListReferenceImagesRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListReferenceImagesRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListReferenceImagesAsyncPager: r"""Lists reference images. @@ -1823,7 +1858,7 @@ async def sample_list_reference_images(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.ListReferenceImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.ListReferenceImagesRequest, dict]]): The request object. Request message for the `ListReferenceImages` method. parent (:class:`str`): @@ -1913,11 +1948,13 @@ async def sample_list_reference_images(): async def get_reference_image( self, - request: Union[product_search_service.GetReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. @@ -1953,7 +1990,7 @@ async def sample_get_reference_image(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.GetReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.GetReferenceImageRequest, dict]]): The request object. Request message for the `GetReferenceImage` method. name (:class:`str`): @@ -2033,14 +2070,14 @@ async def sample_get_reference_image(): async def add_product_to_product_set( self, - request: Union[ - product_search_service.AddProductToProductSetRequest, dict + request: Optional[ + Union[product_search_service.AddProductToProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is @@ -2078,7 +2115,7 @@ async def sample_add_product_to_product_set(): await client.add_product_to_product_set(request=request) Args: - request (Union[google.cloud.vision_v1p3beta1.types.AddProductToProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.AddProductToProductSetRequest, dict]]): The request object. Request message for the `AddProductToProductSet` method. name (:class:`str`): @@ -2157,14 +2194,14 @@ async def sample_add_product_to_product_set(): async def remove_product_from_product_set( self, - request: Union[ - product_search_service.RemoveProductFromProductSetRequest, dict + request: Optional[ + Union[product_search_service.RemoveProductFromProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Removes a Product from the specified ProductSet. @@ -2199,7 +2236,7 @@ async def sample_remove_product_from_product_set(): await client.remove_product_from_product_set(request=request) Args: - request (Union[google.cloud.vision_v1p3beta1.types.RemoveProductFromProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.RemoveProductFromProductSetRequest, dict]]): The request object. Request message for the `RemoveProductFromProductSet` method. name (:class:`str`): @@ -2278,13 +2315,13 @@ async def sample_remove_product_from_product_set(): async def list_products_in_product_set( self, - request: Union[ - product_search_service.ListProductsInProductSetRequest, dict + request: Optional[ + Union[product_search_service.ListProductsInProductSetRequest, dict] ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsInProductSetAsyncPager: r"""Lists the Products in a ProductSet, in an unspecified order. If @@ -2324,7 +2361,7 @@ async def sample_list_products_in_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.ListProductsInProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.ListProductsInProductSetRequest, dict]]): The request object. Request message for the `ListProductsInProductSet` method. name (:class:`str`): @@ -2415,12 +2452,16 @@ async def sample_list_products_in_product_set(): async def import_product_sets( self, - request: Union[product_search_service.ImportProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ImportProductSetsRequest, dict] + ] = None, *, - parent: str = None, - input_config: product_search_service.ImportProductSetsInputConfig = None, + parent: Optional[str] = None, + input_config: Optional[ + product_search_service.ImportProductSetsInputConfig + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Asynchronous API that imports a list of reference images to @@ -2461,13 +2502,13 @@ async def sample_import_product_sets(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1p3beta1.types.ImportProductSetsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p3beta1.types.ImportProductSetsRequest, dict]]): The request object. Request message for the `ImportProductSets` method. parent (:class:`str`): @@ -2573,14 +2614,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ProductSearchAsyncClient",) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/client.py b/google/cloud/vision_v1p3beta1/services/product_search/client.py index 63445973..22be806c 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/client.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1p3beta1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -61,7 +73,7 @@ class ProductSearchClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ProductSearchTransport]: """Returns an appropriate transport class. @@ -404,8 +416,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductSearchTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ProductSearchTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the product search client. @@ -419,7 +431,7 @@ def __init__( transport (Union[str, ProductSearchTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -449,6 +461,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -501,13 +514,15 @@ def __init__( def create_product_set( self, - request: Union[product_search_service.CreateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductSetRequest, dict] + ] = None, *, - parent: str = None, - product_set: product_search_service.ProductSet = None, - product_set_id: str = None, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. @@ -634,11 +649,13 @@ def sample_create_product_set(): def list_product_sets( self, - request: Union[product_search_service.ListProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductSetsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductSetsPager: r"""Lists ProductSets in an unspecified order. @@ -755,11 +772,13 @@ def sample_list_product_sets(): def get_product_set( self, - request: Union[product_search_service.GetProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. @@ -866,12 +885,14 @@ def sample_get_product_set(): def update_product_set( self, - request: Union[product_search_service.UpdateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductSetRequest, dict] + ] = None, *, - product_set: product_search_service.ProductSet = None, - update_mask: field_mask_pb2.FieldMask = None, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be @@ -992,11 +1013,13 @@ def sample_update_product_set(): def delete_product_set( self, - request: Union[product_search_service.DeleteProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a ProductSet. All Products and @@ -1092,13 +1115,15 @@ def sample_delete_product_set(): def create_product( self, - request: Union[product_search_service.CreateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductRequest, dict] + ] = None, *, - parent: str = None, - product: product_search_service.Product = None, - product_id: str = None, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Creates and returns a new product resource. @@ -1224,11 +1249,13 @@ def sample_create_product(): def list_products( self, - request: Union[product_search_service.ListProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsPager: r"""Lists products in an unspecified order. @@ -1345,11 +1372,11 @@ def sample_list_products(): def get_product( self, - request: Union[product_search_service.GetProductRequest, dict] = None, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Gets information associated with a Product. @@ -1451,12 +1478,14 @@ def sample_get_product(): def update_product( self, - request: Union[product_search_service.UpdateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductRequest, dict] + ] = None, *, - product: product_search_service.Product = None, - update_mask: field_mask_pb2.FieldMask = None, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only display_name, @@ -1581,11 +1610,13 @@ def sample_update_product(): def delete_product( self, - request: Union[product_search_service.DeleteProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a product and its reference images. @@ -1681,13 +1712,15 @@ def sample_delete_product(): def create_reference_image( self, - request: Union[product_search_service.CreateReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateReferenceImageRequest, dict] + ] = None, *, - parent: str = None, - reference_image: product_search_service.ReferenceImage = None, - reference_image_id: str = None, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. @@ -1835,11 +1868,13 @@ def sample_create_reference_image(): def delete_reference_image( self, - request: Union[product_search_service.DeleteReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a reference image. @@ -1940,11 +1975,13 @@ def sample_delete_reference_image(): def list_reference_images( self, - request: Union[product_search_service.ListReferenceImagesRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListReferenceImagesRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListReferenceImagesPager: r"""Lists reference images. @@ -2063,11 +2100,13 @@ def sample_list_reference_images(): def get_reference_image( self, - request: Union[product_search_service.GetReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. @@ -2173,14 +2212,14 @@ def sample_get_reference_image(): def add_product_to_product_set( self, - request: Union[ - product_search_service.AddProductToProductSetRequest, dict + request: Optional[ + Union[product_search_service.AddProductToProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is @@ -2294,14 +2333,14 @@ def sample_add_product_to_product_set(): def remove_product_from_product_set( self, - request: Union[ - product_search_service.RemoveProductFromProductSetRequest, dict + request: Optional[ + Union[product_search_service.RemoveProductFromProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Removes a Product from the specified ProductSet. @@ -2412,13 +2451,13 @@ def sample_remove_product_from_product_set(): def list_products_in_product_set( self, - request: Union[ - product_search_service.ListProductsInProductSetRequest, dict + request: Optional[ + Union[product_search_service.ListProductsInProductSetRequest, dict] ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsInProductSetPager: r"""Lists the Products in a ProductSet, in an unspecified order. If @@ -2543,12 +2582,16 @@ def sample_list_products_in_product_set(): def import_product_sets( self, - request: Union[product_search_service.ImportProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ImportProductSetsRequest, dict] + ] = None, *, - parent: str = None, - input_config: product_search_service.ImportProductSetsInputConfig = None, + parent: Optional[str] = None, + input_config: Optional[ + product_search_service.ImportProductSetsInputConfig + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Asynchronous API that imports a list of reference images to @@ -2701,14 +2744,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ProductSearchClient",) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py index bb982d2f..4df36baa 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1p3beta1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -30,14 +31,9 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ProductSearchTransport(abc.ABC): @@ -54,7 +50,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py index ad91f3a9..6b40fd3e 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py @@ -69,14 +69,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -204,8 +204,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py index a9898fd5..04443dda 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py @@ -71,7 +71,7 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -114,15 +114,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1p3beta1/types/geometry.py b/google/cloud/vision_v1p3beta1/types/geometry.py index 5a3f5df8..2bec30f7 100644 --- a/google/cloud/vision_v1p3beta1/types/geometry.py +++ b/google/cloud/vision_v1p3beta1/types/geometry.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -39,11 +41,11 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: int = proto.Field( proto.INT32, number=1, ) - y = proto.Field( + y: int = proto.Field( proto.INT32, number=2, ) @@ -61,11 +63,11 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) @@ -75,18 +77,18 @@ class BoundingPoly(proto.Message): r"""A bounding polygon for the detected image annotation. Attributes: - vertices (Sequence[google.cloud.vision_v1p3beta1.types.Vertex]): + vertices (MutableSequence[google.cloud.vision_v1p3beta1.types.Vertex]): The bounding polygon vertices. - normalized_vertices (Sequence[google.cloud.vision_v1p3beta1.types.NormalizedVertex]): + normalized_vertices (MutableSequence[google.cloud.vision_v1p3beta1.types.NormalizedVertex]): The bounding polygon normalized vertices. """ - vertices = proto.RepeatedField( + vertices: MutableSequence["Vertex"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Vertex", ) - normalized_vertices = proto.RepeatedField( + normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", @@ -108,15 +110,15 @@ class Position(proto.Message): Z coordinate (or depth). """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) - z = proto.Field( + z: float = proto.Field( proto.FLOAT, number=3, ) diff --git a/google/cloud/vision_v1p3beta1/types/image_annotator.py b/google/cloud/vision_v1p3beta1/types/image_annotator.py index f60e5553..e3fec2ac 100644 --- a/google/cloud/vision_v1p3beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p3beta1/types/image_annotator.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p3beta1.types import geometry @@ -115,16 +117,16 @@ class Type(proto.Enum): PRODUCT_SEARCH = 12 OBJECT_LOCALIZATION = 19 - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=1, enum=Type, ) - max_results = proto.Field( + max_results: int = proto.Field( proto.INT32, number=2, ) - model = proto.Field( + model: str = proto.Field( proto.STRING, number=3, ) @@ -165,11 +167,11 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field( + gcs_image_uri: str = proto.Field( proto.STRING, number=1, ) - image_uri = proto.Field( + image_uri: str = proto.Field( proto.STRING, number=2, ) @@ -190,11 +192,11 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field( + content: bytes = proto.Field( proto.BYTES, number=1, ) - source = proto.Field( + source: "ImageSource" = proto.Field( proto.MESSAGE, number=2, message="ImageSource", @@ -223,7 +225,7 @@ class FaceAnnotation(proto.Message): an image. It is not based on the landmarker results, only on the initial face detection, hence the fd (face detection) prefix. - landmarks (Sequence[google.cloud.vision_v1p3beta1.types.FaceAnnotation.Landmark]): + landmarks (MutableSequence[google.cloud.vision_v1p3beta1.types.FaceAnnotation.Landmark]): Detected face landmarks. roll_angle (float): Roll angle, which indicates the amount of @@ -310,83 +312,83 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_ = proto.Field( + type_: "FaceAnnotation.Landmark.Type" = proto.Field( proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type", ) - position = proto.Field( + position: geometry.Position = proto.Field( proto.MESSAGE, number=4, message=geometry.Position, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - fd_bounding_poly = proto.Field( + fd_bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - landmarks = proto.RepeatedField( + landmarks: MutableSequence[Landmark] = proto.RepeatedField( proto.MESSAGE, number=3, message=Landmark, ) - roll_angle = proto.Field( + roll_angle: float = proto.Field( proto.FLOAT, number=4, ) - pan_angle = proto.Field( + pan_angle: float = proto.Field( proto.FLOAT, number=5, ) - tilt_angle = proto.Field( + tilt_angle: float = proto.Field( proto.FLOAT, number=6, ) - detection_confidence = proto.Field( + detection_confidence: float = proto.Field( proto.FLOAT, number=7, ) - landmarking_confidence = proto.Field( + landmarking_confidence: float = proto.Field( proto.FLOAT, number=8, ) - joy_likelihood = proto.Field( + joy_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", ) - sorrow_likelihood = proto.Field( + sorrow_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=10, enum="Likelihood", ) - anger_likelihood = proto.Field( + anger_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=11, enum="Likelihood", ) - surprise_likelihood = proto.Field( + surprise_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=12, enum="Likelihood", ) - under_exposed_likelihood = proto.Field( + under_exposed_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=13, enum="Likelihood", ) - blurred_likelihood = proto.Field( + blurred_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=14, enum="Likelihood", ) - headwear_likelihood = proto.Field( + headwear_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=15, enum="Likelihood", @@ -401,7 +403,7 @@ class LocationInfo(proto.Message): lat/long location coordinates. """ - lat_lng = proto.Field( + lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, @@ -420,15 +422,15 @@ class Property(proto.Message): Value of numeric properties. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - uint64_value = proto.Field( + uint64_value: int = proto.Field( proto.UINT64, number=3, ) @@ -466,54 +468,54 @@ class EntityAnnotation(proto.Message): bounding_poly (google.cloud.vision_v1p3beta1.types.BoundingPoly): Image region to which this entity belongs. Not produced for ``LABEL_DETECTION`` features. - locations (Sequence[google.cloud.vision_v1p3beta1.types.LocationInfo]): + locations (MutableSequence[google.cloud.vision_v1p3beta1.types.LocationInfo]): The location information for the detected entity. Multiple ``LocationInfo`` elements can be present because one location may indicate the location of the scene in the image, and another location may indicate the location of the place where the image was taken. Location information is usually present for landmarks. - properties (Sequence[google.cloud.vision_v1p3beta1.types.Property]): + properties (MutableSequence[google.cloud.vision_v1p3beta1.types.Property]): Some entities may have optional user-supplied ``Property`` (name/value) fields, such a score or string that qualifies the entity. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - locale = proto.Field( + locale: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) - topicality = proto.Field( + topicality: float = proto.Field( proto.FLOAT, number=6, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=7, message=geometry.BoundingPoly, ) - locations = proto.RepeatedField( + locations: MutableSequence["LocationInfo"] = proto.RepeatedField( proto.MESSAGE, number=8, message="LocationInfo", ) - properties = proto.RepeatedField( + properties: MutableSequence["Property"] = proto.RepeatedField( proto.MESSAGE, number=9, message="Property", @@ -540,23 +542,23 @@ class LocalizedObjectAnnotation(proto.Message): This must be populated. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=5, message=geometry.BoundingPoly, @@ -592,27 +594,27 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult = proto.Field( + adult: "Likelihood" = proto.Field( proto.ENUM, number=1, enum="Likelihood", ) - spoof = proto.Field( + spoof: "Likelihood" = proto.Field( proto.ENUM, number=2, enum="Likelihood", ) - medical = proto.Field( + medical: "Likelihood" = proto.Field( proto.ENUM, number=3, enum="Likelihood", ) - violence = proto.Field( + violence: "Likelihood" = proto.Field( proto.ENUM, number=4, enum="Likelihood", ) - racy = proto.Field( + racy: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", @@ -629,12 +631,12 @@ class LatLongRect(proto.Message): Max lat/long pair. """ - min_lat_lng = proto.Field( + min_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, ) - max_lat_lng = proto.Field( + max_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=2, message=latlng_pb2.LatLng, @@ -655,16 +657,16 @@ class ColorInfo(proto.Message): Value in range [0, 1]. """ - color = proto.Field( + color: color_pb2.Color = proto.Field( proto.MESSAGE, number=1, message=color_pb2.Color, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - pixel_fraction = proto.Field( + pixel_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -674,12 +676,12 @@ class DominantColorsAnnotation(proto.Message): r"""Set of dominant colors and their corresponding scores. Attributes: - colors (Sequence[google.cloud.vision_v1p3beta1.types.ColorInfo]): + colors (MutableSequence[google.cloud.vision_v1p3beta1.types.ColorInfo]): RGB color values with their score and pixel fraction. """ - colors = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ColorInfo", @@ -695,7 +697,7 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, message="DominantColorsAnnotation", @@ -718,16 +720,16 @@ class CropHint(proto.Message): with respect to the original image. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) - importance_fraction = proto.Field( + importance_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -738,11 +740,11 @@ class CropHintsAnnotation(proto.Message): serving images. Attributes: - crop_hints (Sequence[google.cloud.vision_v1p3beta1.types.CropHint]): + crop_hints (MutableSequence[google.cloud.vision_v1p3beta1.types.CropHint]): Crop hint results. """ - crop_hints = proto.RepeatedField( + crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( proto.MESSAGE, number=1, message="CropHint", @@ -753,7 +755,7 @@ class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. Attributes: - aspect_ratios (Sequence[float]): + aspect_ratios (MutableSequence[float]): Aspect ratios in floats, representing the ratio of the width to the height of the image. For example, if the desired aspect ratio is 4/3, @@ -764,7 +766,7 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField( + aspect_ratios: MutableSequence[float] = proto.RepeatedField( proto.FLOAT, number=1, ) @@ -779,7 +781,7 @@ class WebDetectionParams(proto.Message): geo information in the image. """ - include_geo_results = proto.Field( + include_geo_results: bool = proto.Field( proto.BOOL, number=2, ) @@ -794,16 +796,16 @@ class TextDetectionParams(proto.Message): By default, Cloud Vision API only includes confidence score for DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence score for TEXT_DETECTION as well. - advanced_ocr_options (Sequence[str]): + advanced_ocr_options (MutableSequence[str]): A list of advanced OCR options to fine-tune OCR behavior. """ - enable_text_detection_confidence_score = proto.Field( + enable_text_detection_confidence_score: bool = proto.Field( proto.BOOL, number=9, ) - advanced_ocr_options = proto.RepeatedField( + advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=11, ) @@ -815,7 +817,7 @@ class ImageContext(proto.Message): Attributes: lat_long_rect (google.cloud.vision_v1p3beta1.types.LatLongRect): Not used. - language_hints (Sequence[str]): + language_hints (MutableSequence[str]): List of languages to use for TEXT_DETECTION. In most cases, an empty value yields the best results since it enables automatic language detection. For languages based on the @@ -837,31 +839,31 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect = proto.Field( + lat_long_rect: "LatLongRect" = proto.Field( proto.MESSAGE, number=1, message="LatLongRect", ) - language_hints = proto.RepeatedField( + language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params = proto.Field( + crop_hints_params: "CropHintsParams" = proto.Field( proto.MESSAGE, number=4, message="CropHintsParams", ) - product_search_params = proto.Field( + product_search_params: product_search.ProductSearchParams = proto.Field( proto.MESSAGE, number=5, message=product_search.ProductSearchParams, ) - web_detection_params = proto.Field( + web_detection_params: "WebDetectionParams" = proto.Field( proto.MESSAGE, number=6, message="WebDetectionParams", ) - text_detection_params = proto.Field( + text_detection_params: "TextDetectionParams" = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", @@ -875,24 +877,24 @@ class AnnotateImageRequest(proto.Message): Attributes: image (google.cloud.vision_v1p3beta1.types.Image): The image to be processed. - features (Sequence[google.cloud.vision_v1p3beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p3beta1.types.Feature]): Requested features. image_context (google.cloud.vision_v1p3beta1.types.ImageContext): Additional context that may accompany the image. """ - image = proto.Field( + image: "Image" = proto.Field( proto.MESSAGE, number=1, message="Image", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", @@ -913,11 +915,11 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) - page_number = proto.Field( + page_number: int = proto.Field( proto.INT32, number=2, ) @@ -927,23 +929,23 @@ class AnnotateImageResponse(proto.Message): r"""Response to an image annotation request. Attributes: - face_annotations (Sequence[google.cloud.vision_v1p3beta1.types.FaceAnnotation]): + face_annotations (MutableSequence[google.cloud.vision_v1p3beta1.types.FaceAnnotation]): If present, face detection has completed successfully. - landmark_annotations (Sequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): + landmark_annotations (MutableSequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): If present, landmark detection has completed successfully. - logo_annotations (Sequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): + logo_annotations (MutableSequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): If present, logo detection has completed successfully. - label_annotations (Sequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): + label_annotations (MutableSequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): If present, label detection has completed successfully. - localized_object_annotations (Sequence[google.cloud.vision_v1p3beta1.types.LocalizedObjectAnnotation]): + localized_object_annotations (MutableSequence[google.cloud.vision_v1p3beta1.types.LocalizedObjectAnnotation]): If present, localized object detection has completed successfully. This will be sorted descending by confidence score. - text_annotations (Sequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): + text_annotations (MutableSequence[google.cloud.vision_v1p3beta1.types.EntityAnnotation]): If present, text (OCR) detection has completed successfully. full_text_annotation (google.cloud.vision_v1p3beta1.types.TextAnnotation): @@ -975,72 +977,74 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations = proto.RepeatedField( + face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FaceAnnotation", ) - landmark_annotations = proto.RepeatedField( + landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityAnnotation", ) - logo_annotations = proto.RepeatedField( + logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=3, message="EntityAnnotation", ) - label_annotations = proto.RepeatedField( + label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=4, message="EntityAnnotation", ) - localized_object_annotations = proto.RepeatedField( + localized_object_annotations: MutableSequence[ + "LocalizedObjectAnnotation" + ] = proto.RepeatedField( proto.MESSAGE, number=22, message="LocalizedObjectAnnotation", ) - text_annotations = proto.RepeatedField( + text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=5, message="EntityAnnotation", ) - full_text_annotation = proto.Field( + full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation = proto.Field( + safe_search_annotation: "SafeSearchAnnotation" = proto.Field( proto.MESSAGE, number=6, message="SafeSearchAnnotation", ) - image_properties_annotation = proto.Field( + image_properties_annotation: "ImageProperties" = proto.Field( proto.MESSAGE, number=8, message="ImageProperties", ) - crop_hints_annotation = proto.Field( + crop_hints_annotation: "CropHintsAnnotation" = proto.Field( proto.MESSAGE, number=11, message="CropHintsAnnotation", ) - web_detection = proto.Field( + web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, ) - product_search_results = proto.Field( + product_search_results: product_search.ProductSearchResults = proto.Field( proto.MESSAGE, number=14, message=product_search.ProductSearchResults, ) - error = proto.Field( + error: status_pb2.Status = proto.Field( proto.MESSAGE, number=9, message=status_pb2.Status, ) - context = proto.Field( + context: "ImageAnnotationContext" = proto.Field( proto.MESSAGE, number=21, message="ImageAnnotationContext", @@ -1056,17 +1060,17 @@ class AnnotateFileResponse(proto.Message): input_config (google.cloud.vision_v1p3beta1.types.InputConfig): Information about the file for which this response is generated. - responses (Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1p3beta1.types.AnnotateImageResponse]): Individual responses to images found within the file. """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=2, message="AnnotateImageResponse", @@ -1078,12 +1082,12 @@ class BatchAnnotateImagesRequest(proto.Message): service call. Attributes: - requests (Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]): Individual image annotation requests for this batch. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", @@ -1094,12 +1098,12 @@ class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1p3beta1.types.AnnotateImageResponse]): Individual responses to image annotation requests within the batch. """ - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageResponse", @@ -1112,7 +1116,7 @@ class AsyncAnnotateFileRequest(proto.Message): Attributes: input_config (google.cloud.vision_v1p3beta1.types.InputConfig): Required. Information about the input file. - features (Sequence[google.cloud.vision_v1p3beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p3beta1.types.Feature]): Required. Requested features. image_context (google.cloud.vision_v1p3beta1.types.ImageContext): Additional context that may accompany the @@ -1122,22 +1126,22 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", ) - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=4, message="OutputConfig", @@ -1153,7 +1157,7 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, message="OutputConfig", @@ -1165,12 +1169,12 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): single service call. Attributes: - requests (Sequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. """ - requests = proto.RepeatedField( + requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileRequest", @@ -1181,13 +1185,13 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileResponse]): + responses (MutableSequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one for each request in AsyncBatchAnnotateFilesRequest. """ - responses = proto.RepeatedField( + responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileResponse", @@ -1207,12 +1211,12 @@ class InputConfig(proto.Message): supported. Wildcards are not supported. """ - gcs_source = proto.Field( + gcs_source: "GcsSource" = proto.Field( proto.MESSAGE, number=1, message="GcsSource", ) - mime_type = proto.Field( + mime_type: str = proto.Field( proto.STRING, number=2, ) @@ -1239,12 +1243,12 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination = proto.Field( + gcs_destination: "GcsDestination" = proto.Field( proto.MESSAGE, number=1, message="GcsDestination", ) - batch_size = proto.Field( + batch_size: int = proto.Field( proto.INT32, number=2, ) @@ -1261,7 +1265,7 @@ class GcsSource(proto.Message): Wildcards are not currently supported. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1292,7 +1296,7 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1319,17 +1323,17 @@ class State(proto.Enum): DONE = 3 CANCELLED = 4 - state = proto.Field( + state: State = proto.Field( proto.ENUM, number=1, enum=State, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, diff --git a/google/cloud/vision_v1p3beta1/types/product_search.py b/google/cloud/vision_v1p3beta1/types/product_search.py index e1bf62b9..1a888cc8 100644 --- a/google/cloud/vision_v1p3beta1/types/product_search.py +++ b/google/cloud/vision_v1p3beta1/types/product_search.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p3beta1.types import geometry @@ -44,7 +46,7 @@ class ProductSearchParams(proto.Message): Format is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. - product_categories (Sequence[str]): + product_categories (MutableSequence[str]): The list of product categories to search in. Currently, we only consider the first category, and either "homegoods-v2", "apparel-v2", @@ -70,20 +72,20 @@ class ProductSearchParams(proto.Message): instead of an '='. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=9, message=geometry.BoundingPoly, ) - product_set = proto.Field( + product_set: str = proto.Field( proto.STRING, number=6, ) - product_categories = proto.RepeatedField( + product_categories: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=7, ) - filter = proto.Field( + filter: str = proto.Field( proto.STRING, number=8, ) @@ -98,9 +100,9 @@ class ProductSearchResults(proto.Message): results. Products added to the product set and products removed from the product set after this time are not reflected in the current results. - results (Sequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.Result]): + results (MutableSequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.Result]): List of results, one for each product match. - product_grouped_results (Sequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.GroupedResult]): + product_grouped_results (MutableSequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.GroupedResult]): List of results grouped by products detected in the query image. Each entry corresponds to one bounding polygon in the query image, and @@ -123,16 +125,16 @@ class Result(proto.Message): product that is the closest match to the query. """ - product = proto.Field( + product: product_search_service.Product = proto.Field( proto.MESSAGE, number=1, message=product_search_service.Product, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - image = proto.Field( + image: str = proto.Field( proto.STRING, number=3, ) @@ -154,19 +156,19 @@ class ObjectAnnotation(proto.Message): Score of the result. Range [0, 1]. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) @@ -179,40 +181,42 @@ class GroupedResult(proto.Message): bounding_poly (google.cloud.vision_v1p3beta1.types.BoundingPoly): The bounding polygon around the product detected in the query image. - results (Sequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.Result]): + results (MutableSequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.Result]): List of results, one for each product match. - object_annotations (Sequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.ObjectAnnotation]): + object_annotations (MutableSequence[google.cloud.vision_v1p3beta1.types.ProductSearchResults.ObjectAnnotation]): List of generic predictions for the object in the bounding box. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - results = proto.RepeatedField( + results: MutableSequence["ProductSearchResults.Result"] = proto.RepeatedField( proto.MESSAGE, number=2, message="ProductSearchResults.Result", ) - object_annotations = proto.RepeatedField( + object_annotations: MutableSequence[ + "ProductSearchResults.ObjectAnnotation" + ] = proto.RepeatedField( proto.MESSAGE, number=3, message="ProductSearchResults.ObjectAnnotation", ) - index_time = proto.Field( + index_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - results = proto.RepeatedField( + results: MutableSequence[Result] = proto.RepeatedField( proto.MESSAGE, number=5, message=Result, ) - product_grouped_results = proto.RepeatedField( + product_grouped_results: MutableSequence[GroupedResult] = proto.RepeatedField( proto.MESSAGE, number=6, message=GroupedResult, diff --git a/google/cloud/vision_v1p3beta1/types/product_search_service.py b/google/cloud/vision_v1p3beta1/types/product_search_service.py index 3be3dbef..9590d9f9 100644 --- a/google/cloud/vision_v1p3beta1/types/product_search_service.py +++ b/google/cloud/vision_v1p3beta1/types/product_search_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p3beta1.types import geometry @@ -82,7 +84,7 @@ class Product(proto.Message): "toys-v2". The legacy categories "homegoods", "apparel", and "toys" are still supported, but these should not be used for new products. - product_labels (Sequence[google.cloud.vision_v1p3beta1.types.Product.KeyValue]): + product_labels (MutableSequence[google.cloud.vision_v1p3beta1.types.Product.KeyValue]): Key-value pairs that can be attached to a product. At query time, constraints can be specified based on the product_labels. @@ -108,32 +110,32 @@ class KeyValue(proto.Message): bytes. """ - key = proto.Field( + key: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - display_name = proto.Field( + display_name: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - product_category = proto.Field( + product_category: str = proto.Field( proto.STRING, number=4, ) - product_labels = proto.RepeatedField( + product_labels: MutableSequence[KeyValue] = proto.RepeatedField( proto.MESSAGE, number=5, message=KeyValue, @@ -174,20 +176,20 @@ class ProductSet(proto.Message): ProductSet. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - display_name = proto.Field( + display_name: str = proto.Field( proto.STRING, number=2, ) - index_time = proto.Field( + index_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - index_error = proto.Field( + index_error: status_pb2.Status = proto.Field( proto.MESSAGE, number=4, message=status_pb2.Status, @@ -212,7 +214,7 @@ class ReferenceImage(proto.Message): image. The URI must start with ``gs://``. - bounding_polys (Sequence[google.cloud.vision_v1p3beta1.types.BoundingPoly]): + bounding_polys (MutableSequence[google.cloud.vision_v1p3beta1.types.BoundingPoly]): Optional. Bounding polygons around the areas of interest in the reference image. If this field is empty, the system will try to detect @@ -225,15 +227,15 @@ class ReferenceImage(proto.Message): 1:4 or less (i.e. 1:3 is ok; 1:5 is not). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=2, ) - bounding_polys = proto.RepeatedField( + bounding_polys: MutableSequence[geometry.BoundingPoly] = proto.RepeatedField( proto.MESSAGE, number=3, message=geometry.BoundingPoly, @@ -259,16 +261,16 @@ class CreateProductRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: "Product" = proto.Field( proto.MESSAGE, number=2, message="Product", ) - product_id = proto.Field( + product_id: str = proto.Field( proto.STRING, number=3, ) @@ -291,15 +293,15 @@ class ListProductsRequest(proto.Message): if any. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -309,7 +311,7 @@ class ListProductsResponse(proto.Message): r"""Response message for the ``ListProducts`` method. Attributes: - products (Sequence[google.cloud.vision_v1p3beta1.types.Product]): + products (MutableSequence[google.cloud.vision_v1p3beta1.types.Product]): List of products. next_page_token (str): Token to retrieve the next page of results, @@ -321,12 +323,12 @@ class ListProductsResponse(proto.Message): def raw_page(self): return self - products = proto.RepeatedField( + products: MutableSequence["Product"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Product", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -343,7 +345,7 @@ class GetProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -364,12 +366,12 @@ class UpdateProductRequest(proto.Message): ``product_labels``, ``display_name``, and ``description``. """ - product = proto.Field( + product: "Product" = proto.Field( proto.MESSAGE, number=1, message="Product", ) - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, @@ -387,7 +389,7 @@ class DeleteProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -412,16 +414,16 @@ class CreateProductSetRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - product_set = proto.Field( + product_set: "ProductSet" = proto.Field( proto.MESSAGE, number=2, message="ProductSet", ) - product_set_id = proto.Field( + product_set_id: str = proto.Field( proto.STRING, number=3, ) @@ -444,15 +446,15 @@ class ListProductSetsRequest(proto.Message): if any. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -462,7 +464,7 @@ class ListProductSetsResponse(proto.Message): r"""Response message for the ``ListProductSets`` method. Attributes: - product_sets (Sequence[google.cloud.vision_v1p3beta1.types.ProductSet]): + product_sets (MutableSequence[google.cloud.vision_v1p3beta1.types.ProductSet]): List of ProductSets. next_page_token (str): Token to retrieve the next page of results, @@ -474,12 +476,12 @@ class ListProductSetsResponse(proto.Message): def raw_page(self): return self - product_sets = proto.RepeatedField( + product_sets: MutableSequence["ProductSet"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ProductSet", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -496,7 +498,7 @@ class GetProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -516,12 +518,12 @@ class UpdateProductSetRequest(proto.Message): ``display_name``. """ - product_set = proto.Field( + product_set: "ProductSet" = proto.Field( proto.MESSAGE, number=1, message="ProductSet", ) - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, @@ -539,7 +541,7 @@ class DeleteProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -566,16 +568,16 @@ class CreateReferenceImageRequest(proto.Message): characters long. It cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - reference_image = proto.Field( + reference_image: "ReferenceImage" = proto.Field( proto.MESSAGE, number=2, message="ReferenceImage", ) - reference_image_id = proto.Field( + reference_image_id: str = proto.Field( proto.STRING, number=3, ) @@ -602,15 +604,15 @@ class ListReferenceImagesRequest(proto.Message): Defaults to the first page if not specified. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -620,7 +622,7 @@ class ListReferenceImagesResponse(proto.Message): r"""Response message for the ``ListReferenceImages`` method. Attributes: - reference_images (Sequence[google.cloud.vision_v1p3beta1.types.ReferenceImage]): + reference_images (MutableSequence[google.cloud.vision_v1p3beta1.types.ReferenceImage]): The list of reference images. page_size (int): The maximum number of items to return. @@ -634,16 +636,16 @@ class ListReferenceImagesResponse(proto.Message): def raw_page(self): return self - reference_images = proto.RepeatedField( + reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=3, ) @@ -661,7 +663,7 @@ class GetReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -680,7 +682,7 @@ class DeleteReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -703,11 +705,11 @@ class AddProductToProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: str = proto.Field( proto.STRING, number=2, ) @@ -730,11 +732,11 @@ class RemoveProductFromProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: str = proto.Field( proto.STRING, number=2, ) @@ -758,15 +760,15 @@ class ListProductsInProductSetRequest(proto.Message): if any. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -776,7 +778,7 @@ class ListProductsInProductSetResponse(proto.Message): r"""Response message for the ``ListProductsInProductSet`` method. Attributes: - products (Sequence[google.cloud.vision_v1p3beta1.types.Product]): + products (MutableSequence[google.cloud.vision_v1p3beta1.types.Product]): The list of Products. next_page_token (str): Token to retrieve the next page of results, @@ -788,12 +790,12 @@ class ListProductsInProductSetResponse(proto.Message): def raw_page(self): return self - products = proto.RepeatedField( + products: MutableSequence["Product"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Product", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -867,7 +869,7 @@ class ImportProductSetsGcsSource(proto.Message): polygons. """ - csv_file_uri = proto.Field( + csv_file_uri: str = proto.Field( proto.STRING, number=1, ) @@ -887,7 +889,7 @@ class ImportProductSetsInputConfig(proto.Message): This field is a member of `oneof`_ ``source``. """ - gcs_source = proto.Field( + gcs_source: "ImportProductSetsGcsSource" = proto.Field( proto.MESSAGE, number=1, oneof="source", @@ -909,11 +911,11 @@ class ImportProductSetsRequest(proto.Message): requests. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - input_config = proto.Field( + input_config: "ImportProductSetsInputConfig" = proto.Field( proto.MESSAGE, number=2, message="ImportProductSetsInputConfig", @@ -930,9 +932,9 @@ class ImportProductSetsResponse(proto.Message): field. Attributes: - reference_images (Sequence[google.cloud.vision_v1p3beta1.types.ReferenceImage]): + reference_images (MutableSequence[google.cloud.vision_v1p3beta1.types.ReferenceImage]): The list of reference_images that are imported successfully. - statuses (Sequence[google.rpc.status_pb2.Status]): + statuses (MutableSequence[google.rpc.status_pb2.Status]): The rpc status for each ImportProductSet request, including both successes and errors. @@ -942,12 +944,12 @@ class ImportProductSetsResponse(proto.Message): line 0. """ - reference_images = proto.RepeatedField( + reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - statuses = proto.RepeatedField( + statuses: MutableSequence[status_pb2.Status] = proto.RepeatedField( proto.MESSAGE, number=2, message=status_pb2.Status, @@ -983,17 +985,17 @@ class State(proto.Enum): FAILED = 3 CANCELLED = 4 - state = proto.Field( + state: State = proto.Field( proto.ENUM, number=1, enum=State, ) - submit_time = proto.Field( + submit_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - end_time = proto.Field( + end_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, diff --git a/google/cloud/vision_v1p3beta1/types/text_annotation.py b/google/cloud/vision_v1p3beta1/types/text_annotation.py index 16c168a8..aac0c22a 100644 --- a/google/cloud/vision_v1p3beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p3beta1/types/text_annotation.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p3beta1.types import geometry @@ -42,7 +44,7 @@ class TextAnnotation(proto.Message): message definition below for more detail. Attributes: - pages (Sequence[google.cloud.vision_v1p3beta1.types.Page]): + pages (MutableSequence[google.cloud.vision_v1p3beta1.types.Page]): List of pages detected by OCR. text (str): UTF-8 text detected on the pages. @@ -60,11 +62,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=1, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) @@ -88,12 +90,12 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_ = proto.Field( + type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - is_prefix = proto.Field( + is_prefix: bool = proto.Field( proto.BOOL, number=2, ) @@ -102,30 +104,32 @@ class TextProperty(proto.Message): r"""Additional information detected on the structural component. Attributes: - detected_languages (Sequence[google.cloud.vision_v1p3beta1.types.TextAnnotation.DetectedLanguage]): + detected_languages (MutableSequence[google.cloud.vision_v1p3beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with confidence. detected_break (google.cloud.vision_v1p3beta1.types.TextAnnotation.DetectedBreak): Detected start or end of a text segment. """ - detected_languages = proto.RepeatedField( + detected_languages: MutableSequence[ + "TextAnnotation.DetectedLanguage" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", ) - detected_break = proto.Field( + detected_break: "TextAnnotation.DetectedBreak" = proto.Field( proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", ) - pages = proto.RepeatedField( + pages: MutableSequence["Page"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Page", ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=2, ) @@ -143,32 +147,32 @@ class Page(proto.Message): height (int): Page height. For PDFs the unit is points. For images (including TIFFs) the unit is pixels. - blocks (Sequence[google.cloud.vision_v1p3beta1.types.Block]): + blocks (MutableSequence[google.cloud.vision_v1p3beta1.types.Block]): List of blocks of text, images etc on this page. confidence (float): Confidence of the OCR results on the page. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - width = proto.Field( + width: int = proto.Field( proto.INT32, number=2, ) - height = proto.Field( + height: int = proto.Field( proto.INT32, number=3, ) - blocks = proto.RepeatedField( + blocks: MutableSequence["Block"] = proto.RepeatedField( proto.MESSAGE, number=4, message="Block", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -206,7 +210,7 @@ class Block(proto.Message): 1----0 and the vertice order will still be (0, 1, 2, 3). - paragraphs (Sequence[google.cloud.vision_v1p3beta1.types.Paragraph]): + paragraphs (MutableSequence[google.cloud.vision_v1p3beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). block_type (google.cloud.vision_v1p3beta1.types.Block.BlockType): @@ -225,27 +229,27 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs = proto.RepeatedField( + paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Paragraph", ) - block_type = proto.Field( + block_type: BlockType = proto.Field( proto.ENUM, number=4, enum=BlockType, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -271,29 +275,29 @@ class Paragraph(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). - words (Sequence[google.cloud.vision_v1p3beta1.types.Word]): + words (MutableSequence[google.cloud.vision_v1p3beta1.types.Word]): List of words in this paragraph. confidence (float): Confidence of the OCR results for the paragraph. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words = proto.RepeatedField( + words: MutableSequence["Word"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Word", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -317,7 +321,7 @@ class Word(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertice order will still be (0, 1, 2, 3). - symbols (Sequence[google.cloud.vision_v1p3beta1.types.Symbol]): + symbols (MutableSequence[google.cloud.vision_v1p3beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural reading order. @@ -325,22 +329,22 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols = proto.RepeatedField( + symbols: MutableSequence["Symbol"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Symbol", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -372,21 +376,21 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=3, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) diff --git a/google/cloud/vision_v1p3beta1/types/web_detection.py b/google/cloud/vision_v1p3beta1/types/web_detection.py index 0f68e4a7..96713e4f 100644 --- a/google/cloud/vision_v1p3beta1/types/web_detection.py +++ b/google/cloud/vision_v1p3beta1/types/web_detection.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -28,24 +30,24 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. Attributes: - web_entities (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebEntity]): + web_entities (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the Internet. - full_matching_images (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): Fully matching images from the Internet. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): Partial matching images from the Internet. Those images are similar enough to share some key-point features. For example an original image will likely have partial matching for its crops. - pages_with_matching_images (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebPage]): + pages_with_matching_images (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebPage]): Web pages containing the matching images from the Internet. - visually_similar_images (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): + visually_similar_images (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): The visually similar image results. - best_guess_labels (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebLabel]): + best_guess_labels (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebLabel]): Best guess text labels for the request image. """ @@ -64,15 +66,15 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field( + entity_id: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) @@ -88,11 +90,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) @@ -109,10 +111,10 @@ class WebPage(proto.Message): page_title (str): Title for the web page, may contain HTML markups. - full_matching_images (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): Fully matching images on the page. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebImage]): Partial matching images on the page. Those images are similar enough to share some key-point features. For example an original @@ -120,24 +122,28 @@ class WebPage(proto.Message): crops. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - page_title = proto.Field( + page_title: str = proto.Field( proto.STRING, number=3, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=4, message="WebDetection.WebImage", ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=5, message="WebDetection.WebImage", @@ -155,41 +161,41 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field( + label: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - web_entities = proto.RepeatedField( + web_entities: MutableSequence[WebEntity] = proto.RepeatedField( proto.MESSAGE, number=1, message=WebEntity, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=2, message=WebImage, ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=3, message=WebImage, ) - pages_with_matching_images = proto.RepeatedField( + pages_with_matching_images: MutableSequence[WebPage] = proto.RepeatedField( proto.MESSAGE, number=4, message=WebPage, ) - visually_similar_images = proto.RepeatedField( + visually_similar_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=6, message=WebImage, ) - best_guess_labels = proto.RepeatedField( + best_guess_labels: MutableSequence[WebLabel] = proto.RepeatedField( proto.MESSAGE, number=8, message=WebLabel, diff --git a/google/cloud/vision_v1p4beta1/__init__.py b/google/cloud/vision_v1p4beta1/__init__.py index 74f09c5f..0d16eca7 100644 --- a/google/cloud/vision_v1p4beta1/__init__.py +++ b/google/cloud/vision_v1p4beta1/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.vision import gapic_version as package_version + +__version__ = package_version.__version__ + from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers diff --git a/google/cloud/vision_v1p4beta1/gapic_metadata.json b/google/cloud/vision_v1p4beta1/gapic_metadata.json new file mode 100644 index 00000000..bc41c344 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/gapic_metadata.json @@ -0,0 +1,267 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.vision_v1p4beta1", + "protoPackage": "google.cloud.vision.v1p4beta1", + "schema": "1.0", + "services": { + "ImageAnnotator": { + "clients": { + "grpc": { + "libraryClient": "ImageAnnotatorClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "AsyncBatchAnnotateImages": { + "methods": [ + "async_batch_annotate_images" + ] + }, + "BatchAnnotateFiles": { + "methods": [ + "batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ImageAnnotatorAsyncClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "async_batch_annotate_files" + ] + }, + "AsyncBatchAnnotateImages": { + "methods": [ + "async_batch_annotate_images" + ] + }, + "BatchAnnotateFiles": { + "methods": [ + "batch_annotate_files" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "batch_annotate_images" + ] + } + } + } + } + }, + "ProductSearch": { + "clients": { + "grpc": { + "libraryClient": "ProductSearchClient", + "rpcs": { + "AddProductToProductSet": { + "methods": [ + "add_product_to_product_set" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "CreateProductSet": { + "methods": [ + "create_product_set" + ] + }, + "CreateReferenceImage": { + "methods": [ + "create_reference_image" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "DeleteProductSet": { + "methods": [ + "delete_product_set" + ] + }, + "DeleteReferenceImage": { + "methods": [ + "delete_reference_image" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "GetProductSet": { + "methods": [ + "get_product_set" + ] + }, + "GetReferenceImage": { + "methods": [ + "get_reference_image" + ] + }, + "ImportProductSets": { + "methods": [ + "import_product_sets" + ] + }, + "ListProductSets": { + "methods": [ + "list_product_sets" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "ListProductsInProductSet": { + "methods": [ + "list_products_in_product_set" + ] + }, + "ListReferenceImages": { + "methods": [ + "list_reference_images" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveProductFromProductSet": { + "methods": [ + "remove_product_from_product_set" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + }, + "UpdateProductSet": { + "methods": [ + "update_product_set" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProductSearchAsyncClient", + "rpcs": { + "AddProductToProductSet": { + "methods": [ + "add_product_to_product_set" + ] + }, + "CreateProduct": { + "methods": [ + "create_product" + ] + }, + "CreateProductSet": { + "methods": [ + "create_product_set" + ] + }, + "CreateReferenceImage": { + "methods": [ + "create_reference_image" + ] + }, + "DeleteProduct": { + "methods": [ + "delete_product" + ] + }, + "DeleteProductSet": { + "methods": [ + "delete_product_set" + ] + }, + "DeleteReferenceImage": { + "methods": [ + "delete_reference_image" + ] + }, + "GetProduct": { + "methods": [ + "get_product" + ] + }, + "GetProductSet": { + "methods": [ + "get_product_set" + ] + }, + "GetReferenceImage": { + "methods": [ + "get_reference_image" + ] + }, + "ImportProductSets": { + "methods": [ + "import_product_sets" + ] + }, + "ListProductSets": { + "methods": [ + "list_product_sets" + ] + }, + "ListProducts": { + "methods": [ + "list_products" + ] + }, + "ListProductsInProductSet": { + "methods": [ + "list_products_in_product_set" + ] + }, + "ListReferenceImages": { + "methods": [ + "list_reference_images" + ] + }, + "PurgeProducts": { + "methods": [ + "purge_products" + ] + }, + "RemoveProductFromProductSet": { + "methods": [ + "remove_product_from_product_set" + ] + }, + "UpdateProduct": { + "methods": [ + "update_product" + ] + }, + "UpdateProductSet": { + "methods": [ + "update_product_set" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/vision_v1p4beta1/gapic_version.py b/google/cloud/vision_v1p4beta1/gapic_version.py new file mode 100644 index 00000000..47c54531 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "3.2.0" # {x-release-please-version} diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py index a470a115..36f99715 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -165,9 +176,9 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -211,11 +222,15 @@ def __init__( async def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -247,10 +262,10 @@ async def sample_batch_annotate_images(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.BatchAnnotateImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.BatchAnnotateImagesRequest, dict]]): The request object. Multiple image annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]`): Required. Individual image annotation requests for this batch. @@ -314,11 +329,13 @@ async def sample_batch_annotate_images(): async def batch_annotate_files( self, - request: Union[image_annotator.BatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateFileRequest] = None, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation @@ -356,10 +373,10 @@ async def sample_batch_annotate_files(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.BatchAnnotateFilesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.BatchAnnotateFilesRequest, dict]]): The request object. A list of requests to annotate files using the BatchAnnotateFiles API. - requests (:class:`Sequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]`): Required. The list of file annotation requests. Right now we support only one AnnotateFileRequest in @@ -423,12 +440,16 @@ async def sample_batch_annotate_files(): async def async_batch_annotate_images( self, - request: Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, - output_config: image_annotator.OutputConfig = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, + output_config: Optional[image_annotator.OutputConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of @@ -468,16 +489,16 @@ async def sample_async_batch_annotate_images(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.AsyncBatchAnnotateImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.AsyncBatchAnnotateImagesRequest, dict]]): The request object. Request for async image annotation for a list of images. - requests (:class:`Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]`): Required. Individual image annotation requests for this batch. @@ -561,11 +582,15 @@ async def sample_async_batch_annotate_images(): async def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Run asynchronous image detection and annotation for a list of @@ -600,16 +625,16 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.AsyncBatchAnnotateFilesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.AsyncBatchAnnotateFilesRequest, dict]]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (:class:`Sequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]`): + requests (:class:`MutableSequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]`): Required. Individual async file annotation requests for this batch. @@ -689,14 +714,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/client.py b/google/cloud/vision_v1p4beta1/services/image_annotator/client.py index a0b64a32..7b5f1aca 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -58,7 +70,7 @@ class ImageAnnotatorClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ImageAnnotatorTransport]: """Returns an appropriate transport class. @@ -361,8 +373,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageAnnotatorTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ImageAnnotatorTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the image annotator client. @@ -376,7 +388,7 @@ def __init__( transport (Union[str, ImageAnnotatorTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -406,6 +418,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -458,11 +471,15 @@ def __init__( def batch_annotate_images( self, - request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateImagesResponse: r"""Run image detection and annotation for a batch of @@ -497,7 +514,7 @@ def sample_batch_annotate_images(): request (Union[google.cloud.vision_v1p4beta1.types.BatchAnnotateImagesRequest, dict]): The request object. Multiple image annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. @@ -557,11 +574,13 @@ def sample_batch_annotate_images(): def batch_annotate_files( self, - request: Union[image_annotator.BatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.BatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateFileRequest] = None, + requests: Optional[MutableSequence[image_annotator.AnnotateFileRequest]] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> image_annotator.BatchAnnotateFilesResponse: r"""Service that performs image detection and annotation @@ -602,7 +621,7 @@ def sample_batch_annotate_files(): request (Union[google.cloud.vision_v1p4beta1.types.BatchAnnotateFilesRequest, dict]): The request object. A list of requests to annotate files using the BatchAnnotateFiles API. - requests (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]): Required. The list of file annotation requests. Right now we support only one AnnotateFileRequest in @@ -662,12 +681,16 @@ def sample_batch_annotate_files(): def async_batch_annotate_images( self, - request: Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateImagesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AnnotateImageRequest] = None, - output_config: image_annotator.OutputConfig = None, + requests: Optional[ + MutableSequence[image_annotator.AnnotateImageRequest] + ] = None, + output_config: Optional[image_annotator.OutputConfig] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of @@ -716,7 +739,7 @@ def sample_async_batch_annotate_images(): request (Union[google.cloud.vision_v1p4beta1.types.AsyncBatchAnnotateImagesRequest, dict]): The request object. Request for async image annotation for a list of images. - requests (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. @@ -798,11 +821,15 @@ def sample_async_batch_annotate_images(): def async_batch_annotate_files( self, - request: Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] = None, + request: Optional[ + Union[image_annotator.AsyncBatchAnnotateFilesRequest, dict] + ] = None, *, - requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + requests: Optional[ + MutableSequence[image_annotator.AsyncAnnotateFileRequest] + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Run asynchronous image detection and annotation for a list of @@ -846,7 +873,7 @@ def sample_async_batch_annotate_files(): request (Union[google.cloud.vision_v1p4beta1.types.AsyncBatchAnnotateFilesRequest, dict]): The request object. Multiple async file annotation requests are batched into a single service call. - requests (Sequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. @@ -931,14 +958,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py index f35e0c71..f64a42be 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1p4beta1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -29,14 +30,9 @@ from google.cloud.vision_v1p4beta1.types import image_annotator from google.longrunning import operations_pb2 # type: ignore -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ImageAnnotatorTransport(abc.ABC): @@ -53,7 +49,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py index ffa8e470..d24429f9 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py @@ -52,14 +52,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -187,8 +187,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py index 0f034a7e..bad7fff8 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py @@ -54,7 +54,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -97,15 +97,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1p4beta1/services/product_search/async_client.py b/google/cloud/vision_v1p4beta1/services/product_search/async_client.py index ec356c39..6e9aa650 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/async_client.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/async_client.py @@ -16,8 +16,19 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions @@ -191,9 +202,9 @@ def transport(self) -> ProductSearchTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ProductSearchTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the product search client. @@ -237,13 +248,15 @@ def __init__( async def create_product_set( self, - request: Union[product_search_service.CreateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductSetRequest, dict] + ] = None, *, - parent: str = None, - product_set: product_search_service.ProductSet = None, - product_set_id: str = None, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. @@ -280,7 +293,7 @@ async def sample_create_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.CreateProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.CreateProductSetRequest, dict]]): The request object. Request message for the `CreateProductSet` method. parent (:class:`str`): @@ -377,11 +390,13 @@ async def sample_create_product_set(): async def list_product_sets( self, - request: Union[product_search_service.ListProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductSetsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductSetsAsyncPager: r"""Lists ProductSets in an unspecified order. @@ -419,7 +434,7 @@ async def sample_list_product_sets(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.ListProductSetsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.ListProductSetsRequest, dict]]): The request object. Request message for the `ListProductSets` method. parent (:class:`str`): @@ -508,11 +523,13 @@ async def sample_list_product_sets(): async def get_product_set( self, - request: Union[product_search_service.GetProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. @@ -548,7 +565,7 @@ async def sample_get_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.GetProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.GetProductSetRequest, dict]]): The request object. Request message for the `GetProductSet` method. name (:class:`str`): @@ -629,12 +646,14 @@ async def sample_get_product_set(): async def update_product_set( self, - request: Union[product_search_service.UpdateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductSetRequest, dict] + ] = None, *, - product_set: product_search_service.ProductSet = None, - update_mask: field_mask_pb2.FieldMask = None, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be @@ -673,7 +692,7 @@ async def sample_update_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.UpdateProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.UpdateProductSetRequest, dict]]): The request object. Request message for the `UpdateProductSet` method. product_set (:class:`google.cloud.vision_v1p4beta1.types.ProductSet`): @@ -762,11 +781,13 @@ async def sample_update_product_set(): async def delete_product_set( self, - request: Union[product_search_service.DeleteProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a ProductSet. Products and @@ -798,7 +819,7 @@ async def sample_delete_product_set(): await client.delete_product_set(request=request) Args: - request (Union[google.cloud.vision_v1p4beta1.types.DeleteProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.DeleteProductSetRequest, dict]]): The request object. Request message for the `DeleteProductSet` method. name (:class:`str`): @@ -867,13 +888,15 @@ async def sample_delete_product_set(): async def create_product( self, - request: Union[product_search_service.CreateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductRequest, dict] + ] = None, *, - parent: str = None, - product: product_search_service.Product = None, - product_id: str = None, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Creates and returns a new product resource. @@ -914,7 +937,7 @@ async def sample_create_product(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.CreateProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.CreateProductRequest, dict]]): The request object. Request message for the `CreateProduct` method. parent (:class:`str`): @@ -1006,11 +1029,13 @@ async def sample_create_product(): async def list_products( self, - request: Union[product_search_service.ListProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsAsyncPager: r"""Lists products in an unspecified order. @@ -1048,7 +1073,7 @@ async def sample_list_products(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.ListProductsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.ListProductsRequest, dict]]): The request object. Request message for the `ListProducts` method. parent (:class:`str`): @@ -1137,11 +1162,11 @@ async def sample_list_products(): async def get_product( self, - request: Union[product_search_service.GetProductRequest, dict] = None, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Gets information associated with a Product. @@ -1177,7 +1202,7 @@ async def sample_get_product(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.GetProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.GetProductRequest, dict]]): The request object. Request message for the `GetProduct` method. name (:class:`str`): @@ -1253,12 +1278,14 @@ async def sample_get_product(): async def update_product( self, - request: Union[product_search_service.UpdateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductRequest, dict] + ] = None, *, - product: product_search_service.Product = None, - update_mask: field_mask_pb2.FieldMask = None, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, @@ -1304,7 +1331,7 @@ async def sample_update_product(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.UpdateProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.UpdateProductRequest, dict]]): The request object. Request message for the `UpdateProduct` method. product (:class:`google.cloud.vision_v1p4beta1.types.Product`): @@ -1390,11 +1417,13 @@ async def sample_update_product(): async def delete_product( self, - request: Union[product_search_service.DeleteProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a product and its reference @@ -1428,7 +1457,7 @@ async def sample_delete_product(): await client.delete_product(request=request) Args: - request (Union[google.cloud.vision_v1p4beta1.types.DeleteProductRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.DeleteProductRequest, dict]]): The request object. Request message for the `DeleteProduct` method. name (:class:`str`): @@ -1497,13 +1526,15 @@ async def sample_delete_product(): async def create_reference_image( self, - request: Union[product_search_service.CreateReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateReferenceImageRequest, dict] + ] = None, *, - parent: str = None, - reference_image: product_search_service.ReferenceImage = None, - reference_image_id: str = None, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. @@ -1560,7 +1591,7 @@ async def sample_create_reference_image(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.CreateReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.CreateReferenceImageRequest, dict]]): The request object. Request message for the `CreateReferenceImage` method. parent (:class:`str`): @@ -1658,11 +1689,13 @@ async def sample_create_reference_image(): async def delete_reference_image( self, - request: Union[product_search_service.DeleteReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a reference image. @@ -1697,7 +1730,7 @@ async def sample_delete_reference_image(): await client.delete_reference_image(request=request) Args: - request (Union[google.cloud.vision_v1p4beta1.types.DeleteReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.DeleteReferenceImageRequest, dict]]): The request object. Request message for the `DeleteReferenceImage` method. name (:class:`str`): @@ -1768,11 +1801,13 @@ async def sample_delete_reference_image(): async def list_reference_images( self, - request: Union[product_search_service.ListReferenceImagesRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListReferenceImagesRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListReferenceImagesAsyncPager: r"""Lists reference images. @@ -1811,7 +1846,7 @@ async def sample_list_reference_images(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.ListReferenceImagesRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.ListReferenceImagesRequest, dict]]): The request object. Request message for the `ListReferenceImages` method. parent (:class:`str`): @@ -1901,11 +1936,13 @@ async def sample_list_reference_images(): async def get_reference_image( self, - request: Union[product_search_service.GetReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. @@ -1941,7 +1978,7 @@ async def sample_get_reference_image(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.GetReferenceImageRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.GetReferenceImageRequest, dict]]): The request object. Request message for the `GetReferenceImage` method. name (:class:`str`): @@ -2021,14 +2058,14 @@ async def sample_get_reference_image(): async def add_product_to_product_set( self, - request: Union[ - product_search_service.AddProductToProductSetRequest, dict + request: Optional[ + Union[product_search_service.AddProductToProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is @@ -2066,7 +2103,7 @@ async def sample_add_product_to_product_set(): await client.add_product_to_product_set(request=request) Args: - request (Union[google.cloud.vision_v1p4beta1.types.AddProductToProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.AddProductToProductSetRequest, dict]]): The request object. Request message for the `AddProductToProductSet` method. name (:class:`str`): @@ -2145,14 +2182,14 @@ async def sample_add_product_to_product_set(): async def remove_product_from_product_set( self, - request: Union[ - product_search_service.RemoveProductFromProductSetRequest, dict + request: Optional[ + Union[product_search_service.RemoveProductFromProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Removes a Product from the specified ProductSet. @@ -2182,7 +2219,7 @@ async def sample_remove_product_from_product_set(): await client.remove_product_from_product_set(request=request) Args: - request (Union[google.cloud.vision_v1p4beta1.types.RemoveProductFromProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.RemoveProductFromProductSetRequest, dict]]): The request object. Request message for the `RemoveProductFromProductSet` method. name (:class:`str`): @@ -2261,13 +2298,13 @@ async def sample_remove_product_from_product_set(): async def list_products_in_product_set( self, - request: Union[ - product_search_service.ListProductsInProductSetRequest, dict + request: Optional[ + Union[product_search_service.ListProductsInProductSetRequest, dict] ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsInProductSetAsyncPager: r"""Lists the Products in a ProductSet, in an unspecified order. If @@ -2307,7 +2344,7 @@ async def sample_list_products_in_product_set(): print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.ListProductsInProductSetRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.ListProductsInProductSetRequest, dict]]): The request object. Request message for the `ListProductsInProductSet` method. name (:class:`str`): @@ -2398,12 +2435,16 @@ async def sample_list_products_in_product_set(): async def import_product_sets( self, - request: Union[product_search_service.ImportProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ImportProductSetsRequest, dict] + ] = None, *, - parent: str = None, - input_config: product_search_service.ImportProductSetsInputConfig = None, + parent: Optional[str] = None, + input_config: Optional[ + product_search_service.ImportProductSetsInputConfig + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Asynchronous API that imports a list of reference images to @@ -2444,13 +2485,13 @@ async def sample_import_product_sets(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.ImportProductSetsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.ImportProductSetsRequest, dict]]): The request object. Request message for the `ImportProductSets` method. parent (:class:`str`): @@ -2551,11 +2592,13 @@ async def sample_import_product_sets(): async def purge_products( self, - request: Union[product_search_service.PurgeProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.PurgeProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Asynchronous API to delete all Products in a ProductSet or all @@ -2611,13 +2654,13 @@ async def sample_purge_products(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.vision_v1p4beta1.types.PurgeProductsRequest, dict]): + request (Optional[Union[google.cloud.vision_v1p4beta1.types.PurgeProductsRequest, dict]]): The request object. Request message for the `PurgeProducts` method. parent (:class:`str`): @@ -2708,14 +2751,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ProductSearchAsyncClient",) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/client.py b/google/cloud/vision_v1p4beta1/services/product_search/client.py index e46e131e..a6ceedc6 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/client.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/client.py @@ -16,8 +16,20 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union -import pkg_resources +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +from google.cloud.vision_v1p4beta1 import gapic_version as package_version from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -62,7 +74,7 @@ class ProductSearchClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[ProductSearchTransport]: """Returns an appropriate transport class. @@ -405,8 +417,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProductSearchTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, ProductSearchTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the product search client. @@ -420,7 +432,7 @@ def __init__( transport (Union[str, ProductSearchTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -450,6 +462,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -502,13 +515,15 @@ def __init__( def create_product_set( self, - request: Union[product_search_service.CreateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductSetRequest, dict] + ] = None, *, - parent: str = None, - product_set: product_search_service.ProductSet = None, - product_set_id: str = None, + parent: Optional[str] = None, + product_set: Optional[product_search_service.ProductSet] = None, + product_set_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Creates and returns a new ProductSet resource. @@ -635,11 +650,13 @@ def sample_create_product_set(): def list_product_sets( self, - request: Union[product_search_service.ListProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductSetsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductSetsPager: r"""Lists ProductSets in an unspecified order. @@ -756,11 +773,13 @@ def sample_list_product_sets(): def get_product_set( self, - request: Union[product_search_service.GetProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Gets information associated with a ProductSet. @@ -867,12 +886,14 @@ def sample_get_product_set(): def update_product_set( self, - request: Union[product_search_service.UpdateProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductSetRequest, dict] + ] = None, *, - product_set: product_search_service.ProductSet = None, - update_mask: field_mask_pb2.FieldMask = None, + product_set: Optional[product_search_service.ProductSet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ProductSet: r"""Makes changes to a ProductSet resource. Only display_name can be @@ -993,11 +1014,13 @@ def sample_update_product_set(): def delete_product_set( self, - request: Union[product_search_service.DeleteProductSetRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductSetRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a ProductSet. Products and @@ -1088,13 +1111,15 @@ def sample_delete_product_set(): def create_product( self, - request: Union[product_search_service.CreateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateProductRequest, dict] + ] = None, *, - parent: str = None, - product: product_search_service.Product = None, - product_id: str = None, + parent: Optional[str] = None, + product: Optional[product_search_service.Product] = None, + product_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Creates and returns a new product resource. @@ -1220,11 +1245,13 @@ def sample_create_product(): def list_products( self, - request: Union[product_search_service.ListProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsPager: r"""Lists products in an unspecified order. @@ -1341,11 +1368,11 @@ def sample_list_products(): def get_product( self, - request: Union[product_search_service.GetProductRequest, dict] = None, + request: Optional[Union[product_search_service.GetProductRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Gets information associated with a Product. @@ -1447,12 +1474,14 @@ def sample_get_product(): def update_product( self, - request: Union[product_search_service.UpdateProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.UpdateProductRequest, dict] + ] = None, *, - product: product_search_service.Product = None, - update_mask: field_mask_pb2.FieldMask = None, + product: Optional[product_search_service.Product] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.Product: r"""Makes changes to a Product resource. Only the ``display_name``, @@ -1577,11 +1606,13 @@ def sample_update_product(): def delete_product( self, - request: Union[product_search_service.DeleteProductRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteProductRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a product and its reference @@ -1674,13 +1705,15 @@ def sample_delete_product(): def create_reference_image( self, - request: Union[product_search_service.CreateReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.CreateReferenceImageRequest, dict] + ] = None, *, - parent: str = None, - reference_image: product_search_service.ReferenceImage = None, - reference_image_id: str = None, + parent: Optional[str] = None, + reference_image: Optional[product_search_service.ReferenceImage] = None, + reference_image_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Creates and returns a new ReferenceImage resource. @@ -1828,11 +1861,13 @@ def sample_create_reference_image(): def delete_reference_image( self, - request: Union[product_search_service.DeleteReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.DeleteReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Permanently deletes a reference image. @@ -1928,11 +1963,13 @@ def sample_delete_reference_image(): def list_reference_images( self, - request: Union[product_search_service.ListReferenceImagesRequest, dict] = None, + request: Optional[ + Union[product_search_service.ListReferenceImagesRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListReferenceImagesPager: r"""Lists reference images. @@ -2051,11 +2088,13 @@ def sample_list_reference_images(): def get_reference_image( self, - request: Union[product_search_service.GetReferenceImageRequest, dict] = None, + request: Optional[ + Union[product_search_service.GetReferenceImageRequest, dict] + ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> product_search_service.ReferenceImage: r"""Gets information associated with a ReferenceImage. @@ -2161,14 +2200,14 @@ def sample_get_reference_image(): def add_product_to_product_set( self, - request: Union[ - product_search_service.AddProductToProductSetRequest, dict + request: Optional[ + Union[product_search_service.AddProductToProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Adds a Product to the specified ProductSet. If the Product is @@ -2282,14 +2321,14 @@ def sample_add_product_to_product_set(): def remove_product_from_product_set( self, - request: Union[ - product_search_service.RemoveProductFromProductSetRequest, dict + request: Optional[ + Union[product_search_service.RemoveProductFromProductSetRequest, dict] ] = None, *, - name: str = None, - product: str = None, + name: Optional[str] = None, + product: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Removes a Product from the specified ProductSet. @@ -2395,13 +2434,13 @@ def sample_remove_product_from_product_set(): def list_products_in_product_set( self, - request: Union[ - product_search_service.ListProductsInProductSetRequest, dict + request: Optional[ + Union[product_search_service.ListProductsInProductSetRequest, dict] ] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListProductsInProductSetPager: r"""Lists the Products in a ProductSet, in an unspecified order. If @@ -2526,12 +2565,16 @@ def sample_list_products_in_product_set(): def import_product_sets( self, - request: Union[product_search_service.ImportProductSetsRequest, dict] = None, + request: Optional[ + Union[product_search_service.ImportProductSetsRequest, dict] + ] = None, *, - parent: str = None, - input_config: product_search_service.ImportProductSetsInputConfig = None, + parent: Optional[str] = None, + input_config: Optional[ + product_search_service.ImportProductSetsInputConfig + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Asynchronous API that imports a list of reference images to @@ -2672,11 +2715,13 @@ def sample_import_product_sets(): def purge_products( self, - request: Union[product_search_service.PurgeProductsRequest, dict] = None, + request: Optional[ + Union[product_search_service.PurgeProductsRequest, dict] + ] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Asynchronous API to delete all Products in a ProductSet or all @@ -2836,14 +2881,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("ProductSearchClient",) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py index 5294b1b5..bc549ca1 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py @@ -15,7 +15,8 @@ # import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -import pkg_resources + +from google.cloud.vision_v1p4beta1 import gapic_version as package_version import google.auth # type: ignore import google.api_core @@ -30,14 +31,9 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-vision", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class ProductSearchTransport(abc.ABC): @@ -54,7 +50,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py index 248acbd1..95fa8bd6 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py @@ -69,14 +69,14 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, @@ -204,8 +204,8 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py index a3f53fb6..2a795bb0 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py @@ -71,7 +71,7 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -114,15 +114,15 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, api_audience: Optional[str] = None, diff --git a/google/cloud/vision_v1p4beta1/types/face.py b/google/cloud/vision_v1p4beta1/types/face.py index bda1f4bf..76d58cf5 100644 --- a/google/cloud/vision_v1p4beta1/types/face.py +++ b/google/cloud/vision_v1p4beta1/types/face.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -30,7 +32,7 @@ class FaceRecognitionParams(proto.Message): r"""Parameters for a celebrity recognition request. Attributes: - celebrity_set (Sequence[str]): + celebrity_set (MutableSequence[str]): The resource names for one or more [CelebritySet][google.cloud.vision.v1p4beta1.CelebritySet]s. A celebrity set is preloaded and can be specified as @@ -39,7 +41,7 @@ class FaceRecognitionParams(proto.Message): Celebrities in the CelebritySets. """ - celebrity_set = proto.RepeatedField( + celebrity_set: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) @@ -58,15 +60,15 @@ class Celebrity(proto.Message): The Celebrity's description. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - display_name = proto.Field( + display_name: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) @@ -83,12 +85,12 @@ class FaceRecognitionResult(proto.Message): Recognition confidence. Range [0, 1]. """ - celebrity = proto.Field( + celebrity: "Celebrity" = proto.Field( proto.MESSAGE, number=1, message="Celebrity", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) diff --git a/google/cloud/vision_v1p4beta1/types/geometry.py b/google/cloud/vision_v1p4beta1/types/geometry.py index 85607d4a..5d72b28e 100644 --- a/google/cloud/vision_v1p4beta1/types/geometry.py +++ b/google/cloud/vision_v1p4beta1/types/geometry.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -39,11 +41,11 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: int = proto.Field( proto.INT32, number=1, ) - y = proto.Field( + y: int = proto.Field( proto.INT32, number=2, ) @@ -61,11 +63,11 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) @@ -75,18 +77,18 @@ class BoundingPoly(proto.Message): r"""A bounding polygon for the detected image annotation. Attributes: - vertices (Sequence[google.cloud.vision_v1p4beta1.types.Vertex]): + vertices (MutableSequence[google.cloud.vision_v1p4beta1.types.Vertex]): The bounding polygon vertices. - normalized_vertices (Sequence[google.cloud.vision_v1p4beta1.types.NormalizedVertex]): + normalized_vertices (MutableSequence[google.cloud.vision_v1p4beta1.types.NormalizedVertex]): The bounding polygon normalized vertices. """ - vertices = proto.RepeatedField( + vertices: MutableSequence["Vertex"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Vertex", ) - normalized_vertices = proto.RepeatedField( + normalized_vertices: MutableSequence["NormalizedVertex"] = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", @@ -108,15 +110,15 @@ class Position(proto.Message): Z coordinate (or depth). """ - x = proto.Field( + x: float = proto.Field( proto.FLOAT, number=1, ) - y = proto.Field( + y: float = proto.Field( proto.FLOAT, number=2, ) - z = proto.Field( + z: float = proto.Field( proto.FLOAT, number=3, ) diff --git a/google/cloud/vision_v1p4beta1/types/image_annotator.py b/google/cloud/vision_v1p4beta1/types/image_annotator.py index 66d346bf..5b5a557a 100644 --- a/google/cloud/vision_v1p4beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p4beta1/types/image_annotator.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p4beta1.types import face @@ -121,16 +123,16 @@ class Type(proto.Enum): PRODUCT_SEARCH = 12 OBJECT_LOCALIZATION = 19 - type_ = proto.Field( + type_: Type = proto.Field( proto.ENUM, number=1, enum=Type, ) - max_results = proto.Field( + max_results: int = proto.Field( proto.INT32, number=2, ) - model = proto.Field( + model: str = proto.Field( proto.STRING, number=3, ) @@ -171,11 +173,11 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field( + gcs_image_uri: str = proto.Field( proto.STRING, number=1, ) - image_uri = proto.Field( + image_uri: str = proto.Field( proto.STRING, number=2, ) @@ -196,11 +198,11 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field( + content: bytes = proto.Field( proto.BYTES, number=1, ) - source = proto.Field( + source: "ImageSource" = proto.Field( proto.MESSAGE, number=2, message="ImageSource", @@ -228,7 +230,7 @@ class FaceAnnotation(proto.Message): an image. It is not based on the landmarker results, only on the initial face detection, hence the fd (face detection) prefix. - landmarks (Sequence[google.cloud.vision_v1p4beta1.types.FaceAnnotation.Landmark]): + landmarks (MutableSequence[google.cloud.vision_v1p4beta1.types.FaceAnnotation.Landmark]): Detected face landmarks. roll_angle (float): Roll angle, which indicates the amount of @@ -261,7 +263,7 @@ class FaceAnnotation(proto.Message): Blurred likelihood. headwear_likelihood (google.cloud.vision_v1p4beta1.types.Likelihood): Headwear likelihood. - recognition_result (Sequence[google.cloud.vision_v1p4beta1.types.FaceRecognitionResult]): + recognition_result (MutableSequence[google.cloud.vision_v1p4beta1.types.FaceRecognitionResult]): Additional recognition information. Only computed if image_context.face_recognition_params is provided, **and** a match is found to a @@ -324,88 +326,90 @@ class Type(proto.Enum): CHIN_LEFT_GONION = 33 CHIN_RIGHT_GONION = 34 - type_ = proto.Field( + type_: "FaceAnnotation.Landmark.Type" = proto.Field( proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type", ) - position = proto.Field( + position: geometry.Position = proto.Field( proto.MESSAGE, number=4, message=geometry.Position, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - fd_bounding_poly = proto.Field( + fd_bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - landmarks = proto.RepeatedField( + landmarks: MutableSequence[Landmark] = proto.RepeatedField( proto.MESSAGE, number=3, message=Landmark, ) - roll_angle = proto.Field( + roll_angle: float = proto.Field( proto.FLOAT, number=4, ) - pan_angle = proto.Field( + pan_angle: float = proto.Field( proto.FLOAT, number=5, ) - tilt_angle = proto.Field( + tilt_angle: float = proto.Field( proto.FLOAT, number=6, ) - detection_confidence = proto.Field( + detection_confidence: float = proto.Field( proto.FLOAT, number=7, ) - landmarking_confidence = proto.Field( + landmarking_confidence: float = proto.Field( proto.FLOAT, number=8, ) - joy_likelihood = proto.Field( + joy_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", ) - sorrow_likelihood = proto.Field( + sorrow_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=10, enum="Likelihood", ) - anger_likelihood = proto.Field( + anger_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=11, enum="Likelihood", ) - surprise_likelihood = proto.Field( + surprise_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=12, enum="Likelihood", ) - under_exposed_likelihood = proto.Field( + under_exposed_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=13, enum="Likelihood", ) - blurred_likelihood = proto.Field( + blurred_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=14, enum="Likelihood", ) - headwear_likelihood = proto.Field( + headwear_likelihood: "Likelihood" = proto.Field( proto.ENUM, number=15, enum="Likelihood", ) - recognition_result = proto.RepeatedField( + recognition_result: MutableSequence[ + face.FaceRecognitionResult + ] = proto.RepeatedField( proto.MESSAGE, number=16, message=face.FaceRecognitionResult, @@ -420,7 +424,7 @@ class LocationInfo(proto.Message): lat/long location coordinates. """ - lat_lng = proto.Field( + lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, @@ -439,15 +443,15 @@ class Property(proto.Message): Value of numeric properties. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - uint64_value = proto.Field( + uint64_value: int = proto.Field( proto.UINT64, number=3, ) @@ -485,54 +489,54 @@ class EntityAnnotation(proto.Message): bounding_poly (google.cloud.vision_v1p4beta1.types.BoundingPoly): Image region to which this entity belongs. Not produced for ``LABEL_DETECTION`` features. - locations (Sequence[google.cloud.vision_v1p4beta1.types.LocationInfo]): + locations (MutableSequence[google.cloud.vision_v1p4beta1.types.LocationInfo]): The location information for the detected entity. Multiple ``LocationInfo`` elements can be present because one location may indicate the location of the scene in the image, and another location may indicate the location of the place where the image was taken. Location information is usually present for landmarks. - properties (Sequence[google.cloud.vision_v1p4beta1.types.Property]): + properties (MutableSequence[google.cloud.vision_v1p4beta1.types.Property]): Some entities may have optional user-supplied ``Property`` (name/value) fields, such a score or string that qualifies the entity. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - locale = proto.Field( + locale: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) - topicality = proto.Field( + topicality: float = proto.Field( proto.FLOAT, number=6, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=7, message=geometry.BoundingPoly, ) - locations = proto.RepeatedField( + locations: MutableSequence["LocationInfo"] = proto.RepeatedField( proto.MESSAGE, number=8, message="LocationInfo", ) - properties = proto.RepeatedField( + properties: MutableSequence["Property"] = proto.RepeatedField( proto.MESSAGE, number=9, message="Property", @@ -559,23 +563,23 @@ class LocalizedObjectAnnotation(proto.Message): This must be populated. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=5, message=geometry.BoundingPoly, @@ -611,27 +615,27 @@ class SafeSearchAnnotation(proto.Message): body areas. """ - adult = proto.Field( + adult: "Likelihood" = proto.Field( proto.ENUM, number=1, enum="Likelihood", ) - spoof = proto.Field( + spoof: "Likelihood" = proto.Field( proto.ENUM, number=2, enum="Likelihood", ) - medical = proto.Field( + medical: "Likelihood" = proto.Field( proto.ENUM, number=3, enum="Likelihood", ) - violence = proto.Field( + violence: "Likelihood" = proto.Field( proto.ENUM, number=4, enum="Likelihood", ) - racy = proto.Field( + racy: "Likelihood" = proto.Field( proto.ENUM, number=9, enum="Likelihood", @@ -648,12 +652,12 @@ class LatLongRect(proto.Message): Max lat/long pair. """ - min_lat_lng = proto.Field( + min_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=1, message=latlng_pb2.LatLng, ) - max_lat_lng = proto.Field( + max_lat_lng: latlng_pb2.LatLng = proto.Field( proto.MESSAGE, number=2, message=latlng_pb2.LatLng, @@ -674,16 +678,16 @@ class ColorInfo(proto.Message): Value in range [0, 1]. """ - color = proto.Field( + color: color_pb2.Color = proto.Field( proto.MESSAGE, number=1, message=color_pb2.Color, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - pixel_fraction = proto.Field( + pixel_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -693,12 +697,12 @@ class DominantColorsAnnotation(proto.Message): r"""Set of dominant colors and their corresponding scores. Attributes: - colors (Sequence[google.cloud.vision_v1p4beta1.types.ColorInfo]): + colors (MutableSequence[google.cloud.vision_v1p4beta1.types.ColorInfo]): RGB color values with their score and pixel fraction. """ - colors = proto.RepeatedField( + colors: MutableSequence["ColorInfo"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ColorInfo", @@ -714,7 +718,7 @@ class ImageProperties(proto.Message): successfully. """ - dominant_colors = proto.Field( + dominant_colors: "DominantColorsAnnotation" = proto.Field( proto.MESSAGE, number=1, message="DominantColorsAnnotation", @@ -737,16 +741,16 @@ class CropHint(proto.Message): with respect to the original image. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) - importance_fraction = proto.Field( + importance_fraction: float = proto.Field( proto.FLOAT, number=3, ) @@ -757,11 +761,11 @@ class CropHintsAnnotation(proto.Message): serving images. Attributes: - crop_hints (Sequence[google.cloud.vision_v1p4beta1.types.CropHint]): + crop_hints (MutableSequence[google.cloud.vision_v1p4beta1.types.CropHint]): Crop hint results. """ - crop_hints = proto.RepeatedField( + crop_hints: MutableSequence["CropHint"] = proto.RepeatedField( proto.MESSAGE, number=1, message="CropHint", @@ -772,7 +776,7 @@ class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. Attributes: - aspect_ratios (Sequence[float]): + aspect_ratios (MutableSequence[float]): Aspect ratios in floats, representing the ratio of the width to the height of the image. For example, if the desired aspect ratio is 4/3, @@ -783,7 +787,7 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField( + aspect_ratios: MutableSequence[float] = proto.RepeatedField( proto.FLOAT, number=1, ) @@ -798,7 +802,7 @@ class WebDetectionParams(proto.Message): geo information in the image. """ - include_geo_results = proto.Field( + include_geo_results: bool = proto.Field( proto.BOOL, number=2, ) @@ -813,16 +817,16 @@ class TextDetectionParams(proto.Message): By default, Cloud Vision API only includes confidence score for DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence score for TEXT_DETECTION as well. - advanced_ocr_options (Sequence[str]): + advanced_ocr_options (MutableSequence[str]): A list of advanced OCR options to fine-tune OCR behavior. """ - enable_text_detection_confidence_score = proto.Field( + enable_text_detection_confidence_score: bool = proto.Field( proto.BOOL, number=9, ) - advanced_ocr_options = proto.RepeatedField( + advanced_ocr_options: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=11, ) @@ -834,7 +838,7 @@ class ImageContext(proto.Message): Attributes: lat_long_rect (google.cloud.vision_v1p4beta1.types.LatLongRect): Not used. - language_hints (Sequence[str]): + language_hints (MutableSequence[str]): List of languages to use for TEXT_DETECTION. In most cases, an empty value yields the best results since it enables automatic language detection. For languages based on the @@ -858,36 +862,36 @@ class ImageContext(proto.Message): text detection. """ - lat_long_rect = proto.Field( + lat_long_rect: "LatLongRect" = proto.Field( proto.MESSAGE, number=1, message="LatLongRect", ) - language_hints = proto.RepeatedField( + language_hints: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - crop_hints_params = proto.Field( + crop_hints_params: "CropHintsParams" = proto.Field( proto.MESSAGE, number=4, message="CropHintsParams", ) - face_recognition_params = proto.Field( + face_recognition_params: face.FaceRecognitionParams = proto.Field( proto.MESSAGE, number=10, message=face.FaceRecognitionParams, ) - product_search_params = proto.Field( + product_search_params: product_search.ProductSearchParams = proto.Field( proto.MESSAGE, number=5, message=product_search.ProductSearchParams, ) - web_detection_params = proto.Field( + web_detection_params: "WebDetectionParams" = proto.Field( proto.MESSAGE, number=6, message="WebDetectionParams", ) - text_detection_params = proto.Field( + text_detection_params: "TextDetectionParams" = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", @@ -902,24 +906,24 @@ class AnnotateImageRequest(proto.Message): Attributes: image (google.cloud.vision_v1p4beta1.types.Image): The image to be processed. - features (Sequence[google.cloud.vision_v1p4beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p4beta1.types.Feature]): Requested features. image_context (google.cloud.vision_v1p4beta1.types.ImageContext): Additional context that may accompany the image. """ - image = proto.Field( + image: "Image" = proto.Field( proto.MESSAGE, number=1, message="Image", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", @@ -940,11 +944,11 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) - page_number = proto.Field( + page_number: int = proto.Field( proto.INT32, number=2, ) @@ -954,23 +958,23 @@ class AnnotateImageResponse(proto.Message): r"""Response to an image annotation request. Attributes: - face_annotations (Sequence[google.cloud.vision_v1p4beta1.types.FaceAnnotation]): + face_annotations (MutableSequence[google.cloud.vision_v1p4beta1.types.FaceAnnotation]): If present, face detection has completed successfully. - landmark_annotations (Sequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): + landmark_annotations (MutableSequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): If present, landmark detection has completed successfully. - logo_annotations (Sequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): + logo_annotations (MutableSequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): If present, logo detection has completed successfully. - label_annotations (Sequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): + label_annotations (MutableSequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): If present, label detection has completed successfully. - localized_object_annotations (Sequence[google.cloud.vision_v1p4beta1.types.LocalizedObjectAnnotation]): + localized_object_annotations (MutableSequence[google.cloud.vision_v1p4beta1.types.LocalizedObjectAnnotation]): If present, localized object detection has completed successfully. This will be sorted descending by confidence score. - text_annotations (Sequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): + text_annotations (MutableSequence[google.cloud.vision_v1p4beta1.types.EntityAnnotation]): If present, text (OCR) detection has completed successfully. full_text_annotation (google.cloud.vision_v1p4beta1.types.TextAnnotation): @@ -1002,72 +1006,74 @@ class AnnotateImageResponse(proto.Message): to understand where this image comes from. """ - face_annotations = proto.RepeatedField( + face_annotations: MutableSequence["FaceAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=1, message="FaceAnnotation", ) - landmark_annotations = proto.RepeatedField( + landmark_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityAnnotation", ) - logo_annotations = proto.RepeatedField( + logo_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=3, message="EntityAnnotation", ) - label_annotations = proto.RepeatedField( + label_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=4, message="EntityAnnotation", ) - localized_object_annotations = proto.RepeatedField( + localized_object_annotations: MutableSequence[ + "LocalizedObjectAnnotation" + ] = proto.RepeatedField( proto.MESSAGE, number=22, message="LocalizedObjectAnnotation", ) - text_annotations = proto.RepeatedField( + text_annotations: MutableSequence["EntityAnnotation"] = proto.RepeatedField( proto.MESSAGE, number=5, message="EntityAnnotation", ) - full_text_annotation = proto.Field( + full_text_annotation: text_annotation.TextAnnotation = proto.Field( proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, ) - safe_search_annotation = proto.Field( + safe_search_annotation: "SafeSearchAnnotation" = proto.Field( proto.MESSAGE, number=6, message="SafeSearchAnnotation", ) - image_properties_annotation = proto.Field( + image_properties_annotation: "ImageProperties" = proto.Field( proto.MESSAGE, number=8, message="ImageProperties", ) - crop_hints_annotation = proto.Field( + crop_hints_annotation: "CropHintsAnnotation" = proto.Field( proto.MESSAGE, number=11, message="CropHintsAnnotation", ) - web_detection = proto.Field( + web_detection: gcv_web_detection.WebDetection = proto.Field( proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, ) - product_search_results = proto.Field( + product_search_results: product_search.ProductSearchResults = proto.Field( proto.MESSAGE, number=14, message=product_search.ProductSearchResults, ) - error = proto.Field( + error: status_pb2.Status = proto.Field( proto.MESSAGE, number=9, message=status_pb2.Status, ) - context = proto.Field( + context: "ImageAnnotationContext" = proto.Field( proto.MESSAGE, number=21, message="ImageAnnotationContext", @@ -1079,12 +1085,12 @@ class BatchAnnotateImagesRequest(proto.Message): service call. Attributes: - requests (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", @@ -1095,12 +1101,12 @@ class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageResponse]): Individual responses to image annotation requests within the batch. """ - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageResponse", @@ -1114,12 +1120,12 @@ class AnnotateFileRequest(proto.Message): Attributes: input_config (google.cloud.vision_v1p4beta1.types.InputConfig): Required. Information about the input file. - features (Sequence[google.cloud.vision_v1p4beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p4beta1.types.Feature]): Required. Requested features. image_context (google.cloud.vision_v1p4beta1.types.ImageContext): Additional context that may accompany the image(s) in the file. - pages (Sequence[int]): + pages (MutableSequence[int]): Pages of the file to perform image annotation. Pages starts from 1, we assume the first page of @@ -1137,22 +1143,22 @@ class AnnotateFileRequest(proto.Message): of the file. """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", ) - pages = proto.RepeatedField( + pages: MutableSequence[int] = proto.RepeatedField( proto.INT32, number=4, ) @@ -1167,7 +1173,7 @@ class AnnotateFileResponse(proto.Message): input_config (google.cloud.vision_v1p4beta1.types.InputConfig): Information about the file for which this response is generated. - responses (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageResponse]): + responses (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageResponse]): Individual responses to images found within the file. This field will be empty if the ``error`` field is set. total_pages (int): @@ -1178,21 +1184,21 @@ class AnnotateFileResponse(proto.Message): The ``responses`` field will not be set in this case. """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateImageResponse"] = proto.RepeatedField( proto.MESSAGE, number=2, message="AnnotateImageResponse", ) - total_pages = proto.Field( + total_pages: int = proto.Field( proto.INT32, number=3, ) - error = proto.Field( + error: status_pb2.Status = proto.Field( proto.MESSAGE, number=4, message=status_pb2.Status, @@ -1204,14 +1210,14 @@ class BatchAnnotateFilesRequest(proto.Message): BatchAnnotateFiles API. Attributes: - requests (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]): Required. The list of file annotation requests. Right now we support only one AnnotateFileRequest in BatchAnnotateFilesRequest. """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateFileRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateFileRequest", @@ -1222,14 +1228,14 @@ class BatchAnnotateFilesResponse(proto.Message): r"""A list of file annotation responses. Attributes: - responses (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateFileResponse]): + responses (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateFileResponse]): The list of file annotation responses, each response corresponding to each AnnotateFileRequest in BatchAnnotateFilesRequest. """ - responses = proto.RepeatedField( + responses: MutableSequence["AnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateFileResponse", @@ -1242,7 +1248,7 @@ class AsyncAnnotateFileRequest(proto.Message): Attributes: input_config (google.cloud.vision_v1p4beta1.types.InputConfig): Required. Information about the input file. - features (Sequence[google.cloud.vision_v1p4beta1.types.Feature]): + features (MutableSequence[google.cloud.vision_v1p4beta1.types.Feature]): Required. Requested features. image_context (google.cloud.vision_v1p4beta1.types.ImageContext): Additional context that may accompany the @@ -1252,22 +1258,22 @@ class AsyncAnnotateFileRequest(proto.Message): metadata (e.g. format). """ - input_config = proto.Field( + input_config: "InputConfig" = proto.Field( proto.MESSAGE, number=1, message="InputConfig", ) - features = proto.RepeatedField( + features: MutableSequence["Feature"] = proto.RepeatedField( proto.MESSAGE, number=2, message="Feature", ) - image_context = proto.Field( + image_context: "ImageContext" = proto.Field( proto.MESSAGE, number=3, message="ImageContext", ) - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=4, message="OutputConfig", @@ -1283,7 +1289,7 @@ class AsyncAnnotateFileResponse(proto.Message): AsyncAnnotateFileRequest. """ - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, message="OutputConfig", @@ -1294,7 +1300,7 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): r"""Request for async image annotation for a list of images. Attributes: - requests (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): Required. Individual image annotation requests for this batch. output_config (google.cloud.vision_v1p4beta1.types.OutputConfig): @@ -1302,12 +1308,12 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): metadata (e.g. format). """ - requests = proto.RepeatedField( + requests: MutableSequence["AnnotateImageRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", ) - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=2, message="OutputConfig", @@ -1323,7 +1329,7 @@ class AsyncBatchAnnotateImagesResponse(proto.Message): AsyncBatchAnnotateImagesRequest. """ - output_config = proto.Field( + output_config: "OutputConfig" = proto.Field( proto.MESSAGE, number=1, message="OutputConfig", @@ -1335,12 +1341,12 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): single service call. Attributes: - requests (Sequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]): + requests (MutableSequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]): Required. Individual async file annotation requests for this batch. """ - requests = proto.RepeatedField( + requests: MutableSequence["AsyncAnnotateFileRequest"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileRequest", @@ -1351,13 +1357,13 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. Attributes: - responses (Sequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileResponse]): + responses (MutableSequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one for each request in AsyncBatchAnnotateFilesRequest. """ - responses = proto.RepeatedField( + responses: MutableSequence["AsyncAnnotateFileResponse"] = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileResponse", @@ -1385,16 +1391,16 @@ class InputConfig(proto.Message): are supported. Wildcards are not supported. """ - gcs_source = proto.Field( + gcs_source: "GcsSource" = proto.Field( proto.MESSAGE, number=1, message="GcsSource", ) - content = proto.Field( + content: bytes = proto.Field( proto.BYTES, number=3, ) - mime_type = proto.Field( + mime_type: str = proto.Field( proto.STRING, number=2, ) @@ -1421,12 +1427,12 @@ class OutputConfig(proto.Message): potential future support for other output configurations. """ - gcs_destination = proto.Field( + gcs_destination: "GcsDestination" = proto.Field( proto.MESSAGE, number=1, message="GcsDestination", ) - batch_size = proto.Field( + batch_size: int = proto.Field( proto.INT32, number=2, ) @@ -1443,7 +1449,7 @@ class GcsSource(proto.Message): Wildcards are not currently supported. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1483,7 +1489,7 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) @@ -1510,17 +1516,17 @@ class State(proto.Enum): DONE = 3 CANCELLED = 4 - state = proto.Field( + state: State = proto.Field( proto.ENUM, number=1, enum=State, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, diff --git a/google/cloud/vision_v1p4beta1/types/product_search.py b/google/cloud/vision_v1p4beta1/types/product_search.py index 5f9fe74f..12d1a37c 100644 --- a/google/cloud/vision_v1p4beta1/types/product_search.py +++ b/google/cloud/vision_v1p4beta1/types/product_search.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p4beta1.types import geometry @@ -44,7 +46,7 @@ class ProductSearchParams(proto.Message): Format is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. - product_categories (Sequence[str]): + product_categories (MutableSequence[str]): The list of product categories to search in. Currently, we only consider the first category, and either "homegoods-v2", "apparel-v2", @@ -70,20 +72,20 @@ class ProductSearchParams(proto.Message): instead of an '='. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=9, message=geometry.BoundingPoly, ) - product_set = proto.Field( + product_set: str = proto.Field( proto.STRING, number=6, ) - product_categories = proto.RepeatedField( + product_categories: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=7, ) - filter = proto.Field( + filter: str = proto.Field( proto.STRING, number=8, ) @@ -98,9 +100,9 @@ class ProductSearchResults(proto.Message): results. Products added to the product set and products removed from the product set after this time are not reflected in the current results. - results (Sequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.Result]): + results (MutableSequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.Result]): List of results, one for each product match. - product_grouped_results (Sequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.GroupedResult]): + product_grouped_results (MutableSequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.GroupedResult]): List of results grouped by products detected in the query image. Each entry corresponds to one bounding polygon in the query image, and @@ -123,16 +125,16 @@ class Result(proto.Message): product that is the closest match to the query. """ - product = proto.Field( + product: product_search_service.Product = proto.Field( proto.MESSAGE, number=1, message=product_search_service.Product, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - image = proto.Field( + image: str = proto.Field( proto.STRING, number=3, ) @@ -154,19 +156,19 @@ class ObjectAnnotation(proto.Message): Score of the result. Range [0, 1]. """ - mid = proto.Field( + mid: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=3, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=4, ) @@ -179,40 +181,42 @@ class GroupedResult(proto.Message): bounding_poly (google.cloud.vision_v1p4beta1.types.BoundingPoly): The bounding polygon around the product detected in the query image. - results (Sequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.Result]): + results (MutableSequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.Result]): List of results, one for each product match. - object_annotations (Sequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.ObjectAnnotation]): + object_annotations (MutableSequence[google.cloud.vision_v1p4beta1.types.ProductSearchResults.ObjectAnnotation]): List of generic predictions for the object in the bounding box. """ - bounding_poly = proto.Field( + bounding_poly: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=1, message=geometry.BoundingPoly, ) - results = proto.RepeatedField( + results: MutableSequence["ProductSearchResults.Result"] = proto.RepeatedField( proto.MESSAGE, number=2, message="ProductSearchResults.Result", ) - object_annotations = proto.RepeatedField( + object_annotations: MutableSequence[ + "ProductSearchResults.ObjectAnnotation" + ] = proto.RepeatedField( proto.MESSAGE, number=3, message="ProductSearchResults.ObjectAnnotation", ) - index_time = proto.Field( + index_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - results = proto.RepeatedField( + results: MutableSequence[Result] = proto.RepeatedField( proto.MESSAGE, number=5, message=Result, ) - product_grouped_results = proto.RepeatedField( + product_grouped_results: MutableSequence[GroupedResult] = proto.RepeatedField( proto.MESSAGE, number=6, message=GroupedResult, diff --git a/google/cloud/vision_v1p4beta1/types/product_search_service.py b/google/cloud/vision_v1p4beta1/types/product_search_service.py index ea89fd09..92663457 100644 --- a/google/cloud/vision_v1p4beta1/types/product_search_service.py +++ b/google/cloud/vision_v1p4beta1/types/product_search_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p4beta1.types import geometry @@ -84,7 +86,7 @@ class Product(proto.Message): "toys-v2". The legacy categories "homegoods", "apparel", and "toys" are still supported, but these should not be used for new products. - product_labels (Sequence[google.cloud.vision_v1p4beta1.types.Product.KeyValue]): + product_labels (MutableSequence[google.cloud.vision_v1p4beta1.types.Product.KeyValue]): Key-value pairs that can be attached to a product. At query time, constraints can be specified based on the product_labels. @@ -115,32 +117,32 @@ class KeyValue(proto.Message): bytes. """ - key = proto.Field( + key: str = proto.Field( proto.STRING, number=1, ) - value = proto.Field( + value: str = proto.Field( proto.STRING, number=2, ) - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - display_name = proto.Field( + display_name: str = proto.Field( proto.STRING, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) - product_category = proto.Field( + product_category: str = proto.Field( proto.STRING, number=4, ) - product_labels = proto.RepeatedField( + product_labels: MutableSequence[KeyValue] = proto.RepeatedField( proto.MESSAGE, number=5, message=KeyValue, @@ -182,20 +184,20 @@ class ProductSet(proto.Message): ProductSet. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - display_name = proto.Field( + display_name: str = proto.Field( proto.STRING, number=2, ) - index_time = proto.Field( + index_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - index_error = proto.Field( + index_error: status_pb2.Status = proto.Field( proto.MESSAGE, number=4, message=status_pb2.Status, @@ -220,7 +222,7 @@ class ReferenceImage(proto.Message): image. The URI must start with ``gs://``. - bounding_polys (Sequence[google.cloud.vision_v1p4beta1.types.BoundingPoly]): + bounding_polys (MutableSequence[google.cloud.vision_v1p4beta1.types.BoundingPoly]): Optional. Bounding polygons around the areas of interest in the reference image. If this field is empty, the system will try to detect @@ -233,15 +235,15 @@ class ReferenceImage(proto.Message): 1:4 or less (i.e. 1:3 is ok; 1:5 is not). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=2, ) - bounding_polys = proto.RepeatedField( + bounding_polys: MutableSequence[geometry.BoundingPoly] = proto.RepeatedField( proto.MESSAGE, number=3, message=geometry.BoundingPoly, @@ -267,16 +269,16 @@ class CreateProductRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: "Product" = proto.Field( proto.MESSAGE, number=2, message="Product", ) - product_id = proto.Field( + product_id: str = proto.Field( proto.STRING, number=3, ) @@ -299,15 +301,15 @@ class ListProductsRequest(proto.Message): if any. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -317,7 +319,7 @@ class ListProductsResponse(proto.Message): r"""Response message for the ``ListProducts`` method. Attributes: - products (Sequence[google.cloud.vision_v1p4beta1.types.Product]): + products (MutableSequence[google.cloud.vision_v1p4beta1.types.Product]): List of products. next_page_token (str): Token to retrieve the next page of results, @@ -329,12 +331,12 @@ class ListProductsResponse(proto.Message): def raw_page(self): return self - products = proto.RepeatedField( + products: MutableSequence["Product"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Product", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -351,7 +353,7 @@ class GetProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -372,12 +374,12 @@ class UpdateProductRequest(proto.Message): ``product_labels``, ``display_name``, and ``description``. """ - product = proto.Field( + product: "Product" = proto.Field( proto.MESSAGE, number=1, message="Product", ) - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, @@ -395,7 +397,7 @@ class DeleteProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -420,16 +422,16 @@ class CreateProductSetRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - product_set = proto.Field( + product_set: "ProductSet" = proto.Field( proto.MESSAGE, number=2, message="ProductSet", ) - product_set_id = proto.Field( + product_set_id: str = proto.Field( proto.STRING, number=3, ) @@ -452,15 +454,15 @@ class ListProductSetsRequest(proto.Message): if any. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -470,7 +472,7 @@ class ListProductSetsResponse(proto.Message): r"""Response message for the ``ListProductSets`` method. Attributes: - product_sets (Sequence[google.cloud.vision_v1p4beta1.types.ProductSet]): + product_sets (MutableSequence[google.cloud.vision_v1p4beta1.types.ProductSet]): List of ProductSets. next_page_token (str): Token to retrieve the next page of results, @@ -482,12 +484,12 @@ class ListProductSetsResponse(proto.Message): def raw_page(self): return self - product_sets = proto.RepeatedField( + product_sets: MutableSequence["ProductSet"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ProductSet", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -504,7 +506,7 @@ class GetProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -524,12 +526,12 @@ class UpdateProductSetRequest(proto.Message): ``display_name``. """ - product_set = proto.Field( + product_set: "ProductSet" = proto.Field( proto.MESSAGE, number=1, message="ProductSet", ) - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, @@ -547,7 +549,7 @@ class DeleteProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -574,16 +576,16 @@ class CreateReferenceImageRequest(proto.Message): characters long. It cannot contain the character ``/``. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - reference_image = proto.Field( + reference_image: "ReferenceImage" = proto.Field( proto.MESSAGE, number=2, message="ReferenceImage", ) - reference_image_id = proto.Field( + reference_image_id: str = proto.Field( proto.STRING, number=3, ) @@ -610,15 +612,15 @@ class ListReferenceImagesRequest(proto.Message): Defaults to the first page if not specified. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -628,7 +630,7 @@ class ListReferenceImagesResponse(proto.Message): r"""Response message for the ``ListReferenceImages`` method. Attributes: - reference_images (Sequence[google.cloud.vision_v1p4beta1.types.ReferenceImage]): + reference_images (MutableSequence[google.cloud.vision_v1p4beta1.types.ReferenceImage]): The list of reference images. page_size (int): The maximum number of items to return. @@ -642,16 +644,16 @@ class ListReferenceImagesResponse(proto.Message): def raw_page(self): return self - reference_images = proto.RepeatedField( + reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=3, ) @@ -669,7 +671,7 @@ class GetReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -688,7 +690,7 @@ class DeleteReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -711,11 +713,11 @@ class AddProductToProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: str = proto.Field( proto.STRING, number=2, ) @@ -738,11 +740,11 @@ class RemoveProductFromProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - product = proto.Field( + product: str = proto.Field( proto.STRING, number=2, ) @@ -766,15 +768,15 @@ class ListProductsInProductSetRequest(proto.Message): if any. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) @@ -784,7 +786,7 @@ class ListProductsInProductSetResponse(proto.Message): r"""Response message for the ``ListProductsInProductSet`` method. Attributes: - products (Sequence[google.cloud.vision_v1p4beta1.types.Product]): + products (MutableSequence[google.cloud.vision_v1p4beta1.types.Product]): The list of Products. next_page_token (str): Token to retrieve the next page of results, @@ -796,12 +798,12 @@ class ListProductsInProductSetResponse(proto.Message): def raw_page(self): return self - products = proto.RepeatedField( + products: MutableSequence["Product"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Product", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) @@ -888,7 +890,7 @@ class ImportProductSetsGcsSource(proto.Message): too large to process (larger than 20MP). """ - csv_file_uri = proto.Field( + csv_file_uri: str = proto.Field( proto.STRING, number=1, ) @@ -908,7 +910,7 @@ class ImportProductSetsInputConfig(proto.Message): This field is a member of `oneof`_ ``source``. """ - gcs_source = proto.Field( + gcs_source: "ImportProductSetsGcsSource" = proto.Field( proto.MESSAGE, number=1, oneof="source", @@ -930,11 +932,11 @@ class ImportProductSetsRequest(proto.Message): requests. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - input_config = proto.Field( + input_config: "ImportProductSetsInputConfig" = proto.Field( proto.MESSAGE, number=2, message="ImportProductSetsInputConfig", @@ -951,9 +953,9 @@ class ImportProductSetsResponse(proto.Message): field. Attributes: - reference_images (Sequence[google.cloud.vision_v1p4beta1.types.ReferenceImage]): + reference_images (MutableSequence[google.cloud.vision_v1p4beta1.types.ReferenceImage]): The list of reference_images that are imported successfully. - statuses (Sequence[google.rpc.status_pb2.Status]): + statuses (MutableSequence[google.rpc.status_pb2.Status]): The rpc status for each ImportProductSet request, including both successes and errors. @@ -963,12 +965,12 @@ class ImportProductSetsResponse(proto.Message): line 0. """ - reference_images = proto.RepeatedField( + reference_images: MutableSequence["ReferenceImage"] = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - statuses = proto.RepeatedField( + statuses: MutableSequence[status_pb2.Status] = proto.RepeatedField( proto.MESSAGE, number=2, message=status_pb2.Status, @@ -1004,17 +1006,17 @@ class State(proto.Enum): FAILED = 3 CANCELLED = 4 - state = proto.Field( + state: State = proto.Field( proto.ENUM, number=1, enum=State, ) - submit_time = proto.Field( + submit_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - end_time = proto.Field( + end_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, @@ -1032,7 +1034,7 @@ class ProductSetPurgeConfig(proto.Message): ProductSets, the Product will still be deleted. """ - product_set_id = proto.Field( + product_set_id: str = proto.Field( proto.STRING, number=1, ) @@ -1069,22 +1071,22 @@ class PurgeProductsRequest(proto.Message): value to true to actually perform the purge. """ - product_set_purge_config = proto.Field( + product_set_purge_config: "ProductSetPurgeConfig" = proto.Field( proto.MESSAGE, number=2, oneof="target", message="ProductSetPurgeConfig", ) - delete_orphan_products = proto.Field( + delete_orphan_products: bool = proto.Field( proto.BOOL, number=3, oneof="target", ) - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - force = proto.Field( + force: bool = proto.Field( proto.BOOL, number=4, ) diff --git a/google/cloud/vision_v1p4beta1/types/text_annotation.py b/google/cloud/vision_v1p4beta1/types/text_annotation.py index b111c85f..11c93270 100644 --- a/google/cloud/vision_v1p4beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p4beta1/types/text_annotation.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore from google.cloud.vision_v1p4beta1.types import geometry @@ -42,7 +44,7 @@ class TextAnnotation(proto.Message): message definition below for more detail. Attributes: - pages (Sequence[google.cloud.vision_v1p4beta1.types.Page]): + pages (MutableSequence[google.cloud.vision_v1p4beta1.types.Page]): List of pages detected by OCR. text (str): UTF-8 text detected on the pages. @@ -60,11 +62,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=1, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=2, ) @@ -88,12 +90,12 @@ class BreakType(proto.Enum): HYPHEN = 4 LINE_BREAK = 5 - type_ = proto.Field( + type_: "TextAnnotation.DetectedBreak.BreakType" = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - is_prefix = proto.Field( + is_prefix: bool = proto.Field( proto.BOOL, number=2, ) @@ -102,30 +104,32 @@ class TextProperty(proto.Message): r"""Additional information detected on the structural component. Attributes: - detected_languages (Sequence[google.cloud.vision_v1p4beta1.types.TextAnnotation.DetectedLanguage]): + detected_languages (MutableSequence[google.cloud.vision_v1p4beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with confidence. detected_break (google.cloud.vision_v1p4beta1.types.TextAnnotation.DetectedBreak): Detected start or end of a text segment. """ - detected_languages = proto.RepeatedField( + detected_languages: MutableSequence[ + "TextAnnotation.DetectedLanguage" + ] = proto.RepeatedField( proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", ) - detected_break = proto.Field( + detected_break: "TextAnnotation.DetectedBreak" = proto.Field( proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", ) - pages = proto.RepeatedField( + pages: MutableSequence["Page"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Page", ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=2, ) @@ -143,32 +147,32 @@ class Page(proto.Message): height (int): Page height. For PDFs the unit is points. For images (including TIFFs) the unit is pixels. - blocks (Sequence[google.cloud.vision_v1p4beta1.types.Block]): + blocks (MutableSequence[google.cloud.vision_v1p4beta1.types.Block]): List of blocks of text, images etc on this page. confidence (float): Confidence of the OCR results on the page. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - width = proto.Field( + width: int = proto.Field( proto.INT32, number=2, ) - height = proto.Field( + height: int = proto.Field( proto.INT32, number=3, ) - blocks = proto.RepeatedField( + blocks: MutableSequence["Block"] = proto.RepeatedField( proto.MESSAGE, number=4, message="Block", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -206,7 +210,7 @@ class Block(proto.Message): 1----0 and the vertex order will still be (0, 1, 2, 3). - paragraphs (Sequence[google.cloud.vision_v1p4beta1.types.Paragraph]): + paragraphs (MutableSequence[google.cloud.vision_v1p4beta1.types.Paragraph]): List of paragraphs in this block (if this blocks is of type text). block_type (google.cloud.vision_v1p4beta1.types.Block.BlockType): @@ -225,27 +229,27 @@ class BlockType(proto.Enum): RULER = 4 BARCODE = 5 - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - paragraphs = proto.RepeatedField( + paragraphs: MutableSequence["Paragraph"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Paragraph", ) - block_type = proto.Field( + block_type: BlockType = proto.Field( proto.ENUM, number=4, enum=BlockType, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=5, ) @@ -271,29 +275,29 @@ class Paragraph(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertex order will still be (0, 1, 2, 3). - words (Sequence[google.cloud.vision_v1p4beta1.types.Word]): + words (MutableSequence[google.cloud.vision_v1p4beta1.types.Word]): List of all words in this paragraph. confidence (float): Confidence of the OCR results for the paragraph. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - words = proto.RepeatedField( + words: MutableSequence["Word"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Word", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -317,7 +321,7 @@ class Word(proto.Message): - when it's rotated 180 degrees around the top-left corner it becomes: 2----3 \| \| 1----0 and the vertex order will still be (0, 1, 2, 3). - symbols (Sequence[google.cloud.vision_v1p4beta1.types.Symbol]): + symbols (MutableSequence[google.cloud.vision_v1p4beta1.types.Symbol]): List of symbols in the word. The order of the symbols follows the natural reading order. @@ -325,22 +329,22 @@ class Word(proto.Message): Confidence of the OCR results for the word. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - symbols = proto.RepeatedField( + symbols: MutableSequence["Symbol"] = proto.RepeatedField( proto.MESSAGE, number=3, message="Symbol", ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) @@ -372,21 +376,21 @@ class Symbol(proto.Message): Confidence of the OCR results for the symbol. Range [0, 1]. """ - property = proto.Field( + property: "TextAnnotation.TextProperty" = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - bounding_box = proto.Field( + bounding_box: geometry.BoundingPoly = proto.Field( proto.MESSAGE, number=2, message=geometry.BoundingPoly, ) - text = proto.Field( + text: str = proto.Field( proto.STRING, number=3, ) - confidence = proto.Field( + confidence: float = proto.Field( proto.FLOAT, number=4, ) diff --git a/google/cloud/vision_v1p4beta1/types/web_detection.py b/google/cloud/vision_v1p4beta1/types/web_detection.py index 55d0b826..47b6dd5a 100644 --- a/google/cloud/vision_v1p4beta1/types/web_detection.py +++ b/google/cloud/vision_v1p4beta1/types/web_detection.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + import proto # type: ignore @@ -28,24 +30,24 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. Attributes: - web_entities (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebEntity]): + web_entities (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the Internet. - full_matching_images (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): Fully matching images from the Internet. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): Partial matching images from the Internet. Those images are similar enough to share some key-point features. For example an original image will likely have partial matching for its crops. - pages_with_matching_images (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebPage]): + pages_with_matching_images (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebPage]): Web pages containing the matching images from the Internet. - visually_similar_images (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): + visually_similar_images (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): The visually similar image results. - best_guess_labels (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebLabel]): + best_guess_labels (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebLabel]): The service's best guess as to the topic of the request image. Inferred from similar images on the open web. @@ -66,15 +68,15 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field( + entity_id: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=3, ) @@ -90,11 +92,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) @@ -111,10 +113,10 @@ class WebPage(proto.Message): page_title (str): Title for the web page, may contain HTML markups. - full_matching_images (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): + full_matching_images (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): Fully matching images on the page. Can include resized copies of the query image. - partial_matching_images (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): + partial_matching_images (MutableSequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebImage]): Partial matching images on the page. Those images are similar enough to share some key-point features. For example an original @@ -122,24 +124,28 @@ class WebPage(proto.Message): crops. """ - url = proto.Field( + url: str = proto.Field( proto.STRING, number=1, ) - score = proto.Field( + score: float = proto.Field( proto.FLOAT, number=2, ) - page_title = proto.Field( + page_title: str = proto.Field( proto.STRING, number=3, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=4, message="WebDetection.WebImage", ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[ + "WebDetection.WebImage" + ] = proto.RepeatedField( proto.MESSAGE, number=5, message="WebDetection.WebImage", @@ -157,41 +163,41 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field( + label: str = proto.Field( proto.STRING, number=1, ) - language_code = proto.Field( + language_code: str = proto.Field( proto.STRING, number=2, ) - web_entities = proto.RepeatedField( + web_entities: MutableSequence[WebEntity] = proto.RepeatedField( proto.MESSAGE, number=1, message=WebEntity, ) - full_matching_images = proto.RepeatedField( + full_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=2, message=WebImage, ) - partial_matching_images = proto.RepeatedField( + partial_matching_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=3, message=WebImage, ) - pages_with_matching_images = proto.RepeatedField( + pages_with_matching_images: MutableSequence[WebPage] = proto.RepeatedField( proto.MESSAGE, number=4, message=WebPage, ) - visually_similar_images = proto.RepeatedField( + visually_similar_images: MutableSequence[WebImage] = proto.RepeatedField( proto.MESSAGE, number=6, message=WebImage, ) - best_guess_labels = proto.RepeatedField( + best_guess_labels: MutableSequence[WebLabel] = proto.RepeatedField( proto.MESSAGE, number=8, message=WebLabel, diff --git a/mypy.ini b/mypy.ini index 4505b485..574c5aed 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,3 +1,3 @@ [mypy] -python_version = 3.6 +python_version = 3.7 namespace_packages = True diff --git a/noxfile.py b/noxfile.py index 870b38f6..1cc6f4e5 100644 --- a/noxfile.py +++ b/noxfile.py @@ -274,12 +274,16 @@ def cover(session): session.run("coverage", "erase") -@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.session(python="3.9") def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") + session.install( + "sphinx==4.0.1", + "alabaster", + "recommonmark", + ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( @@ -296,13 +300,16 @@ def docs(session): ) -@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.session(python="3.9") def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") session.install( - "sphinx==4.0.1", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml" + "sphinx==4.0.1", + "alabaster", + "recommonmark", + "gcp-sphinx-docfx-yaml", ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) diff --git a/owlbot.py b/owlbot.py index 6b21e04e..4aa84403 100644 --- a/owlbot.py +++ b/owlbot.py @@ -1,4 +1,4 @@ -# Copyright 2018 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,17 +12,30 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This script is used to synthesize generated parts of this library.""" +import json +from pathlib import Path +import shutil import synthtool as s -from synthtool import gcp +import synthtool.gcp as gcp from synthtool.languages import python -common = gcp.CommonTemplates() +# ---------------------------------------------------------------------------- +# Copy the generated client from the owl-bot staging directory +# ---------------------------------------------------------------------------- + +clean_up_generated_samples = True -default_version = "v1" +# Load the default version defined in .repo-metadata.json. +default_version = json.load(open(".repo-metadata.json", "rt")).get( + "default_version" +) for library in s.get_staging_dirs(default_version): + if clean_up_generated_samples: + shutil.rmtree("samples/generated_samples", ignore_errors=True) + clean_up_generated_samples = False + if library.name == "v1": s.replace( library / "google/cloud/vision/__init__.py", @@ -87,39 +100,23 @@ " requests[i] = image_annotator.AsyncAnnotateFileRequest(requests[i])" ) - s.move(library / f"google/cloud/vision_{library.name}/proto") - s.move(library / f"google/cloud/vision_{library.name}/services") - s.move(library / f"google/cloud/vision_{library.name}/types") - s.move(library / f"google/cloud/vision_{library.name}/__init__.py") - s.move(library / f"google/cloud/vision_{library.name}/py.typed") - s.move(library / f"tests/unit/gapic/vision_{library.name}") - - # don't publish docs for these versions - if library.name != "v1p1beta1": - s.move(library / f"docs/vision_{library.name}") - - # Move docs configuration - s.move(library / f"docs/conf.py") - s.move(library / "samples") - + s.move([library], excludes=["**/gapic_version.py", "README.rst", "docs/index.rst", "docs/vision_v1p1beta1", "google/cloud/vision/__init__.py"]) s.remove_staging_dirs() # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library( - samples=True, - microgenerator=True, - cov_level=99, - system_test_external_dependencies=["google-cloud-storage"] -) -s.move(templated_files, excludes=[".coveragerc", "README.rst"]) -python.configure_previous_major_version_branches() +templated_files = gcp.CommonTemplates().py_library( + cov_level=99, + microgenerator=True, + versions=gcp.common.detect_versions(path="./google", default_first=True), + system_test_external_dependencies=["google-cloud-storage"], +) +s.move(templated_files, excludes=[".coveragerc", ".github/release-please.yml", "README.rst", "docs/index.rst","google/cloud/vision/__init__.py"]) -# ---------------------------------------------------------------------------- -# Samples templates -# ---------------------------------------------------------------------------- python.py_samples(skip_readmes=True) -s.shell.run(["nox", "-s", "blacken"], hide_output=False) +# run format session for all directories which have a noxfile +for noxfile in Path(".").glob("**/noxfile.py"): + s.shell.run(["nox", "-s", "blacken"], cwd=noxfile.parent, hide_output=False) diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 00000000..9131789f --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,49 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "python", + "extra-files": [ + "google/cloud/vision/gapic_version.py", + "google/cloud/vision_v1/gapic_version.py", + "google/cloud/vision_v1p1beta1/gapic_version.py", + "google/cloud/vision_v1p2beta1/gapic_version.py", + "google/cloud/vision_v1p3beta1/gapic_version.py", + "google/cloud/vision_v1p4beta1/gapic_version.py", + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json", + "jsonpath": "$.clientLibrary.version" + }, + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json", + "jsonpath": "$.clientLibrary.version" + }, + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json", + "jsonpath": "$.clientLibrary.version" + }, + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json", + "jsonpath": "$.clientLibrary.version" + }, + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json", + "jsonpath": "$.clientLibrary.version" + } + ] + } + }, + "release-type": "python", + "plugins": [ + { + "type": "sentence-case" + } + ], + "initial-version": "0.1.0" +} + diff --git a/samples/README b/samples/README new file mode 100644 index 00000000..621045ed --- /dev/null +++ b/samples/README @@ -0,0 +1,3 @@ +These samples have moved. + +https://github.com/GoogleCloudPlatform/python-docs-samples/tree/main/vision/snippets \ No newline at end of file diff --git a/samples/generated_samples/snippet_metadata_vision_v1.json b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json similarity index 99% rename from samples/generated_samples/snippet_metadata_vision_v1.json rename to samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json index 093faeb3..db813a27 100644 --- a/samples/generated_samples/snippet_metadata_vision_v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-vision" + "name": "google-cloud-vision", + "version": "3.2.0" }, "snippets": [ { @@ -34,7 +35,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -114,7 +115,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -195,7 +196,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]" }, { "name": "output_config", @@ -279,7 +280,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]" }, { "name": "output_config", @@ -364,7 +365,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AnnotateFileRequest]" }, { "name": "retry", @@ -444,7 +445,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AnnotateFileRequest]" }, { "name": "retry", @@ -525,7 +526,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]" }, { "name": "retry", @@ -605,7 +606,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1.types.AnnotateImageRequest]" }, { "name": "retry", diff --git a/samples/generated_samples/snippet_metadata_vision_v1p1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json similarity index 95% rename from samples/generated_samples/snippet_metadata_vision_v1p1beta1.json rename to samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json index 3dd79db8..a52e6de3 100644 --- a/samples/generated_samples/snippet_metadata_vision_v1p1beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-vision" + "name": "google-cloud-vision", + "version": "3.2.0" }, "snippets": [ { @@ -34,7 +35,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]" }, { "name": "retry", @@ -114,7 +115,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]" }, { "name": "retry", diff --git a/samples/generated_samples/snippet_metadata_vision_v1p2beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json similarity index 95% rename from samples/generated_samples/snippet_metadata_vision_v1p2beta1.json rename to samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json index df4399c9..ae37f5c8 100644 --- a/samples/generated_samples/snippet_metadata_vision_v1p2beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-vision" + "name": "google-cloud-vision", + "version": "3.2.0" }, "snippets": [ { @@ -34,7 +35,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -114,7 +115,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -195,7 +196,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]" }, { "name": "retry", @@ -275,7 +276,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]" }, { "name": "retry", diff --git a/samples/generated_samples/snippet_metadata_vision_v1p3beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json similarity index 99% rename from samples/generated_samples/snippet_metadata_vision_v1p3beta1.json rename to samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json index 38f9f04d..6c96ba59 100644 --- a/samples/generated_samples/snippet_metadata_vision_v1p3beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-vision" + "name": "google-cloud-vision", + "version": "3.2.0" }, "snippets": [ { @@ -34,7 +35,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -114,7 +115,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -195,7 +196,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]" }, { "name": "retry", @@ -275,7 +276,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]" }, { "name": "retry", diff --git a/samples/generated_samples/snippet_metadata_vision_v1p4beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json similarity index 99% rename from samples/generated_samples/snippet_metadata_vision_v1p4beta1.json rename to samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json index 275e575c..c5564bda 100644 --- a/samples/generated_samples/snippet_metadata_vision_v1p4beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-vision" + "name": "google-cloud-vision", + "version": "3.2.0" }, "snippets": [ { @@ -34,7 +35,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -114,7 +115,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]" }, { "name": "retry", @@ -195,7 +196,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" }, { "name": "output_config", @@ -279,7 +280,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" }, { "name": "output_config", @@ -364,7 +365,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]" }, { "name": "retry", @@ -444,7 +445,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]" }, { "name": "retry", @@ -525,7 +526,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" }, { "name": "retry", @@ -605,7 +606,7 @@ }, { "name": "requests", - "type": "Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" + "type": "MutableSequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]" }, { "name": "retry", diff --git a/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py b/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py index a2c0f4eb..7d890d11 100644 --- a/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_files_async.py @@ -47,7 +47,7 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py b/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py index 0c0509e2..550edf0c 100644 --- a/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py +++ b/samples/generated_samples/vision_v1_generated_image_annotator_async_batch_annotate_images_async.py @@ -47,7 +47,7 @@ async def sample_async_batch_annotate_images(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py b/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py index 8cffc714..078c53fb 100644 --- a/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py +++ b/samples/generated_samples/vision_v1_generated_product_search_import_product_sets_async.py @@ -48,7 +48,7 @@ async def sample_import_product_sets(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py b/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py index 364fe4a6..4933cc02 100644 --- a/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py +++ b/samples/generated_samples/vision_v1_generated_product_search_purge_products_async.py @@ -48,7 +48,7 @@ async def sample_purge_products(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py b/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py index 08695297..b7f0bddb 100644 --- a/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/samples/generated_samples/vision_v1p2beta1_generated_image_annotator_async_batch_annotate_files_async.py @@ -47,7 +47,7 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py b/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py index 792c8072..0829146e 100644 --- a/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/samples/generated_samples/vision_v1p3beta1_generated_image_annotator_async_batch_annotate_files_async.py @@ -47,7 +47,7 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py b/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py index 10012fd8..50fc3502 100644 --- a/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py +++ b/samples/generated_samples/vision_v1p3beta1_generated_product_search_import_product_sets_async.py @@ -48,7 +48,7 @@ async def sample_import_product_sets(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py b/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py index cf871c95..d8e48921 100644 --- a/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py +++ b/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_files_async.py @@ -47,7 +47,7 @@ async def sample_async_batch_annotate_files(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py b/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py index fcda4bec..e5a42cd0 100644 --- a/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py +++ b/samples/generated_samples/vision_v1p4beta1_generated_image_annotator_async_batch_annotate_images_async.py @@ -47,7 +47,7 @@ async def sample_async_batch_annotate_images(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py b/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py index 8657e125..36440a0e 100644 --- a/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py +++ b/samples/generated_samples/vision_v1p4beta1_generated_product_search_import_product_sets_async.py @@ -48,7 +48,7 @@ async def sample_import_product_sets(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py b/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py index 883e30c7..050d47e4 100644 --- a/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py +++ b/samples/generated_samples/vision_v1p4beta1_generated_product_search_purge_products_async.py @@ -48,7 +48,7 @@ async def sample_purge_products(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/snippets/crop_hints/.gitignore b/samples/snippets/crop_hints/.gitignore deleted file mode 100644 index 69e00386..00000000 --- a/samples/snippets/crop_hints/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -output-crop.jpg -output-hint.jpg diff --git a/samples/snippets/crop_hints/README.rst b/samples/snippets/crop_hints/README.rst deleted file mode 100644 index 4ca8652f..00000000 --- a/samples/snippets/crop_hints/README.rst +++ /dev/null @@ -1,111 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Vision API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/crop_hints/README.rst - - -This directory contains samples for Google Cloud Vision API. `Google Cloud Vision API`_ allows developers to easily integrate vision detection features within applications, including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. - -- See the `migration guide`_ for information about migrating to Python client library v0.25.1. - -.. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - - - - -.. _Google Cloud Vision API: https://cloud.google.com/vision/docs - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Samples -------------------------------------------------------------------------------- - -Crop Hints Tutorial -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/crop_hints/crop_hints.py,vision/cloud-client/crop_hints/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python crop_hints.py - - usage: crop_hints.py [-h] image_file mode - - positional arguments: - image_file The image you'd like to crop. - mode Set to "crop" or "draw". - - optional arguments: - -h, --help show this help message and exit - - - - - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/crop_hints/README.rst.in b/samples/snippets/crop_hints/README.rst.in deleted file mode 100644 index 113d2771..00000000 --- a/samples/snippets/crop_hints/README.rst.in +++ /dev/null @@ -1,30 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Vision API - short_name: Cloud Vision API - url: https://cloud.google.com/vision/docs - description: > - `Google Cloud Vision API`_ allows developers to easily integrate vision - detection features within applications, including image labeling, face and - landmark detection, optical character recognition (OCR), and tagging of - explicit content. - - - - See the `migration guide`_ for information about migrating to Python client library v0.25.1. - - - .. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - -setup: -- auth -- install_deps - -samples: -- name: Crop Hints Tutorial - file: crop_hints.py - show_help: True - -cloud_client_library: true - -folder: vision/cloud-client/crop_hints \ No newline at end of file diff --git a/samples/snippets/crop_hints/crop_hints.py b/samples/snippets/crop_hints/crop_hints.py deleted file mode 100644 index 766e4e00..00000000 --- a/samples/snippets/crop_hints/crop_hints.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Outputs a cropped image or an image highlighting crop regions on an image. - -Examples: - python crop_hints.py resources/cropme.jpg draw - python crop_hints.py resources/cropme.jpg crop -""" -# [START vision_crop_hints_tutorial] -# [START vision_crop_hints_tutorial_imports] -import argparse -import io - -from google.cloud import vision -from PIL import Image, ImageDraw -# [END vision_crop_hints_tutorial_imports] - - -def get_crop_hint(path): - # [START vision_crop_hints_tutorial_get_crop_hints] - """Detect crop hints on a single image and return the first result.""" - client = vision.ImageAnnotatorClient() - - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.77]) - image_context = vision.ImageContext(crop_hints_params=crop_hints_params) - - response = client.crop_hints(image=image, image_context=image_context) - hints = response.crop_hints_annotation.crop_hints - - # Get bounds for the first crop hint using an aspect ratio of 1.77. - vertices = hints[0].bounding_poly.vertices - # [END vision_crop_hints_tutorial_get_crop_hints] - - return vertices - - -def draw_hint(image_file): - """Draw a border around the image using the hints in the vector list.""" - # [START vision_crop_hints_tutorial_draw_crop_hints] - vects = get_crop_hint(image_file) - - im = Image.open(image_file) - draw = ImageDraw.Draw(im) - draw.polygon([ - vects[0].x, vects[0].y, - vects[1].x, vects[1].y, - vects[2].x, vects[2].y, - vects[3].x, vects[3].y], None, 'red') - im.save('output-hint.jpg', 'JPEG') - print('Saved new image to output-hint.jpg') - # [END vision_crop_hints_tutorial_draw_crop_hints] - - -def crop_to_hint(image_file): - """Crop the image using the hints in the vector list.""" - # [START vision_crop_hints_tutorial_crop_to_hints] - vects = get_crop_hint(image_file) - - im = Image.open(image_file) - im2 = im.crop([vects[0].x, vects[0].y, - vects[2].x - 1, vects[2].y - 1]) - im2.save('output-crop.jpg', 'JPEG') - print('Saved new image to output-crop.jpg') - # [END vision_crop_hints_tutorial_crop_to_hints] - - -if __name__ == '__main__': - # [START vision_crop_hints_tutorial_run_application] - parser = argparse.ArgumentParser() - parser.add_argument('image_file', help='The image you\'d like to crop.') - parser.add_argument('mode', help='Set to "crop" or "draw".') - args = parser.parse_args() - - if args.mode == 'crop': - crop_to_hint(args.image_file) - elif args.mode == 'draw': - draw_hint(args.image_file) - # [END vision_crop_hints_tutorial_run_application] -# [END vision_crop_hints_tutorial] diff --git a/samples/snippets/crop_hints/crop_hints_test.py b/samples/snippets/crop_hints/crop_hints_test.py deleted file mode 100644 index 2ba900f4..00000000 --- a/samples/snippets/crop_hints/crop_hints_test.py +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os - -import crop_hints - - -def test_crop(capsys): - """Checks the output image for cropping the image is created.""" - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/cropme.jpg') - crop_hints.crop_to_hint(file_name) - out, _ = capsys.readouterr() - assert os.path.isfile('output-crop.jpg') - - -def test_draw(capsys): - """Checks the output image for drawing the crop hint is created.""" - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/cropme.jpg') - crop_hints.draw_hint(file_name) - out, _ = capsys.readouterr() - assert os.path.isfile('output-hint.jpg') diff --git a/samples/snippets/crop_hints/noxfile.py b/samples/snippets/crop_hints/noxfile.py deleted file mode 100644 index 0398d72f..00000000 --- a/samples/snippets/crop_hints/noxfile.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, List, Optional - -import nox - - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--import-order-style=google", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") - else: - session.install("flake8", "flake8-import-order", "flake8-annotations") - - local_names = _determine_local_import_names(".") - args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob("**/test_*.py", recursive=True) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install( - "-r", "requirements-test.txt", "-c", "constraints-test.txt" - ) - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(['--workers', 'auto', '--tests-per-worker', 'auto']) - elif "pytest-xdist" in packages: - concurrent_args.extend(['-n', 'auto']) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/crop_hints/noxfile_config.py b/samples/snippets/crop_hints/noxfile_config.py deleted file mode 100644 index e5578c31..00000000 --- a/samples/snippets/crop_hints/noxfile_config.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Default TEST_CONFIG_OVERRIDE for python repos. - -# You can copy this file into your directory, then it will be inported from -# the noxfile.py. - -# The source of truth: -# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py - -TEST_CONFIG_OVERRIDE = { - # You can opt out from the test for specific Python versions. - # Pillow 9.0.0 does not support python 3.6 - "ignored_versions": ["3.6"], -} diff --git a/samples/snippets/crop_hints/requirements-test.txt b/samples/snippets/crop_hints/requirements-test.txt deleted file mode 100644 index e0716850..00000000 --- a/samples/snippets/crop_hints/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.1.3 diff --git a/samples/snippets/crop_hints/requirements.txt b/samples/snippets/crop_hints/requirements.txt deleted file mode 100644 index c524155a..00000000 --- a/samples/snippets/crop_hints/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -google-cloud-vision==3.1.3 -pillow==9.2.0 diff --git a/samples/snippets/crop_hints/resources/cropme.jpg b/samples/snippets/crop_hints/resources/cropme.jpg deleted file mode 100644 index 50145895..00000000 Binary files a/samples/snippets/crop_hints/resources/cropme.jpg and /dev/null differ diff --git a/samples/snippets/detect/README.rst b/samples/snippets/detect/README.rst deleted file mode 100644 index a06e286b..00000000 --- a/samples/snippets/detect/README.rst +++ /dev/null @@ -1,261 +0,0 @@ - -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Vision API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/detect/README.rst - - -This directory contains samples for Google Cloud Vision API. `Google Cloud Vision API`_ allows developers to easily integrate vision detection features within applications, including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. - -- See the `migration guide`_ for information about migrating to Python client library v0.25.1. - -.. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - - - - -.. _Google Cloud Vision API: https://cloud.google.com/vision/docs - - -Setup -------------------------------------------------------------------------------- - - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - - - - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 3.6+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - - - - - - -Samples -------------------------------------------------------------------------------- - - -Detect -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/detect/detect.py,vision/cloud-client/detect/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python detect.py - - - usage: detect.py [-h] - {faces,faces-uri,labels,labels-uri,landmarks,landmarks-uri,text,text-uri,logos,logos-uri,safe-search,safe-search-uri,properties,properties-uri,web,web-uri,web-geo,web-geo-uri,crophints,crophints-uri,document,document-uri,ocr-uri,object-localization,object-localization-uri} - ... - - This application demonstrates how to perform basic operations with the - Google Cloud Vision API. - - Example Usage: - python detect.py text ./resources/wakeupcat.jpg - python detect.py labels ./resources/landmark.jpg - python detect.py web ./resources/landmark.jpg - python detect.py web-uri http://wheresgus.com/dog.JPG - python detect.py web-geo ./resources/city.jpg - python detect.py faces-uri gs://your-bucket/file.jpg - python detect.py ocr-uri gs://python-docs-samples-tests/HodgeConj.pdf gs://BUCKET_NAME/PREFIX/ - python detect.py object-localization ./resources/puppies.jpg - python detect.py object-localization-uri gs://... - - For more information, the documentation at - https://cloud.google.com/vision/docs. - - positional arguments: - {faces,faces-uri,labels,labels-uri,landmarks,landmarks-uri,text,text-uri,logos,logos-uri,safe-search,safe-search-uri,properties,properties-uri,web,web-uri,web-geo,web-geo-uri,crophints,crophints-uri,document,document-uri,ocr-uri,object-localization,object-localization-uri} - faces Detects faces in an image. - faces-uri Detects faces in the file located in Google Cloud - Storage or the web. - labels Detects labels in the file. - labels-uri Detects labels in the file located in Google Cloud - Storage or on the Web. - landmarks Detects landmarks in the file. - landmarks-uri Detects landmarks in the file located in Google Cloud - Storage or on the Web. - text Detects text in the file. - text-uri Detects text in the file located in Google Cloud - Storage or on the Web. - logos Detects logos in the file. - logos-uri Detects logos in the file located in Google Cloud - Storage or on the Web. - safe-search Detects unsafe features in the file. - safe-search-uri Detects unsafe features in the file located in Google - Cloud Storage or on the Web. - properties Detects image properties in the file. - properties-uri Detects image properties in the file located in Google - Cloud Storage or on the Web. - web Detects web annotations given an image. - web-uri Detects web annotations in the file located in Google - Cloud Storage. - web-geo Detects web annotations given an image, using the - geotag metadata in the image to detect web entities. - web-geo-uri Detects web annotations given an image in the file - located in Google Cloud Storage., using the geotag - metadata in the image to detect web entities. - crophints Detects crop hints in an image. - crophints-uri Detects crop hints in the file located in Google Cloud - Storage. - document Detects document features in an image. - document-uri Detects document features in the file located in - Google Cloud Storage. - ocr-uri OCR with PDF/TIFF as source files on GCS - object-localization - OCR with PDF/TIFF as source files on GCS - object-localization-uri - OCR with PDF/TIFF as source files on GCS - - optional arguments: - -h, --help show this help message and exit - - - - - -Beta Detect -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/detect/beta_snippets.py,vision/cloud-client/detect/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python beta_snippets.py - - - usage: beta_snippets.py [-h] - {object-localization,object-localization-uri,handwritten-ocr,handwritten-ocr-uri,batch-annotate-files,batch-annotate-files-uri,batch-annotate-images-uri} - ... - - Google Cloud Vision API Python Beta Snippets - - Example Usage: - python beta_snippets.py -h - python beta_snippets.py object-localization INPUT_IMAGE - python beta_snippets.py object-localization-uri gs://... - python beta_snippets.py handwritten-ocr INPUT_IMAGE - python beta_snippets.py handwritten-ocr-uri gs://... - python beta_snippets.py batch-annotate-files INPUT_PDF - python beta_snippets.py batch-annotate-files-uri gs://... - python beta_snippets.py batch-annotate-images-uri gs://... gs://... - - For more information, the documentation at - https://cloud.google.com/vision/docs. - - positional arguments: - {object-localization,object-localization-uri,handwritten-ocr,handwritten-ocr-uri,batch-annotate-files,batch-annotate-files-uri,batch-annotate-images-uri} - object-localization - Localize objects in the local image. Args: path: The - path to the local file. - object-localization-uri - Localize objects in the image on Google Cloud Storage - Args: uri: The path to the file in Google Cloud - Storage (gs://...) - handwritten-ocr Detects handwritten characters in a local image. Args: - path: The path to the local file. - handwritten-ocr-uri - Detects handwritten characters in the file located in - Google Cloud Storage. Args: uri: The path to the file - in Google Cloud Storage (gs://...) - batch-annotate-files - Detects document features in a PDF/TIFF/GIF file. - While your PDF file may have several pages, this API - can process up to 5 pages only. Args: path: The path - to the local file. - batch-annotate-files-uri - Detects document features in a PDF/TIFF/GIF file. - While your PDF file may have several pages, this API - can process up to 5 pages only. Args: uri: The path to - the file in Google Cloud Storage (gs://...) - batch-annotate-images-uri - Batch annotation of images on Google Cloud Storage - asynchronously. Args: input_image_uri: The path to the - image in Google Cloud Storage (gs://...) output_uri: - The path to the output path in Google Cloud Storage - (gs://...) - - optional arguments: - -h, --help show this help message and exit - - - - - - - - - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ diff --git a/samples/snippets/detect/README.rst.in b/samples/snippets/detect/README.rst.in deleted file mode 100644 index 0d105411..00000000 --- a/samples/snippets/detect/README.rst.in +++ /dev/null @@ -1,33 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Vision API - short_name: Cloud Vision API - url: https://cloud.google.com/vision/docs - description: > - `Google Cloud Vision API`_ allows developers to easily integrate vision - detection features within applications, including image labeling, face and - landmark detection, optical character recognition (OCR), and tagging of - explicit content. - - - - See the `migration guide`_ for information about migrating to Python client library v0.25.1. - - - .. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - -setup: -- auth -- install_deps - -samples: -- name: Detect - file: detect.py - show_help: True -- name: Beta Detect - file: beta_snippets.py - show_help: True - -cloud_client_library: true - -folder: vision/cloud-client/detect \ No newline at end of file diff --git a/samples/snippets/detect/beta_snippets.py b/samples/snippets/detect/beta_snippets.py deleted file mode 100644 index 03dba60e..00000000 --- a/samples/snippets/detect/beta_snippets.py +++ /dev/null @@ -1,412 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2018 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Google Cloud Vision API Python Beta Snippets - -Example Usage: -python beta_snippets.py -h -python beta_snippets.py object-localization INPUT_IMAGE -python beta_snippets.py object-localization-uri gs://... -python beta_snippets.py handwritten-ocr INPUT_IMAGE -python beta_snippets.py handwritten-ocr-uri gs://... -python beta_snippets.py batch-annotate-files INPUT_PDF -python beta_snippets.py batch-annotate-files-uri gs://... -python beta_snippets.py batch-annotate-images-uri gs://... gs://... - - -For more information, the documentation at -https://cloud.google.com/vision/docs. -""" - -import argparse -import io - - -# [START vision_localize_objects_beta] -def localize_objects(path): - """Localize objects in the local image. - - Args: - path: The path to the local file. - """ - from google.cloud import vision_v1p3beta1 as vision - client = vision.ImageAnnotatorClient() - - with open(path, 'rb') as image_file: - content = image_file.read() - image = vision.Image(content=content) - - objects = client.object_localization( - image=image).localized_object_annotations - - print('Number of objects found: {}'.format(len(objects))) - for object_ in objects: - print('\n{} (confidence: {})'.format(object_.name, object_.score)) - print('Normalized bounding polygon vertices: ') - for vertex in object_.bounding_poly.normalized_vertices: - print(' - ({}, {})'.format(vertex.x, vertex.y)) -# [END vision_localize_objects_beta] - - -# [START vision_localize_objects_gcs_beta] -def localize_objects_uri(uri): - """Localize objects in the image on Google Cloud Storage - - Args: - uri: The path to the file in Google Cloud Storage (gs://...) - """ - from google.cloud import vision_v1p3beta1 as vision - client = vision.ImageAnnotatorClient() - - image = vision.Image() - image.source.image_uri = uri - - objects = client.object_localization( - image=image).localized_object_annotations - - print('Number of objects found: {}'.format(len(objects))) - for object_ in objects: - print('\n{} (confidence: {})'.format(object_.name, object_.score)) - print('Normalized bounding polygon vertices: ') - for vertex in object_.bounding_poly.normalized_vertices: - print(' - ({}, {})'.format(vertex.x, vertex.y)) -# [END vision_localize_objects_gcs_beta] - - -# [START vision_handwritten_ocr_beta] -def detect_handwritten_ocr(path): - """Detects handwritten characters in a local image. - - Args: - path: The path to the local file. - """ - from google.cloud import vision_v1p3beta1 as vision - client = vision.ImageAnnotatorClient() - - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - # Language hint codes for handwritten OCR: - # en-t-i0-handwrit, mul-Latn-t-i0-handwrit - # Note: Use only one language hint code per request for handwritten OCR. - image_context = vision.ImageContext( - language_hints=['en-t-i0-handwrit']) - - response = client.document_text_detection(image=image, - image_context=image_context) - - print('Full Text: {}'.format(response.full_text_annotation.text)) - for page in response.full_text_annotation.pages: - for block in page.blocks: - print('\nBlock confidence: {}\n'.format(block.confidence)) - - for paragraph in block.paragraphs: - print('Paragraph confidence: {}'.format( - paragraph.confidence)) - - for word in paragraph.words: - word_text = ''.join([ - symbol.text for symbol in word.symbols - ]) - print('Word text: {} (confidence: {})'.format( - word_text, word.confidence)) - - for symbol in word.symbols: - print('\tSymbol: {} (confidence: {})'.format( - symbol.text, symbol.confidence)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_handwritten_ocr_beta] - - -# [START vision_handwritten_ocr_gcs_beta] -def detect_handwritten_ocr_uri(uri): - """Detects handwritten characters in the file located in Google Cloud - Storage. - - Args: - uri: The path to the file in Google Cloud Storage (gs://...) - """ - from google.cloud import vision_v1p3beta1 as vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - # Language hint codes for handwritten OCR: - # en-t-i0-handwrit, mul-Latn-t-i0-handwrit - # Note: Use only one language hint code per request for handwritten OCR. - image_context = vision.ImageContext( - language_hints=['en-t-i0-handwrit']) - - response = client.document_text_detection(image=image, - image_context=image_context) - - print('Full Text: {}'.format(response.full_text_annotation.text)) - for page in response.full_text_annotation.pages: - for block in page.blocks: - print('\nBlock confidence: {}\n'.format(block.confidence)) - - for paragraph in block.paragraphs: - print('Paragraph confidence: {}'.format( - paragraph.confidence)) - - for word in paragraph.words: - word_text = ''.join([ - symbol.text for symbol in word.symbols - ]) - print('Word text: {} (confidence: {})'.format( - word_text, word.confidence)) - - for symbol in word.symbols: - print('\tSymbol: {} (confidence: {})'.format( - symbol.text, symbol.confidence)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_handwritten_ocr_gcs_beta] - - -# [START vision_batch_annotate_files_beta] -def detect_batch_annotate_files(path): - """Detects document features in a PDF/TIFF/GIF file. - - While your PDF file may have several pages, - this API can process up to 5 pages only. - - Args: - path: The path to the local file. - """ - from google.cloud import vision_v1p4beta1 as vision - client = vision.ImageAnnotatorClient() - - with open(path, 'rb') as pdf_file: - content = pdf_file.read() - - # Other supported mime_types: image/tiff' or 'image/gif' - mime_type = 'application/pdf' - input_config = vision.InputConfig( - content=content, mime_type=mime_type) - - feature = vision.Feature( - type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) - # Annotate the first two pages and the last one (max 5 pages) - # First page starts at 1, and not 0. Last page is -1. - pages = [1, 2, -1] - - request = vision.AnnotateFileRequest( - input_config=input_config, - features=[feature], - pages=pages) - - response = client.batch_annotate_files(requests=[request]) - - for image_response in response.responses[0].responses: - for page in image_response.full_text_annotation.pages: - for block in page.blocks: - print(u'\nBlock confidence: {}\n'.format(block.confidence)) - for par in block.paragraphs: - print(u'\tParagraph confidence: {}'.format(par.confidence)) - for word in par.words: - symbol_texts = [symbol.text for symbol in word.symbols] - word_text = ''.join(symbol_texts) - print(u'\t\tWord text: {} (confidence: {})'.format( - word_text, word.confidence)) - for symbol in word.symbols: - print(u'\t\t\tSymbol: {} (confidence: {})'.format( - symbol.text, symbol.confidence)) -# [END vision_batch_annotate_files_beta] - - -# [START vision_batch_annotate_files_gcs_beta] -def detect_batch_annotate_files_uri(gcs_uri): - """Detects document features in a PDF/TIFF/GIF file. - - While your PDF file may have several pages, - this API can process up to 5 pages only. - - Args: - uri: The path to the file in Google Cloud Storage (gs://...) - """ - from google.cloud import vision_v1p4beta1 as vision - client = vision.ImageAnnotatorClient() - - # Other supported mime_types: image/tiff' or 'image/gif' - mime_type = 'application/pdf' - input_config = vision.InputConfig( - gcs_source=vision.GcsSource(uri=gcs_uri), mime_type=mime_type) - - feature = vision.Feature( - type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) - # Annotate the first two pages and the last one (max 5 pages) - # First page starts at 1, and not 0. Last page is -1. - pages = [1, 2, -1] - - request = vision.AnnotateFileRequest( - input_config=input_config, - features=[feature], - pages=pages) - - response = client.batch_annotate_files(requests=[request]) - - for image_response in response.responses[0].responses: - for page in image_response.full_text_annotation.pages: - for block in page.blocks: - print(u'\nBlock confidence: {}\n'.format(block.confidence)) - for par in block.paragraphs: - print(u'\tParagraph confidence: {}'.format(par.confidence)) - for word in par.words: - symbol_texts = [symbol.text for symbol in word.symbols] - word_text = ''.join(symbol_texts) - print(u'\t\tWord text: {} (confidence: {})'.format( - word_text, word.confidence)) - for symbol in word.symbols: - print(u'\t\t\tSymbol: {} (confidence: {})'.format( - symbol.text, symbol.confidence)) -# [END vision_batch_annotate_files_gcs_beta] - - -# [START vision_async_batch_annotate_images_beta] -def async_batch_annotate_images_uri(input_image_uri, output_uri): - """Batch annotation of images on Google Cloud Storage asynchronously. - - Args: - input_image_uri: The path to the image in Google Cloud Storage (gs://...) - output_uri: The path to the output path in Google Cloud Storage (gs://...) - """ - import re - - from google.cloud import storage - - from google.cloud import vision_v1p4beta1 as vision - client = vision.ImageAnnotatorClient() - - # Construct the request for the image(s) to be annotated: - image_source = vision.ImageSource(image_uri=input_image_uri) - image = vision.Image(source=image_source) - features = [ - vision.Feature(type_=vision.Feature.Type.LABEL_DETECTION), - vision.Feature(type_=vision.Feature.Type.TEXT_DETECTION), - vision.Feature(type_=vision.Feature.Type.IMAGE_PROPERTIES), - ] - requests = [ - vision.AnnotateImageRequest(image=image, features=features), - ] - - gcs_destination = vision.GcsDestination(uri=output_uri) - output_config = vision.OutputConfig( - gcs_destination=gcs_destination, batch_size=2) - - operation = client.async_batch_annotate_images( - requests=requests, output_config=output_config) - - print('Waiting for the operation to finish.') - operation.result(timeout=10000) - - # Once the request has completed and the output has been - # written to Google Cloud Storage, we can list all the output files. - storage_client = storage.Client() - - match = re.match(r'gs://([^/]+)/(.+)', output_uri) - bucket_name = match.group(1) - prefix = match.group(2) - - bucket = storage_client.get_bucket(bucket_name) - - # Lists objects with the given prefix. - blob_list = list(bucket.list_blobs(prefix=prefix)) - print('Output files:') - for blob in blob_list: - print(blob.name) - - # Processes the first output file from Google Cloud Storage. - # Since we specified batch_size=2, the first response contains - # annotations for the first two annotate image requests. - output = blob_list[0] - - json_string = output.download_as_string() - response = vision.BatchAnnotateImagesResponse.from_json(json_string) - - # Prints the actual response for the first annotate image request. - print(u'The annotation response for the first request: {}'.format( - response.responses[0])) -# [END vision_async_batch_annotate_images_beta] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - subparsers = parser.add_subparsers(dest='command') - - object_parser = subparsers.add_parser( - 'object-localization', help=localize_objects.__doc__) - object_parser.add_argument('path') - - object_uri_parser = subparsers.add_parser( - 'object-localization-uri', help=localize_objects_uri.__doc__) - object_uri_parser.add_argument('uri') - - handwritten_parser = subparsers.add_parser( - 'handwritten-ocr', help=detect_handwritten_ocr.__doc__) - handwritten_parser.add_argument('path') - - handwritten_uri_parser = subparsers.add_parser( - 'handwritten-ocr-uri', help=detect_handwritten_ocr_uri.__doc__) - handwritten_uri_parser.add_argument('uri') - - batch_annotate_parser = subparsers.add_parser( - 'batch-annotate-files', help=detect_batch_annotate_files.__doc__) - batch_annotate_parser.add_argument('path') - - batch_annotate_uri_parser = subparsers.add_parser( - 'batch-annotate-files-uri', - help=detect_batch_annotate_files_uri.__doc__) - batch_annotate_uri_parser.add_argument('uri') - - batch_annotate__image_uri_parser = subparsers.add_parser( - 'batch-annotate-images-uri', - help=async_batch_annotate_images_uri.__doc__) - batch_annotate__image_uri_parser.add_argument('uri') - batch_annotate__image_uri_parser.add_argument('output') - - args = parser.parse_args() - - if 'uri' in args.command: - if 'object-localization-uri' in args.command: - localize_objects_uri(args.uri) - elif 'handwritten-ocr-uri' in args.command: - detect_handwritten_ocr_uri(args.uri) - elif 'batch-annotate-files-uri' in args.command: - detect_batch_annotate_files_uri(args.uri) - elif 'batch-annotate-images-uri' in args.command: - async_batch_annotate_images_uri(args.uri, args.output) - else: - if 'object-localization' in args.command: - localize_objects(args.path) - elif 'handwritten-ocr' in args.command: - detect_handwritten_ocr(args.path) - elif 'batch-annotate-files' in args.command: - detect_batch_annotate_files(args.path) diff --git a/samples/snippets/detect/beta_snippets_test.py b/samples/snippets/detect/beta_snippets_test.py deleted file mode 100644 index 4a5a4663..00000000 --- a/samples/snippets/detect/beta_snippets_test.py +++ /dev/null @@ -1,91 +0,0 @@ -# Copyright 2018 Google LLC All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import beta_snippets - -RESOURCES = os.path.join(os.path.dirname(__file__), 'resources') -GCS_ROOT = 'gs://cloud-samples-data/vision/' - -BUCKET = os.environ['CLOUD_STORAGE_BUCKET'] -OUTPUT_PREFIX = 'TEST_OUTPUT_{}'.format(uuid.uuid4()) -GCS_DESTINATION_URI = 'gs://{}/{}/'.format(BUCKET, OUTPUT_PREFIX) - - -def test_localize_objects(capsys): - path = os.path.join(RESOURCES, 'puppies.jpg') - - beta_snippets.localize_objects(path) - - out, _ = capsys.readouterr() - assert 'Dog' in out - - -def test_localize_objects_uri(capsys): - uri = GCS_ROOT + 'puppies.jpg' - - beta_snippets.localize_objects_uri(uri) - - out, _ = capsys.readouterr() - assert 'Dog' in out - - -def test_handwritten_ocr(capsys): - path = os.path.join(RESOURCES, 'handwritten.jpg') - - beta_snippets.detect_handwritten_ocr(path) - - out, _ = capsys.readouterr() - assert 'Cloud Vision API' in out - - -def test_handwritten_ocr_uri(capsys): - uri = GCS_ROOT + 'handwritten.jpg' - - beta_snippets.detect_handwritten_ocr_uri(uri) - - out, _ = capsys.readouterr() - assert 'Cloud Vision API' in out - - -def test_detect_batch_annotate_files(capsys): - file_name = os.path.join(RESOURCES, 'kafka.pdf') - beta_snippets.detect_batch_annotate_files(file_name) - out, _ = capsys.readouterr() - assert 'Symbol: a' in out - assert 'Word text: evenings' in out - - -def test_detect_batch_annotate_files_uri(capsys): - gcs_uri = GCS_ROOT + 'document_understanding/kafka.pdf' - beta_snippets.detect_batch_annotate_files_uri(gcs_uri) - out, _ = capsys.readouterr() - assert 'Symbol' in out - assert 'Word text' in out - - -def test_async_batch_annotate_images(capsys): - gcs_uri = GCS_ROOT + 'landmark/eiffel_tower.jpg' - beta_snippets.async_batch_annotate_images_uri(gcs_uri, GCS_DESTINATION_URI) - out, _ = capsys.readouterr() - assert 'description: "Tower"' in out - - from google.cloud import storage - storage_client = storage.Client() - bucket = storage_client.get_bucket(BUCKET) - if len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) > 0: - for blob in bucket.list_blobs(prefix=OUTPUT_PREFIX): - blob.delete() diff --git a/samples/snippets/detect/detect.py b/samples/snippets/detect/detect.py deleted file mode 100644 index 9e5d79e9..00000000 --- a/samples/snippets/detect/detect.py +++ /dev/null @@ -1,1104 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This application demonstrates how to perform basic operations with the -Google Cloud Vision API. - -Example Usage: -python detect.py text ./resources/wakeupcat.jpg -python detect.py labels ./resources/landmark.jpg -python detect.py web ./resources/landmark.jpg -python detect.py web-uri http://wheresgus.com/dog.JPG -python detect.py web-geo ./resources/city.jpg -python detect.py faces-uri gs://your-bucket/file.jpg -python detect.py ocr-uri gs://python-docs-samples-tests/HodgeConj.pdf \ -gs://BUCKET_NAME/PREFIX/ -python detect.py object-localization ./resources/puppies.jpg -python detect.py object-localization-uri gs://... - -For more information, the documentation at -https://cloud.google.com/vision/docs. -""" - -import argparse - - -# [START vision_face_detection] -def detect_faces(path): - """Detects faces in an image.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_face_detection] - # [START vision_python_migration_image_file] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - # [END vision_python_migration_image_file] - - response = client.face_detection(image=image) - faces = response.face_annotations - - # Names of likelihood from google.cloud.vision.enums - likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', - 'LIKELY', 'VERY_LIKELY') - print('Faces:') - - for face in faces: - print('anger: {}'.format(likelihood_name[face.anger_likelihood])) - print('joy: {}'.format(likelihood_name[face.joy_likelihood])) - print('surprise: {}'.format(likelihood_name[face.surprise_likelihood])) - - vertices = (['({},{})'.format(vertex.x, vertex.y) - for vertex in face.bounding_poly.vertices]) - - print('face bounds: {}'.format(','.join(vertices))) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_face_detection] -# [END vision_face_detection] - - -# [START vision_face_detection_gcs] -def detect_faces_uri(uri): - """Detects faces in the file located in Google Cloud Storage or the web.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - # [START vision_python_migration_image_uri] - image = vision.Image() - image.source.image_uri = uri - # [END vision_python_migration_image_uri] - - response = client.face_detection(image=image) - faces = response.face_annotations - - # Names of likelihood from google.cloud.vision.enums - likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', - 'LIKELY', 'VERY_LIKELY') - print('Faces:') - - for face in faces: - print('anger: {}'.format(likelihood_name[face.anger_likelihood])) - print('joy: {}'.format(likelihood_name[face.joy_likelihood])) - print('surprise: {}'.format(likelihood_name[face.surprise_likelihood])) - - vertices = (['({},{})'.format(vertex.x, vertex.y) - for vertex in face.bounding_poly.vertices]) - - print('face bounds: {}'.format(','.join(vertices))) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_face_detection_gcs] - - -# [START vision_label_detection] -def detect_labels(path): - """Detects labels in the file.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_label_detection] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.label_detection(image=image) - labels = response.label_annotations - print('Labels:') - - for label in labels: - print(label.description) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_label_detection] -# [END vision_label_detection] - - -# [START vision_label_detection_gcs] -def detect_labels_uri(uri): - """Detects labels in the file located in Google Cloud Storage or on the - Web.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.label_detection(image=image) - labels = response.label_annotations - print('Labels:') - - for label in labels: - print(label.description) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_label_detection_gcs] - - -# [START vision_landmark_detection] -def detect_landmarks(path): - """Detects landmarks in the file.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_landmark_detection] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.landmark_detection(image=image) - landmarks = response.landmark_annotations - print('Landmarks:') - - for landmark in landmarks: - print(landmark.description) - for location in landmark.locations: - lat_lng = location.lat_lng - print('Latitude {}'.format(lat_lng.latitude)) - print('Longitude {}'.format(lat_lng.longitude)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_landmark_detection] -# [END vision_landmark_detection] - - -# [START vision_landmark_detection_gcs] -def detect_landmarks_uri(uri): - """Detects landmarks in the file located in Google Cloud Storage or on the - Web.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.landmark_detection(image=image) - landmarks = response.landmark_annotations - print('Landmarks:') - - for landmark in landmarks: - print(landmark.description) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_landmark_detection_gcs] - - -# [START vision_logo_detection] -def detect_logos(path): - """Detects logos in the file.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_logo_detection] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.logo_detection(image=image) - logos = response.logo_annotations - print('Logos:') - - for logo in logos: - print(logo.description) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_logo_detection] -# [END vision_logo_detection] - - -# [START vision_logo_detection_gcs] -def detect_logos_uri(uri): - """Detects logos in the file located in Google Cloud Storage or on the Web. - """ - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.logo_detection(image=image) - logos = response.logo_annotations - print('Logos:') - - for logo in logos: - print(logo.description) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_logo_detection_gcs] - - -# [START vision_safe_search_detection] -def detect_safe_search(path): - """Detects unsafe features in the file.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_safe_search_detection] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.safe_search_detection(image=image) - safe = response.safe_search_annotation - - # Names of likelihood from google.cloud.vision.enums - likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', - 'LIKELY', 'VERY_LIKELY') - print('Safe search:') - - print('adult: {}'.format(likelihood_name[safe.adult])) - print('medical: {}'.format(likelihood_name[safe.medical])) - print('spoofed: {}'.format(likelihood_name[safe.spoof])) - print('violence: {}'.format(likelihood_name[safe.violence])) - print('racy: {}'.format(likelihood_name[safe.racy])) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_safe_search_detection] -# [END vision_safe_search_detection] - - -# [START vision_safe_search_detection_gcs] -def detect_safe_search_uri(uri): - """Detects unsafe features in the file located in Google Cloud Storage or - on the Web.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.safe_search_detection(image=image) - safe = response.safe_search_annotation - - # Names of likelihood from google.cloud.vision.enums - likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', - 'LIKELY', 'VERY_LIKELY') - print('Safe search:') - - print('adult: {}'.format(likelihood_name[safe.adult])) - print('medical: {}'.format(likelihood_name[safe.medical])) - print('spoofed: {}'.format(likelihood_name[safe.spoof])) - print('violence: {}'.format(likelihood_name[safe.violence])) - print('racy: {}'.format(likelihood_name[safe.racy])) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_safe_search_detection_gcs] - - -# [START vision_text_detection] -def detect_text(path): - """Detects text in the file.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_text_detection] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.text_detection(image=image) - texts = response.text_annotations - print('Texts:') - - for text in texts: - print('\n"{}"'.format(text.description)) - - vertices = (['({},{})'.format(vertex.x, vertex.y) - for vertex in text.bounding_poly.vertices]) - - print('bounds: {}'.format(','.join(vertices))) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_text_detection] -# [END vision_text_detection] - - -# [START vision_text_detection_gcs] -def detect_text_uri(uri): - """Detects text in the file located in Google Cloud Storage or on the Web. - """ - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.text_detection(image=image) - texts = response.text_annotations - print('Texts:') - - for text in texts: - print('\n"{}"'.format(text.description)) - - vertices = (['({},{})'.format(vertex.x, vertex.y) - for vertex in text.bounding_poly.vertices]) - - print('bounds: {}'.format(','.join(vertices))) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_text_detection_gcs] - - -# [START vision_image_property_detection] -def detect_properties(path): - """Detects image properties in the file.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_image_properties] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.image_properties(image=image) - props = response.image_properties_annotation - print('Properties:') - - for color in props.dominant_colors.colors: - print('fraction: {}'.format(color.pixel_fraction)) - print('\tr: {}'.format(color.color.red)) - print('\tg: {}'.format(color.color.green)) - print('\tb: {}'.format(color.color.blue)) - print('\ta: {}'.format(color.color.alpha)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_image_properties] -# [END vision_image_property_detection] - - -# [START vision_image_property_detection_gcs] -def detect_properties_uri(uri): - """Detects image properties in the file located in Google Cloud Storage or - on the Web.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.image_properties(image=image) - props = response.image_properties_annotation - print('Properties:') - - for color in props.dominant_colors.colors: - print('frac: {}'.format(color.pixel_fraction)) - print('\tr: {}'.format(color.color.red)) - print('\tg: {}'.format(color.color.green)) - print('\tb: {}'.format(color.color.blue)) - print('\ta: {}'.format(color.color.alpha)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_image_property_detection_gcs] - - -# [START vision_web_detection] -def detect_web(path): - """Detects web annotations given an image.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_web_detection] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.web_detection(image=image) - annotations = response.web_detection - - if annotations.best_guess_labels: - for label in annotations.best_guess_labels: - print('\nBest guess label: {}'.format(label.label)) - - if annotations.pages_with_matching_images: - print('\n{} Pages with matching images found:'.format( - len(annotations.pages_with_matching_images))) - - for page in annotations.pages_with_matching_images: - print('\n\tPage url : {}'.format(page.url)) - - if page.full_matching_images: - print('\t{} Full Matches found: '.format( - len(page.full_matching_images))) - - for image in page.full_matching_images: - print('\t\tImage url : {}'.format(image.url)) - - if page.partial_matching_images: - print('\t{} Partial Matches found: '.format( - len(page.partial_matching_images))) - - for image in page.partial_matching_images: - print('\t\tImage url : {}'.format(image.url)) - - if annotations.web_entities: - print('\n{} Web entities found: '.format( - len(annotations.web_entities))) - - for entity in annotations.web_entities: - print('\n\tScore : {}'.format(entity.score)) - print(u'\tDescription: {}'.format(entity.description)) - - if annotations.visually_similar_images: - print('\n{} visually similar images found:\n'.format( - len(annotations.visually_similar_images))) - - for image in annotations.visually_similar_images: - print('\tImage url : {}'.format(image.url)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_web_detection] -# [END vision_web_detection] - - -# [START vision_web_detection_gcs] -def detect_web_uri(uri): - """Detects web annotations in the file located in Google Cloud Storage.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.web_detection(image=image) - annotations = response.web_detection - - if annotations.best_guess_labels: - for label in annotations.best_guess_labels: - print('\nBest guess label: {}'.format(label.label)) - - if annotations.pages_with_matching_images: - print('\n{} Pages with matching images found:'.format( - len(annotations.pages_with_matching_images))) - - for page in annotations.pages_with_matching_images: - print('\n\tPage url : {}'.format(page.url)) - - if page.full_matching_images: - print('\t{} Full Matches found: '.format( - len(page.full_matching_images))) - - for image in page.full_matching_images: - print('\t\tImage url : {}'.format(image.url)) - - if page.partial_matching_images: - print('\t{} Partial Matches found: '.format( - len(page.partial_matching_images))) - - for image in page.partial_matching_images: - print('\t\tImage url : {}'.format(image.url)) - - if annotations.web_entities: - print('\n{} Web entities found: '.format( - len(annotations.web_entities))) - - for entity in annotations.web_entities: - print('\n\tScore : {}'.format(entity.score)) - print(u'\tDescription: {}'.format(entity.description)) - - if annotations.visually_similar_images: - print('\n{} visually similar images found:\n'.format( - len(annotations.visually_similar_images))) - - for image in annotations.visually_similar_images: - print('\tImage url : {}'.format(image.url)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_web_detection_gcs] - - -# [START vision_web_detection_include_geo] -def web_entities_include_geo_results(path): - """Detects web annotations given an image, using the geotag metadata - in the image to detect web entities.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - web_detection_params = vision.WebDetectionParams( - include_geo_results=True) - image_context = vision.ImageContext( - web_detection_params=web_detection_params) - - response = client.web_detection(image=image, image_context=image_context) - - for entity in response.web_detection.web_entities: - print('\n\tScore : {}'.format(entity.score)) - print(u'\tDescription: {}'.format(entity.description)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_web_detection_include_geo] - - -# [START vision_web_detection_include_geo_gcs] -def web_entities_include_geo_results_uri(uri): - """Detects web annotations given an image in the file located in - Google Cloud Storage., using the geotag metadata in the image to - detect web entities.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - - image = vision.Image() - image.source.image_uri = uri - - web_detection_params = vision.WebDetectionParams( - include_geo_results=True) - image_context = vision.ImageContext( - web_detection_params=web_detection_params) - - response = client.web_detection(image=image, image_context=image_context) - - for entity in response.web_detection.web_entities: - print('\n\tScore : {}'.format(entity.score)) - print(u'\tDescription: {}'.format(entity.description)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_web_detection_include_geo_gcs] - - -# [START vision_crop_hint_detection] -def detect_crop_hints(path): - """Detects crop hints in an image.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_crop_hints] - with io.open(path, 'rb') as image_file: - content = image_file.read() - image = vision.Image(content=content) - - crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.77]) - image_context = vision.ImageContext( - crop_hints_params=crop_hints_params) - - response = client.crop_hints(image=image, image_context=image_context) - hints = response.crop_hints_annotation.crop_hints - - for n, hint in enumerate(hints): - print('\nCrop Hint: {}'.format(n)) - - vertices = (['({},{})'.format(vertex.x, vertex.y) - for vertex in hint.bounding_poly.vertices]) - - print('bounds: {}'.format(','.join(vertices))) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_crop_hints] -# [END vision_crop_hint_detection] - - -# [START vision_crop_hint_detection_gcs] -def detect_crop_hints_uri(uri): - """Detects crop hints in the file located in Google Cloud Storage.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.77]) - image_context = vision.ImageContext( - crop_hints_params=crop_hints_params) - - response = client.crop_hints(image=image, image_context=image_context) - hints = response.crop_hints_annotation.crop_hints - - for n, hint in enumerate(hints): - print('\nCrop Hint: {}'.format(n)) - - vertices = (['({},{})'.format(vertex.x, vertex.y) - for vertex in hint.bounding_poly.vertices]) - - print('bounds: {}'.format(','.join(vertices))) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_crop_hint_detection_gcs] - - -# [START vision_fulltext_detection] -def detect_document(path): - """Detects document features in an image.""" - from google.cloud import vision - import io - client = vision.ImageAnnotatorClient() - - # [START vision_python_migration_document_text_detection] - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.document_text_detection(image=image) - - for page in response.full_text_annotation.pages: - for block in page.blocks: - print('\nBlock confidence: {}\n'.format(block.confidence)) - - for paragraph in block.paragraphs: - print('Paragraph confidence: {}'.format( - paragraph.confidence)) - - for word in paragraph.words: - word_text = ''.join([ - symbol.text for symbol in word.symbols - ]) - print('Word text: {} (confidence: {})'.format( - word_text, word.confidence)) - - for symbol in word.symbols: - print('\tSymbol: {} (confidence: {})'.format( - symbol.text, symbol.confidence)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - # [END vision_python_migration_document_text_detection] -# [END vision_fulltext_detection] - - -# [START vision_fulltext_detection_gcs] -def detect_document_uri(uri): - """Detects document features in the file located in Google Cloud - Storage.""" - from google.cloud import vision - client = vision.ImageAnnotatorClient() - image = vision.Image() - image.source.image_uri = uri - - response = client.document_text_detection(image=image) - - for page in response.full_text_annotation.pages: - for block in page.blocks: - print('\nBlock confidence: {}\n'.format(block.confidence)) - - for paragraph in block.paragraphs: - print('Paragraph confidence: {}'.format( - paragraph.confidence)) - - for word in paragraph.words: - word_text = ''.join([ - symbol.text for symbol in word.symbols - ]) - print('Word text: {} (confidence: {})'.format( - word_text, word.confidence)) - - for symbol in word.symbols: - print('\tSymbol: {} (confidence: {})'.format( - symbol.text, symbol.confidence)) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) -# [END vision_fulltext_detection_gcs] - - -# [START vision_text_detection_pdf_gcs] -def async_detect_document(gcs_source_uri, gcs_destination_uri): - """OCR with PDF/TIFF as source files on GCS""" - import json - import re - from google.cloud import vision - from google.cloud import storage - - # Supported mime_types are: 'application/pdf' and 'image/tiff' - mime_type = 'application/pdf' - - # How many pages should be grouped into each json output file. - batch_size = 2 - - client = vision.ImageAnnotatorClient() - - feature = vision.Feature( - type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) - - gcs_source = vision.GcsSource(uri=gcs_source_uri) - input_config = vision.InputConfig( - gcs_source=gcs_source, mime_type=mime_type) - - gcs_destination = vision.GcsDestination(uri=gcs_destination_uri) - output_config = vision.OutputConfig( - gcs_destination=gcs_destination, batch_size=batch_size) - - async_request = vision.AsyncAnnotateFileRequest( - features=[feature], input_config=input_config, - output_config=output_config) - - operation = client.async_batch_annotate_files( - requests=[async_request]) - - print('Waiting for the operation to finish.') - operation.result(timeout=420) - - # Once the request has completed and the output has been - # written to GCS, we can list all the output files. - storage_client = storage.Client() - - match = re.match(r'gs://([^/]+)/(.+)', gcs_destination_uri) - bucket_name = match.group(1) - prefix = match.group(2) - - bucket = storage_client.get_bucket(bucket_name) - - # List objects with the given prefix, filtering out folders. - blob_list = [blob for blob in list(bucket.list_blobs( - prefix=prefix)) if not blob.name.endswith('/')] - print('Output files:') - for blob in blob_list: - print(blob.name) - - # Process the first output file from GCS. - # Since we specified batch_size=2, the first response contains - # the first two pages of the input file. - output = blob_list[0] - - json_string = output.download_as_string() - response = json.loads(json_string) - - # The actual response for the first page of the input file. - first_page_response = response['responses'][0] - annotation = first_page_response['fullTextAnnotation'] - - # Here we print the full text from the first page. - # The response contains more information: - # annotation/pages/blocks/paragraphs/words/symbols - # including confidence scores and bounding boxes - print('Full text:\n') - print(annotation['text']) -# [END vision_text_detection_pdf_gcs] - - -# [START vision_localize_objects] -def localize_objects(path): - """Localize objects in the local image. - - Args: - path: The path to the local file. - """ - from google.cloud import vision - client = vision.ImageAnnotatorClient() - - with open(path, 'rb') as image_file: - content = image_file.read() - image = vision.Image(content=content) - - objects = client.object_localization( - image=image).localized_object_annotations - - print('Number of objects found: {}'.format(len(objects))) - for object_ in objects: - print('\n{} (confidence: {})'.format(object_.name, object_.score)) - print('Normalized bounding polygon vertices: ') - for vertex in object_.bounding_poly.normalized_vertices: - print(' - ({}, {})'.format(vertex.x, vertex.y)) -# [END vision_localize_objects] - - -# [START vision_localize_objects_gcs] -def localize_objects_uri(uri): - """Localize objects in the image on Google Cloud Storage - - Args: - uri: The path to the file in Google Cloud Storage (gs://...) - """ - from google.cloud import vision - client = vision.ImageAnnotatorClient() - - image = vision.Image() - image.source.image_uri = uri - - objects = client.object_localization( - image=image).localized_object_annotations - - print('Number of objects found: {}'.format(len(objects))) - for object_ in objects: - print('\n{} (confidence: {})'.format(object_.name, object_.score)) - print('Normalized bounding polygon vertices: ') - for vertex in object_.bounding_poly.normalized_vertices: - print(' - ({}, {})'.format(vertex.x, vertex.y)) -# [END vision_localize_objects_gcs] - - -def run_local(args): - if args.command == 'faces': - detect_faces(args.path) - elif args.command == 'labels': - detect_labels(args.path) - elif args.command == 'landmarks': - detect_landmarks(args.path) - elif args.command == 'text': - detect_text(args.path) - elif args.command == 'logos': - detect_logos(args.path) - elif args.command == 'safe-search': - detect_safe_search(args.path) - elif args.command == 'properties': - detect_properties(args.path) - elif args.command == 'web': - detect_web(args.path) - elif args.command == 'crophints': - detect_crop_hints(args.path) - elif args.command == 'document': - detect_document(args.path) - elif args.command == 'web-geo': - web_entities_include_geo_results(args.path) - elif args.command == 'object-localization': - localize_objects(args.path) - - -def run_uri(args): - if args.command == 'text-uri': - detect_text_uri(args.uri) - elif args.command == 'faces-uri': - detect_faces_uri(args.uri) - elif args.command == 'labels-uri': - detect_labels_uri(args.uri) - elif args.command == 'landmarks-uri': - detect_landmarks_uri(args.uri) - elif args.command == 'logos-uri': - detect_logos_uri(args.uri) - elif args.command == 'safe-search-uri': - detect_safe_search_uri(args.uri) - elif args.command == 'properties-uri': - detect_properties_uri(args.uri) - elif args.command == 'web-uri': - detect_web_uri(args.uri) - elif args.command == 'crophints-uri': - detect_crop_hints_uri(args.uri) - elif args.command == 'document-uri': - detect_document_uri(args.uri) - elif args.command == 'web-geo-uri': - web_entities_include_geo_results_uri(args.uri) - elif args.command == 'ocr-uri': - async_detect_document(args.uri, args.destination_uri) - elif args.command == 'object-localization-uri': - localize_objects_uri(args.uri) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - subparsers = parser.add_subparsers(dest='command') - - detect_faces_parser = subparsers.add_parser( - 'faces', help=detect_faces.__doc__) - detect_faces_parser.add_argument('path') - - faces_file_parser = subparsers.add_parser( - 'faces-uri', help=detect_faces_uri.__doc__) - faces_file_parser.add_argument('uri') - - detect_labels_parser = subparsers.add_parser( - 'labels', help=detect_labels.__doc__) - detect_labels_parser.add_argument('path') - - labels_file_parser = subparsers.add_parser( - 'labels-uri', help=detect_labels_uri.__doc__) - labels_file_parser.add_argument('uri') - - detect_landmarks_parser = subparsers.add_parser( - 'landmarks', help=detect_landmarks.__doc__) - detect_landmarks_parser.add_argument('path') - - landmark_file_parser = subparsers.add_parser( - 'landmarks-uri', help=detect_landmarks_uri.__doc__) - landmark_file_parser.add_argument('uri') - - detect_text_parser = subparsers.add_parser( - 'text', help=detect_text.__doc__) - detect_text_parser.add_argument('path') - - text_file_parser = subparsers.add_parser( - 'text-uri', help=detect_text_uri.__doc__) - text_file_parser.add_argument('uri') - - detect_logos_parser = subparsers.add_parser( - 'logos', help=detect_logos.__doc__) - detect_logos_parser.add_argument('path') - - logos_file_parser = subparsers.add_parser( - 'logos-uri', help=detect_logos_uri.__doc__) - logos_file_parser.add_argument('uri') - - safe_search_parser = subparsers.add_parser( - 'safe-search', help=detect_safe_search.__doc__) - safe_search_parser.add_argument('path') - - safe_search_file_parser = subparsers.add_parser( - 'safe-search-uri', - help=detect_safe_search_uri.__doc__) - safe_search_file_parser.add_argument('uri') - - properties_parser = subparsers.add_parser( - 'properties', help=detect_properties.__doc__) - properties_parser.add_argument('path') - - properties_file_parser = subparsers.add_parser( - 'properties-uri', - help=detect_properties_uri.__doc__) - properties_file_parser.add_argument('uri') - - # 1.1 Vision features - web_parser = subparsers.add_parser( - 'web', help=detect_web.__doc__) - web_parser.add_argument('path') - - web_uri_parser = subparsers.add_parser( - 'web-uri', - help=detect_web_uri.__doc__) - web_uri_parser.add_argument('uri') - - web_geo_parser = subparsers.add_parser( - 'web-geo', help=web_entities_include_geo_results.__doc__) - web_geo_parser.add_argument('path') - - web_geo_uri_parser = subparsers.add_parser( - 'web-geo-uri', - help=web_entities_include_geo_results_uri.__doc__) - web_geo_uri_parser.add_argument('uri') - - crop_hints_parser = subparsers.add_parser( - 'crophints', help=detect_crop_hints.__doc__) - crop_hints_parser.add_argument('path') - - crop_hints_uri_parser = subparsers.add_parser( - 'crophints-uri', help=detect_crop_hints_uri.__doc__) - crop_hints_uri_parser.add_argument('uri') - - document_parser = subparsers.add_parser( - 'document', help=detect_document.__doc__) - document_parser.add_argument('path') - - document_uri_parser = subparsers.add_parser( - 'document-uri', help=detect_document_uri.__doc__) - document_uri_parser.add_argument('uri') - - ocr_uri_parser = subparsers.add_parser( - 'ocr-uri', help=async_detect_document.__doc__) - ocr_uri_parser.add_argument('uri') - ocr_uri_parser.add_argument('destination_uri') - - object_localization_parser = subparsers.add_parser( - 'object-localization', help=async_detect_document.__doc__) - object_localization_parser.add_argument('path') - - object_localization_uri_parser = subparsers.add_parser( - 'object-localization-uri', help=async_detect_document.__doc__) - object_localization_uri_parser.add_argument('uri') - - args = parser.parse_args() - - if 'uri' in args.command: - run_uri(args) - else: - run_local(args) diff --git a/samples/snippets/detect/detect_test.py b/samples/snippets/detect/detect_test.py deleted file mode 100644 index 7735733f..00000000 --- a/samples/snippets/detect/detect_test.py +++ /dev/null @@ -1,285 +0,0 @@ -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import backoff -from google.cloud import storage -import pytest - -import detect - -ASSET_BUCKET = "cloud-samples-data" - -BUCKET = os.environ['CLOUD_STORAGE_BUCKET'] -OUTPUT_PREFIX = 'TEST_OUTPUT_{}'.format(uuid.uuid4()) -GCS_SOURCE_URI = 'gs://{}/HodgeConj.pdf'.format(BUCKET) -GCS_DESTINATION_URI = 'gs://{}/{}/'.format(BUCKET, OUTPUT_PREFIX) - - -def test_labels(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/wakeupcat.jpg') - detect.detect_labels(file_name) - out, _ = capsys.readouterr() - assert 'Labels' in out - - -def test_labels_uri(capsys): - file_name = 'gs://{}/vision/label/wakeupcat.jpg'.format(ASSET_BUCKET) - detect.detect_labels_uri(file_name) - out, _ = capsys.readouterr() - assert 'Labels' in out - - -def test_landmarks(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/landmark.jpg') - detect.detect_landmarks(file_name) - out, _ = capsys.readouterr() - assert 'palace' in out.lower() - - -def test_landmarks_uri(capsys): - file_name = 'gs://{}/vision/landmark/pofa.jpg'.format(ASSET_BUCKET) - detect.detect_landmarks_uri(file_name) - out, _ = capsys.readouterr() - assert 'palace' in out.lower() - - -def test_faces(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/face_no_surprise.jpg') - detect.detect_faces(file_name) - out, _ = capsys.readouterr() - assert 'face bound' in out - - -def test_faces_uri(capsys): - file_name = 'gs://{}/vision/face/face_no_surprise.jpg'.format(ASSET_BUCKET) - detect.detect_faces_uri(file_name) - out, _ = capsys.readouterr() - assert 'face bound' in out - - -def test_logos(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/logos.png') - detect.detect_logos(file_name) - out, _ = capsys.readouterr() - assert 'google' in out.lower() - - -def test_logos_uri(capsys): - file_name = 'gs://{}/vision/logo/logo_google.png'.format(ASSET_BUCKET) - detect.detect_logos_uri(file_name) - out, _ = capsys.readouterr() - assert 'google' in out.lower() - - -def test_safe_search(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/wakeupcat.jpg') - detect.detect_safe_search(file_name) - out, _ = capsys.readouterr() - assert 'VERY_LIKELY' in out - assert 'racy: ' in out - - -def test_safe_search_uri(capsys): - file_name = 'gs://{}/vision/label/wakeupcat.jpg'.format(ASSET_BUCKET) - detect.detect_safe_search_uri(file_name) - out, _ = capsys.readouterr() - assert 'VERY_LIKELY' in out - assert 'racy: ' in out - - -def test_detect_text(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/text.jpg') - detect.detect_text(file_name) - out, _ = capsys.readouterr() - assert '37%' in out - - -def test_detect_text_uri(capsys): - file_name = 'gs://{}/vision/text/screen.jpg'.format(ASSET_BUCKET) - detect.detect_text_uri(file_name) - out, _ = capsys.readouterr() - assert '37%' in out - - -def test_detect_properties(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/landmark.jpg') - detect.detect_properties(file_name) - out, _ = capsys.readouterr() - assert 'frac' in out - - -def test_detect_properties_uri(capsys): - file_name = 'gs://{}/vision/landmark/pofa.jpg'.format(ASSET_BUCKET) - detect.detect_properties_uri(file_name) - out, _ = capsys.readouterr() - assert 'frac' in out - - -def only_sample_error(e): - """A callback for giving up upon Exceptions. - - Giving up upon any Exceptions other than the ones that sample code - throws at the end of the function. - """ - return 'https://cloud.google.com/apis/design/errors' not in str(e) - - -# Vision 1.1 tests -def test_detect_web(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/landmark.jpg') - - @backoff.on_exception( - backoff.expo, Exception, max_time=60, giveup=only_sample_error) - def run_sample(): - detect.detect_web(file_name) - - run_sample() - out, _ = capsys.readouterr() - assert 'best guess label: palace of fine arts' in out.lower() - - -def test_detect_web_uri(capsys): - file_name = 'gs://{}/vision/landmark/pofa.jpg'.format(ASSET_BUCKET) - - @backoff.on_exception( - backoff.expo, Exception, max_time=60, giveup=only_sample_error) - def run_sample(): - detect.detect_web_uri(file_name) - - run_sample() - out, _ = capsys.readouterr() - assert 'best guess label: palace of fine arts' in out.lower() - - -def test_detect_web_with_geo(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/city.jpg') - - @backoff.on_exception( - backoff.expo, Exception, max_time=60, giveup=only_sample_error) - def run_sample(): - detect.web_entities_include_geo_results(file_name) - - run_sample() - out, _ = capsys.readouterr() - out = out.lower() - assert 'description' in out - - -def test_detect_web_with_geo_uri(capsys): - file_name = 'gs://{}/vision/web/city.jpg'.format(ASSET_BUCKET) - - @backoff.on_exception( - backoff.expo, Exception, max_time=60, giveup=only_sample_error) - def run_sample(): - detect.web_entities_include_geo_results_uri(file_name) - - run_sample() - out, _ = capsys.readouterr() - out = out.lower() - assert 'description' in out - - -def test_detect_document(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/text.jpg') - detect.detect_document(file_name) - out, _ = capsys.readouterr() - assert 'class' in out - - -def test_detect_document_uri(capsys): - file_name = 'gs://{}/vision/text/screen.jpg'.format(ASSET_BUCKET) - detect.detect_document_uri(file_name) - out, _ = capsys.readouterr() - assert 'class' in out - - -def test_detect_crop_hints(capsys): - file_name = os.path.join( - os.path.dirname(__file__), - 'resources/wakeupcat.jpg') - detect.detect_crop_hints(file_name) - out, _ = capsys.readouterr() - assert 'bounds: ' in out - - -def test_detect_crop_hints_uri(capsys): - file_name = 'gs://{}/vision/label/wakeupcat.jpg'.format(ASSET_BUCKET) - detect.detect_crop_hints_uri(file_name) - out, _ = capsys.readouterr() - assert 'bounds: ' in out - - -@pytest.mark.flaky(max_runs=3, min_passes=1) -def test_async_detect_document(capsys): - storage_client = storage.Client() - bucket = storage_client.get_bucket(BUCKET) - if len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) > 0: - for blob in bucket.list_blobs(prefix=OUTPUT_PREFIX): - blob.delete() - - assert len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) == 0 - - uri = 'gs://{}/vision/document/custom_0773375000_title_only.pdf'.format( - ASSET_BUCKET) - detect.async_detect_document( - gcs_source_uri=uri, - gcs_destination_uri=GCS_DESTINATION_URI) - out, _ = capsys.readouterr() - - assert 'OIL, GAS AND MINERAL LEASE' in out - assert len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) > 0 - - for blob in bucket.list_blobs(prefix=OUTPUT_PREFIX): - blob.delete() - - assert len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) == 0 - - -def test_localize_objects(capsys): - detect.localize_objects('resources/puppies.jpg') - - out, _ = capsys.readouterr() - assert 'dog' in out.lower() - - -def test_localize_objects_uri(capsys): - uri = 'gs://cloud-samples-data/vision/puppies.jpg' - - detect.localize_objects_uri(uri) - - out, _ = capsys.readouterr() - assert 'dog' in out.lower() diff --git a/samples/snippets/detect/noxfile.py b/samples/snippets/detect/noxfile.py deleted file mode 100644 index 0398d72f..00000000 --- a/samples/snippets/detect/noxfile.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, List, Optional - -import nox - - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--import-order-style=google", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") - else: - session.install("flake8", "flake8-import-order", "flake8-annotations") - - local_names = _determine_local_import_names(".") - args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob("**/test_*.py", recursive=True) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install( - "-r", "requirements-test.txt", "-c", "constraints-test.txt" - ) - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(['--workers', 'auto', '--tests-per-worker', 'auto']) - elif "pytest-xdist" in packages: - concurrent_args.extend(['-n', 'auto']) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/detect/requirements-test.txt b/samples/snippets/detect/requirements-test.txt deleted file mode 100644 index 38e673c2..00000000 --- a/samples/snippets/detect/requirements-test.txt +++ /dev/null @@ -1,3 +0,0 @@ -backoff==2.2.1 -pytest==7.1.3 -flaky==3.7.0 diff --git a/samples/snippets/detect/requirements.txt b/samples/snippets/detect/requirements.txt deleted file mode 100644 index ab0921e1..00000000 --- a/samples/snippets/detect/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -google-cloud-vision==3.1.3 -google-cloud-storage==2.5.0 diff --git a/samples/snippets/detect/resources/city.jpg b/samples/snippets/detect/resources/city.jpg deleted file mode 100644 index b14282e7..00000000 Binary files a/samples/snippets/detect/resources/city.jpg and /dev/null differ diff --git a/samples/snippets/detect/resources/cloud-samples-data/vision/document/custom_0773375000_title_only.pdf b/samples/snippets/detect/resources/cloud-samples-data/vision/document/custom_0773375000_title_only.pdf deleted file mode 100644 index 514ca6b1..00000000 Binary files a/samples/snippets/detect/resources/cloud-samples-data/vision/document/custom_0773375000_title_only.pdf and /dev/null differ diff --git a/samples/snippets/detect/resources/duck_and_truck.jpg b/samples/snippets/detect/resources/duck_and_truck.jpg deleted file mode 100644 index 5c560fe7..00000000 Binary files a/samples/snippets/detect/resources/duck_and_truck.jpg and /dev/null differ diff --git a/samples/snippets/detect/resources/face_no_surprise.jpg b/samples/snippets/detect/resources/face_no_surprise.jpg deleted file mode 100644 index 0e2894ad..00000000 Binary files a/samples/snippets/detect/resources/face_no_surprise.jpg and /dev/null differ diff --git a/samples/snippets/detect/resources/handwritten.jpg b/samples/snippets/detect/resources/handwritten.jpg deleted file mode 100644 index 50a9575b..00000000 Binary files a/samples/snippets/detect/resources/handwritten.jpg and /dev/null differ diff --git a/samples/snippets/detect/resources/kafka.pdf b/samples/snippets/detect/resources/kafka.pdf deleted file mode 100644 index ffa2e2fa..00000000 Binary files a/samples/snippets/detect/resources/kafka.pdf and /dev/null differ diff --git a/samples/snippets/detect/resources/landmark.jpg b/samples/snippets/detect/resources/landmark.jpg deleted file mode 100644 index 41c3d0fc..00000000 Binary files a/samples/snippets/detect/resources/landmark.jpg and /dev/null differ diff --git a/samples/snippets/detect/resources/logos.png b/samples/snippets/detect/resources/logos.png deleted file mode 100644 index 5538eaed..00000000 Binary files a/samples/snippets/detect/resources/logos.png and /dev/null differ diff --git a/samples/snippets/detect/resources/puppies.jpg b/samples/snippets/detect/resources/puppies.jpg deleted file mode 100644 index 1bfbbc9c..00000000 Binary files a/samples/snippets/detect/resources/puppies.jpg and /dev/null differ diff --git a/samples/snippets/detect/resources/text.jpg b/samples/snippets/detect/resources/text.jpg deleted file mode 100644 index 3b17d55d..00000000 Binary files a/samples/snippets/detect/resources/text.jpg and /dev/null differ diff --git a/samples/snippets/detect/resources/wakeupcat.jpg b/samples/snippets/detect/resources/wakeupcat.jpg deleted file mode 100644 index 139cf461..00000000 Binary files a/samples/snippets/detect/resources/wakeupcat.jpg and /dev/null differ diff --git a/samples/snippets/detect/set_endpoint.py b/samples/snippets/detect/set_endpoint.py deleted file mode 100644 index 1261b024..00000000 --- a/samples/snippets/detect/set_endpoint.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -def set_endpoint(): - """Change your endpoint""" - # [START vision_set_endpoint] - from google.cloud import vision - - client_options = {'api_endpoint': 'eu-vision.googleapis.com'} - - client = vision.ImageAnnotatorClient(client_options=client_options) - # [END vision_set_endpoint] - image_source = vision.ImageSource( - image_uri='gs://cloud-samples-data/vision/text/screen.jpg') - image = vision.Image(source=image_source) - - response = client.text_detection(image=image) - - print('Texts:') - for text in response.text_annotations: - print('{}'.format(text.description)) - - vertices = ['({},{})'.format(vertex.x, vertex.y) - for vertex in text.bounding_poly.vertices] - - print('bounds: {}\n'.format(','.join(vertices))) - - if response.error.message: - raise Exception( - '{}\nFor more info on error messages, check: ' - 'https://cloud.google.com/apis/design/errors'.format( - response.error.message)) - - -if __name__ == '__main__': - set_endpoint() diff --git a/samples/snippets/detect/vision_async_batch_annotate_images.py b/samples/snippets/detect/vision_async_batch_annotate_images.py deleted file mode 100644 index 68d4a298..00000000 --- a/samples/snippets/detect/vision_async_batch_annotate_images.py +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START vision_async_batch_annotate_images] - -from google.cloud import vision_v1 - - -def sample_async_batch_annotate_images( - input_image_uri="gs://cloud-samples-data/vision/label/wakeupcat.jpg", - output_uri="gs://your-bucket/prefix/", -): - """Perform async batch image annotation.""" - client = vision_v1.ImageAnnotatorClient() - - source = {"image_uri": input_image_uri} - image = {"source": source} - features = [ - {"type_": vision_v1.Feature.Type.LABEL_DETECTION}, - {"type_": vision_v1.Feature.Type.IMAGE_PROPERTIES}, - ] - - # Each requests element corresponds to a single image. To annotate more - # images, create a request element for each image and add it to - # the array of requests - requests = [{"image": image, "features": features}] - gcs_destination = {"uri": output_uri} - - # The max number of responses to output in each JSON file - batch_size = 2 - output_config = {"gcs_destination": gcs_destination, - "batch_size": batch_size} - - operation = client.async_batch_annotate_images(requests=requests, output_config=output_config) - - print("Waiting for operation to complete...") - response = operation.result(90) - - # The output is written to GCS with the provided output_uri as prefix - gcs_output_uri = response.output_config.gcs_destination.uri - print("Output written to GCS with prefix: {}".format(gcs_output_uri)) - - -# [END vision_async_batch_annotate_images] diff --git a/samples/snippets/detect/vision_async_batch_annotate_images_test.py b/samples/snippets/detect/vision_async_batch_annotate_images_test.py deleted file mode 100644 index f025d662..00000000 --- a/samples/snippets/detect/vision_async_batch_annotate_images_test.py +++ /dev/null @@ -1,63 +0,0 @@ -# Copyright 2020 Google -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -from google.cloud import storage -import pytest - -import vision_async_batch_annotate_images - -RESOURCES = os.path.join(os.path.dirname(__file__), "resources") -GCS_ROOT = "gs://cloud-samples-data/vision/" - -BUCKET = os.environ["CLOUD_STORAGE_BUCKET"] -OUTPUT_PREFIX = "TEST_OUTPUT_{}".format(uuid.uuid4()) -GCS_DESTINATION_URI = "gs://{}/{}/".format(BUCKET, OUTPUT_PREFIX) - - -@pytest.fixture() -def storage_client(): - yield storage.Client() - - -@pytest.fixture() -def bucket(storage_client): - bucket = storage_client.get_bucket(BUCKET) - - try: - for blob in bucket.list_blobs(prefix=OUTPUT_PREFIX): - blob.delete() - except Exception: - pass - - yield bucket - - for blob in bucket.list_blobs(prefix=OUTPUT_PREFIX): - blob.delete() - - -@pytest.mark.flaky(max_runs=3, min_passes=1) -def test_sample_asyn_batch_annotate_images(storage_client, bucket, capsys): - input_image_uri = os.path.join(GCS_ROOT, "label/wakeupcat.jpg") - - vision_async_batch_annotate_images.sample_async_batch_annotate_images( - input_image_uri=input_image_uri, output_uri=GCS_DESTINATION_URI - ) - - out, _ = capsys.readouterr() - - assert "Output written to GCS" in out - assert len(list(bucket.list_blobs(prefix=OUTPUT_PREFIX))) > 0 diff --git a/samples/snippets/detect/vision_batch_annotate_files.py b/samples/snippets/detect/vision_batch_annotate_files.py deleted file mode 100644 index 98345840..00000000 --- a/samples/snippets/detect/vision_batch_annotate_files.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START vision_batch_annotate_files] - -import io - -from google.cloud import vision_v1 - - -def sample_batch_annotate_files(file_path="path/to/your/document.pdf"): - """Perform batch file annotation.""" - client = vision_v1.ImageAnnotatorClient() - - # Supported mime_type: application/pdf, image/tiff, image/gif - mime_type = "application/pdf" - with io.open(file_path, "rb") as f: - content = f.read() - input_config = {"mime_type": mime_type, "content": content} - features = [{"type_": vision_v1.Feature.Type.DOCUMENT_TEXT_DETECTION}] - - # The service can process up to 5 pages per document file. Here we specify - # the first, second, and last page of the document to be processed. - pages = [1, 2, -1] - requests = [{"input_config": input_config, "features": features, "pages": pages}] - - response = client.batch_annotate_files(requests=requests) - for image_response in response.responses[0].responses: - print(u"Full text: {}".format(image_response.full_text_annotation.text)) - for page in image_response.full_text_annotation.pages: - for block in page.blocks: - print(u"\nBlock confidence: {}".format(block.confidence)) - for par in block.paragraphs: - print(u"\tParagraph confidence: {}".format(par.confidence)) - for word in par.words: - print(u"\t\tWord confidence: {}".format(word.confidence)) - for symbol in word.symbols: - print( - u"\t\t\tSymbol: {}, (confidence: {})".format( - symbol.text, symbol.confidence - ) - ) - - -# [END vision_batch_annotate_files] diff --git a/samples/snippets/detect/vision_batch_annotate_files_gcs.py b/samples/snippets/detect/vision_batch_annotate_files_gcs.py deleted file mode 100644 index 0cd0c204..00000000 --- a/samples/snippets/detect/vision_batch_annotate_files_gcs.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# [START vision_batch_annotate_files_gcs] - -from google.cloud import vision_v1 - - -def sample_batch_annotate_files( - storage_uri="gs://cloud-samples-data/vision/document_understanding/kafka.pdf", -): - """Perform batch file annotation.""" - mime_type = "application/pdf" - - client = vision_v1.ImageAnnotatorClient() - - gcs_source = {"uri": storage_uri} - input_config = {"gcs_source": gcs_source, "mime_type": mime_type} - features = [{"type_": vision_v1.Feature.Type.DOCUMENT_TEXT_DETECTION}] - - # The service can process up to 5 pages per document file. - # Here we specify the first, second, and last page of the document to be - # processed. - pages = [1, 2, -1] - requests = [{"input_config": input_config, "features": features, "pages": pages}] - - response = client.batch_annotate_files(requests=requests) - for image_response in response.responses[0].responses: - print(u"Full text: {}".format(image_response.full_text_annotation.text)) - for page in image_response.full_text_annotation.pages: - for block in page.blocks: - print(u"\nBlock confidence: {}".format(block.confidence)) - for par in block.paragraphs: - print(u"\tParagraph confidence: {}".format(par.confidence)) - for word in par.words: - print(u"\t\tWord confidence: {}".format(word.confidence)) - for symbol in word.symbols: - print( - u"\t\t\tSymbol: {}, (confidence: {})".format( - symbol.text, symbol.confidence - ) - ) - - -# [END vision_batch_annotate_files_gcs] diff --git a/samples/snippets/detect/vision_batch_annotate_files_gcs_test.py b/samples/snippets/detect/vision_batch_annotate_files_gcs_test.py deleted file mode 100644 index 6e861762..00000000 --- a/samples/snippets/detect/vision_batch_annotate_files_gcs_test.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2020 Google -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os - -import vision_batch_annotate_files_gcs - -GCS_ROOT = "gs://cloud-samples-data/vision/" - - -def test_sample_batch_annotate_files_gcs(capsys): - storage_uri = os.path.join(GCS_ROOT, "document_understanding/kafka.pdf") - - vision_batch_annotate_files_gcs.sample_batch_annotate_files(storage_uri=storage_uri) - - out, _ = capsys.readouterr() - - assert "Full text" in out - assert "Block confidence" in out diff --git a/samples/snippets/document_text/.gitignore b/samples/snippets/document_text/.gitignore deleted file mode 100644 index a4c44706..00000000 --- a/samples/snippets/document_text/.gitignore +++ /dev/null @@ -1 +0,0 @@ -output-text.jpg diff --git a/samples/snippets/document_text/README.rst b/samples/snippets/document_text/README.rst deleted file mode 100644 index a38564a2..00000000 --- a/samples/snippets/document_text/README.rst +++ /dev/null @@ -1,111 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Vision API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/document_text/README.rst - - -This directory contains samples for Google Cloud Vision API. `Google Cloud Vision API`_ allows developers to easily integrate vision detection features within applications, including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. - -- See the `migration guide`_ for information about migrating to Python client library v0.25.1. - -.. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - - - - -.. _Google Cloud Vision API: https://cloud.google.com/vision/docs - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Samples -------------------------------------------------------------------------------- - -Document Text tutorial -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/document_text/doctext.py,vision/cloud-client/document_text/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python doctext.py - - usage: doctext.py [-h] [-out_file OUT_FILE] detect_file - - positional arguments: - detect_file The image for text detection. - - optional arguments: - -h, --help show this help message and exit - -out_file OUT_FILE Optional output file - - - - - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/document_text/README.rst.in b/samples/snippets/document_text/README.rst.in deleted file mode 100644 index 4746e327..00000000 --- a/samples/snippets/document_text/README.rst.in +++ /dev/null @@ -1,30 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Vision API - short_name: Cloud Vision API - url: https://cloud.google.com/vision/docs - description: > - `Google Cloud Vision API`_ allows developers to easily integrate vision - detection features within applications, including image labeling, face and - landmark detection, optical character recognition (OCR), and tagging of - explicit content. - - - - See the `migration guide`_ for information about migrating to Python client library v0.25.1. - - - .. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - -setup: -- auth -- install_deps - -samples: -- name: Document Text tutorial - file: doctext.py - show_help: True - -cloud_client_library: true - -folder: vision/cloud-client/document_text \ No newline at end of file diff --git a/samples/snippets/document_text/doctext.py b/samples/snippets/document_text/doctext.py deleted file mode 100644 index 6bfb2b90..00000000 --- a/samples/snippets/document_text/doctext.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Outlines document text given an image. - -Example: - python doctext.py resources/text_menu.jpg -""" -# [START vision_document_text_tutorial] -# [START vision_document_text_tutorial_imports] -import argparse -from enum import Enum -import io - -from google.cloud import vision -from PIL import Image, ImageDraw -# [END vision_document_text_tutorial_imports] - - -class FeatureType(Enum): - PAGE = 1 - BLOCK = 2 - PARA = 3 - WORD = 4 - SYMBOL = 5 - - -def draw_boxes(image, bounds, color): - """Draw a border around the image using the hints in the vector list.""" - draw = ImageDraw.Draw(image) - - for bound in bounds: - draw.polygon( - [ - bound.vertices[0].x, - bound.vertices[0].y, - bound.vertices[1].x, - bound.vertices[1].y, - bound.vertices[2].x, - bound.vertices[2].y, - bound.vertices[3].x, - bound.vertices[3].y, - ], - None, - color, - ) - return image - - -# [START vision_document_text_tutorial_detect_bounds] -def get_document_bounds(image_file, feature): - """Returns document bounds given an image.""" - client = vision.ImageAnnotatorClient() - - bounds = [] - - with io.open(image_file, "rb") as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - response = client.document_text_detection(image=image) - document = response.full_text_annotation - - # Collect specified feature bounds by enumerating all document features - for page in document.pages: - for block in page.blocks: - for paragraph in block.paragraphs: - for word in paragraph.words: - for symbol in word.symbols: - if feature == FeatureType.SYMBOL: - bounds.append(symbol.bounding_box) - - if feature == FeatureType.WORD: - bounds.append(word.bounding_box) - - if feature == FeatureType.PARA: - bounds.append(paragraph.bounding_box) - - if feature == FeatureType.BLOCK: - bounds.append(block.bounding_box) - - # The list `bounds` contains the coordinates of the bounding boxes. - return bounds -# [END vision_document_text_tutorial_detect_bounds] - - -def render_doc_text(filein, fileout): - image = Image.open(filein) - bounds = get_document_bounds(filein, FeatureType.BLOCK) - draw_boxes(image, bounds, "blue") - bounds = get_document_bounds(filein, FeatureType.PARA) - draw_boxes(image, bounds, "red") - bounds = get_document_bounds(filein, FeatureType.WORD) - draw_boxes(image, bounds, "yellow") - - if fileout != 0: - image.save(fileout) - else: - image.show() - - -if __name__ == "__main__": - # [START vision_document_text_tutorial_run_application] - parser = argparse.ArgumentParser() - parser.add_argument("detect_file", help="The image for text detection.") - parser.add_argument("-out_file", help="Optional output file", default=0) - args = parser.parse_args() - - render_doc_text(args.detect_file, args.out_file) - # [END vision_document_text_tutorial_run_application] -# [END vision_document_text_tutorial] diff --git a/samples/snippets/document_text/noxfile.py b/samples/snippets/document_text/noxfile.py deleted file mode 100644 index 0398d72f..00000000 --- a/samples/snippets/document_text/noxfile.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, List, Optional - -import nox - - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--import-order-style=google", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") - else: - session.install("flake8", "flake8-import-order", "flake8-annotations") - - local_names = _determine_local_import_names(".") - args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob("**/test_*.py", recursive=True) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install( - "-r", "requirements-test.txt", "-c", "constraints-test.txt" - ) - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(['--workers', 'auto', '--tests-per-worker', 'auto']) - elif "pytest-xdist" in packages: - concurrent_args.extend(['-n', 'auto']) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/document_text/noxfile_config.py b/samples/snippets/document_text/noxfile_config.py deleted file mode 100644 index e5578c31..00000000 --- a/samples/snippets/document_text/noxfile_config.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Default TEST_CONFIG_OVERRIDE for python repos. - -# You can copy this file into your directory, then it will be inported from -# the noxfile.py. - -# The source of truth: -# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py - -TEST_CONFIG_OVERRIDE = { - # You can opt out from the test for specific Python versions. - # Pillow 9.0.0 does not support python 3.6 - "ignored_versions": ["3.6"], -} diff --git a/samples/snippets/document_text/requirements-test.txt b/samples/snippets/document_text/requirements-test.txt deleted file mode 100644 index e0716850..00000000 --- a/samples/snippets/document_text/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.1.3 diff --git a/samples/snippets/document_text/requirements.txt b/samples/snippets/document_text/requirements.txt deleted file mode 100644 index c524155a..00000000 --- a/samples/snippets/document_text/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -google-cloud-vision==3.1.3 -pillow==9.2.0 diff --git a/samples/snippets/document_text/resources/text_menu.jpg b/samples/snippets/document_text/resources/text_menu.jpg deleted file mode 100644 index caa678b3..00000000 Binary files a/samples/snippets/document_text/resources/text_menu.jpg and /dev/null differ diff --git a/samples/snippets/face_detection/.gitignore b/samples/snippets/face_detection/.gitignore deleted file mode 100644 index 01f02dff..00000000 --- a/samples/snippets/face_detection/.gitignore +++ /dev/null @@ -1 +0,0 @@ -out.jpg diff --git a/samples/snippets/face_detection/README.rst b/samples/snippets/face_detection/README.rst deleted file mode 100644 index b04a344e..00000000 --- a/samples/snippets/face_detection/README.rst +++ /dev/null @@ -1,101 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Vision API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/face_detection/README.rst - - -This directory contains samples for Google Cloud Vision API. `Google Cloud Vision API`_ allows developers to easily integrate vision detection features within applications, including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. - -- See the `migration guide`_ for information about migrating to Python client library v0.25.1. - -.. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - - -This sample demonstrates how to use the Cloud Vision API to do face detection. - - -.. _Google Cloud Vision API: https://cloud.google.com/vision/docs - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Samples -------------------------------------------------------------------------------- - -Face detection -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/face_detection/faces.py,vision/cloud-client/face_detection/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python faces.py - - usage: faces.py [-h] [--out OUTPUT] [--max-results MAX_RESULTS] input_image - - Detects faces in the given image. - - positional arguments: - input_image the image you'd like to detect faces in. - - optional arguments: - -h, --help show this help message and exit - --out OUTPUT the name of the output file. - --max-results MAX_RESULTS - the max results of face detection. - - - - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/face_detection/README.rst.in b/samples/snippets/face_detection/README.rst.in deleted file mode 100644 index 422cec1d..00000000 --- a/samples/snippets/face_detection/README.rst.in +++ /dev/null @@ -1,31 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Vision API - short_name: Cloud Vision API - url: https://cloud.google.com/vision/docs - description: > - `Google Cloud Vision API`_ allows developers to easily integrate vision - detection features within applications, including image labeling, face and - landmark detection, optical character recognition (OCR), and tagging of - explicit content. - - - - See the `migration guide`_ for information about migrating to Python client library v0.25.1. - - - .. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - -description: > - This sample demonstrates how to use the Cloud Vision API to do face detection. - -setup: -- auth -- install_deps - -samples: -- name: Face detection - file: faces.py - show_help: true - -folder: vision/cloud-client/face_detection \ No newline at end of file diff --git a/samples/snippets/face_detection/faces.py b/samples/snippets/face_detection/faces.py deleted file mode 100755 index b325e0ce..00000000 --- a/samples/snippets/face_detection/faces.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2015 Google, Inc -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Draws squares around detected faces in the given image.""" - -import argparse - -# [START vision_face_detection_tutorial_imports] -from google.cloud import vision -from PIL import Image, ImageDraw -# [END vision_face_detection_tutorial_imports] - - -# [START vision_face_detection_tutorial_send_request] -def detect_face(face_file, max_results=4): - """Uses the Vision API to detect faces in the given file. - - Args: - face_file: A file-like object containing an image with faces. - - Returns: - An array of Face objects with information about the picture. - """ - # [START vision_face_detection_tutorial_client] - client = vision.ImageAnnotatorClient() - # [END vision_face_detection_tutorial_client] - - content = face_file.read() - image = vision.Image(content=content) - - return client.face_detection( - image=image, max_results=max_results).face_annotations -# [END vision_face_detection_tutorial_send_request] - - -# [START vision_face_detection_tutorial_process_response] -def highlight_faces(image, faces, output_filename): - """Draws a polygon around the faces, then saves to output_filename. - - Args: - image: a file containing the image with the faces. - faces: a list of faces found in the file. This should be in the format - returned by the Vision API. - output_filename: the name of the image file to be created, where the - faces have polygons drawn around them. - """ - im = Image.open(image) - draw = ImageDraw.Draw(im) - # Sepecify the font-family and the font-size - for face in faces: - box = [(vertex.x, vertex.y) - for vertex in face.bounding_poly.vertices] - draw.line(box + [box[0]], width=5, fill='#00ff00') - # Place the confidence value/score of the detected faces above the - # detection box in the output image - draw.text(((face.bounding_poly.vertices)[0].x, - (face.bounding_poly.vertices)[0].y - 30), - str(format(face.detection_confidence, '.3f')) + '%', - fill='#FF0000') - im.save(output_filename) -# [END vision_face_detection_tutorial_process_response] - - -# [START vision_face_detection_tutorial_run_application] -def main(input_filename, output_filename, max_results): - with open(input_filename, 'rb') as image: - faces = detect_face(image, max_results) - print('Found {} face{}'.format( - len(faces), '' if len(faces) == 1 else 's')) - - print('Writing to file {}'.format(output_filename)) - # Reset the file pointer, so we can read the file again - image.seek(0) - highlight_faces(image, faces, output_filename) -# [END vision_face_detection_tutorial_run_application] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description='Detects faces in the given image.') - parser.add_argument( - 'input_image', help='the image you\'d like to detect faces in.') - parser.add_argument( - '--out', dest='output', default='out.jpg', - help='the name of the output file.') - parser.add_argument( - '--max-results', dest='max_results', default=4, - help='the max results of face detection.') - args = parser.parse_args() - - main(args.input_image, args.output, args.max_results) diff --git a/samples/snippets/face_detection/faces_test.py b/samples/snippets/face_detection/faces_test.py deleted file mode 100644 index cca63c20..00000000 --- a/samples/snippets/face_detection/faces_test.py +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright 2016, Google, Inc. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os - -from PIL import Image - -from faces import main - -RESOURCES = os.path.join(os.path.dirname(__file__), 'resources') - - -def test_main(tmpdir): - out_file = os.path.join(tmpdir.dirname, 'face-output.jpg') - in_file = os.path.join(RESOURCES, 'face-input.jpg') - - # Make sure there isn't already a green box - im = Image.open(in_file) - pixels = im.getdata() - greens = sum(1 for (r, g, b) in pixels if r == 0 and g == 255 and b == 0) - assert greens < 1 - - main(in_file, out_file, 10) - - # Make sure there now is some green drawn - im = Image.open(out_file) - pixels = im.getdata() - greens = sum(1 for (r, g, b) in pixels if r == 0 and g == 255 and b == 0) - assert greens > 10 diff --git a/samples/snippets/face_detection/noxfile.py b/samples/snippets/face_detection/noxfile.py deleted file mode 100644 index 0398d72f..00000000 --- a/samples/snippets/face_detection/noxfile.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, List, Optional - -import nox - - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--import-order-style=google", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") - else: - session.install("flake8", "flake8-import-order", "flake8-annotations") - - local_names = _determine_local_import_names(".") - args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob("**/test_*.py", recursive=True) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install( - "-r", "requirements-test.txt", "-c", "constraints-test.txt" - ) - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(['--workers', 'auto', '--tests-per-worker', 'auto']) - elif "pytest-xdist" in packages: - concurrent_args.extend(['-n', 'auto']) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/face_detection/noxfile_config.py b/samples/snippets/face_detection/noxfile_config.py deleted file mode 100644 index e5578c31..00000000 --- a/samples/snippets/face_detection/noxfile_config.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2021 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Default TEST_CONFIG_OVERRIDE for python repos. - -# You can copy this file into your directory, then it will be inported from -# the noxfile.py. - -# The source of truth: -# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py - -TEST_CONFIG_OVERRIDE = { - # You can opt out from the test for specific Python versions. - # Pillow 9.0.0 does not support python 3.6 - "ignored_versions": ["3.6"], -} diff --git a/samples/snippets/face_detection/requirements-test.txt b/samples/snippets/face_detection/requirements-test.txt deleted file mode 100644 index e0716850..00000000 --- a/samples/snippets/face_detection/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.1.3 diff --git a/samples/snippets/face_detection/requirements.txt b/samples/snippets/face_detection/requirements.txt deleted file mode 100644 index c524155a..00000000 --- a/samples/snippets/face_detection/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -google-cloud-vision==3.1.3 -pillow==9.2.0 diff --git a/samples/snippets/face_detection/resources/face-input.jpg b/samples/snippets/face_detection/resources/face-input.jpg deleted file mode 100644 index c0ee5580..00000000 Binary files a/samples/snippets/face_detection/resources/face-input.jpg and /dev/null differ diff --git a/samples/snippets/product_search/create_product_set_test.py b/samples/snippets/product_search/create_product_set_test.py deleted file mode 100644 index 5dc5190c..00000000 --- a/samples/snippets/product_search/create_product_set_test.py +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import pytest - -from product_set_management import ( - create_product_set, delete_product_set, list_product_sets) - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -PRODUCT_SET_DISPLAY_NAME = 'fake_product_set_display_name_for_testing' -PRODUCT_SET_ID = 'test_{}'.format(uuid.uuid4()) - - -@pytest.fixture(scope="function", autouse=True) -def teardown(): - yield - - # tear down - delete_product_set(PROJECT_ID, LOCATION, PRODUCT_SET_ID) - - -def test_create_product_set(capsys): - create_product_set( - PROJECT_ID, LOCATION, PRODUCT_SET_ID, - PRODUCT_SET_DISPLAY_NAME) - list_product_sets(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_SET_ID in out diff --git a/samples/snippets/product_search/create_product_test.py b/samples/snippets/product_search/create_product_test.py deleted file mode 100644 index a4e55f14..00000000 --- a/samples/snippets/product_search/create_product_test.py +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import pytest - -from product_management import create_product, delete_product, list_products - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -PRODUCT_DISPLAY_NAME = 'fake_product_display_name_for_testing' -PRODUCT_CATEGORY = 'homegoods' -PRODUCT_ID = 'test_{}'.format(uuid.uuid4()) - - -@pytest.fixture(scope="function", autouse=True) -def teardown(): - yield - - # tear down - delete_product(PROJECT_ID, LOCATION, PRODUCT_ID) - - -def test_create_product(capsys): - create_product( - PROJECT_ID, LOCATION, PRODUCT_ID, - PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY) - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_ID in out diff --git a/samples/snippets/product_search/import_product_sets.py b/samples/snippets/product_search/import_product_sets.py deleted file mode 100755 index e2937509..00000000 --- a/samples/snippets/product_search/import_product_sets.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This application demonstrates how to perform import product sets operations -on Product set in Cloud Vision Product Search. - -For more information, see the tutorial page at -https://cloud.google.com/vision/product-search/docs/ -""" - -import argparse - -# [START vision_product_search_tutorial_import] -from google.cloud import vision -# [END vision_product_search_tutorial_import] - - -# [START vision_product_search_import_product_images] -def import_product_sets(project_id, location, gcs_uri): - """Import images of different products in the product set. - Args: - project_id: Id of the project. - location: A compute region name. - gcs_uri: Google Cloud Storage URI. - Target files must be in Product Search CSV format. - """ - client = vision.ProductSearchClient() - - # A resource that represents Google Cloud Platform location. - location_path = f"projects/{project_id}/locations/{location}" - - # Set the input configuration along with Google Cloud Storage URI - gcs_source = vision.ImportProductSetsGcsSource( - csv_file_uri=gcs_uri) - input_config = vision.ImportProductSetsInputConfig( - gcs_source=gcs_source) - - # Import the product sets from the input URI. - response = client.import_product_sets( - parent=location_path, input_config=input_config) - - print('Processing operation name: {}'.format(response.operation.name)) - # synchronous check of operation status - result = response.result() - print('Processing done.') - - for i, status in enumerate(result.statuses): - print('Status of processing line {} of the csv: {}'.format( - i, status)) - # Check the status of reference image - # `0` is the code for OK in google.rpc.Code. - if status.code == 0: - reference_image = result.reference_images[i] - print(reference_image) - else: - print('Status code not OK: {}'.format(status.message)) -# [END vision_product_search_import_product_images] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - subparsers = parser.add_subparsers(dest='command') - parser.add_argument( - '--project_id', - help='Project id. Required', - required=True) - parser.add_argument( - '--location', - help='Compute region name', - default='us-west1') - - import_product_sets_parser = subparsers.add_parser( - 'import_product_sets', help=import_product_sets.__doc__) - import_product_sets_parser.add_argument('gcs_uri') - - args = parser.parse_args() - - if args.command == 'import_product_sets': - import_product_sets(args.project_id, args.location, args.gcs_uri) diff --git a/samples/snippets/product_search/import_product_sets_test.py b/samples/snippets/product_search/import_product_sets_test.py deleted file mode 100644 index b4faf8e5..00000000 --- a/samples/snippets/product_search/import_product_sets_test.py +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -from google.cloud import storage -import pytest - -from import_product_sets import import_product_sets -from product_in_product_set_management import list_products_in_product_set -from product_management import delete_product, list_products -from product_set_management import delete_product_set, list_product_sets -from reference_image_management import list_reference_images - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -FILENAME = uuid.uuid4() -GCS_URI = 'gs://{}/vision/{}.csv'.format(PROJECT_ID, FILENAME) -PRODUCT_SET_DISPLAY_NAME = 'fake_product_set_display_name_for_testing' -PRODUCT_SET_ID = 'test_{}'.format(uuid.uuid4()) -PRODUCT_ID_1 = 'test_{}'.format(uuid.uuid4()) -IMAGE_URI_1 = 'shoes_1.jpg' - - -@pytest.fixture(scope="function", autouse=True) -def setup_teardown(): - # Create the product set csv file locally and upload it to GCS - # This is so that there is a unique product set ID for all python version - # tests. - client = storage.Client(project=PROJECT_ID) - bucket = client.get_bucket(PROJECT_ID) - blob = storage.Blob("vision/{}.csv".format(FILENAME), bucket) - blob.upload_from_string( - '"gs://cloud-samples-data/vision/product_search/shoes_1.jpg",' + - '"{}",'.format(IMAGE_URI_1) + - '"{}",'.format(PRODUCT_SET_ID) + - '"{}",'.format(PRODUCT_ID_1) + - '"apparel",,"style=womens","0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9"') - - yield - - delete_product(PROJECT_ID, LOCATION, PRODUCT_ID_1) - delete_product_set(PROJECT_ID, LOCATION, PRODUCT_SET_ID) - # Delete the created file - blob.delete(client) - - -def test_import_product_sets(capsys): - import_product_sets(PROJECT_ID, LOCATION, GCS_URI) - - list_product_sets(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_SET_ID in out - - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_ID_1 in out - - list_products_in_product_set(PROJECT_ID, LOCATION, PRODUCT_SET_ID) - out, _ = capsys.readouterr() - assert PRODUCT_ID_1 in out - - list_reference_images(PROJECT_ID, LOCATION, PRODUCT_ID_1) - out, _ = capsys.readouterr() - assert IMAGE_URI_1 in out diff --git a/samples/snippets/product_search/noxfile.py b/samples/snippets/product_search/noxfile.py deleted file mode 100644 index 0398d72f..00000000 --- a/samples/snippets/product_search/noxfile.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, List, Optional - -import nox - - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--import-order-style=google", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") - else: - session.install("flake8", "flake8-import-order", "flake8-annotations") - - local_names = _determine_local_import_names(".") - args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob("**/test_*.py", recursive=True) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install( - "-r", "requirements-test.txt", "-c", "constraints-test.txt" - ) - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(['--workers', 'auto', '--tests-per-worker', 'auto']) - elif "pytest-xdist" in packages: - concurrent_args.extend(['-n', 'auto']) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/product_search/product_in_product_set_management.py b/samples/snippets/product_search/product_in_product_set_management.py deleted file mode 100755 index 5dec3c2a..00000000 --- a/samples/snippets/product_search/product_in_product_set_management.py +++ /dev/null @@ -1,208 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This application demonstrates how to perform create operations -on Product set in Cloud Vision Product Search. - -For more information, see the tutorial page at -https://cloud.google.com/vision/product-search/docs/ -""" - -import argparse - -# [START vision_product_search_add_product_to_product_set] -# [START vision_product_search_remove_product_from_product_set] -# [START vision_product_search_purge_products_in_product_set] -from google.cloud import vision - -# [END vision_product_search_add_product_to_product_set] -# [END vision_product_search_remove_product_from_product_set] -# [END vision_product_search_purge_products_in_product_set] - - -# [START vision_product_search_add_product_to_product_set] -def add_product_to_product_set( - project_id, location, product_id, product_set_id): - """Add a product to a product set. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - product_set_id: Id of the product set. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product set. - product_set_path = client.product_set_path( - project=project_id, location=location, - product_set=product_set_id) - - # Get the full path of the product. - product_path = client.product_path( - project=project_id, location=location, product=product_id) - - # Add the product to the product set. - client.add_product_to_product_set( - name=product_set_path, product=product_path) - print('Product added to product set.') -# [END vision_product_search_add_product_to_product_set] - - -# [START vision_product_search_list_products_in_product_set] -def list_products_in_product_set( - project_id, location, product_set_id): - """List all products in a product set. - Args: - project_id: Id of the project. - location: A compute region name. - product_set_id: Id of the product set. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product set. - product_set_path = client.product_set_path( - project=project_id, location=location, - product_set=product_set_id) - - # List all the products available in the product set. - products = client.list_products_in_product_set(name=product_set_path) - - # Display the product information. - for product in products: - print('Product name: {}'.format(product.name)) - print('Product id: {}'.format(product.name.split('/')[-1])) - print('Product display name: {}'.format(product.display_name)) - print('Product description: {}'.format(product.description)) - print('Product category: {}'.format(product.product_category)) - print('Product labels: {}'.format(product.product_labels)) -# [END vision_product_search_list_products_in_product_set] - - -# [START vision_product_search_remove_product_from_product_set] -def remove_product_from_product_set( - project_id, location, product_id, product_set_id): - """Remove a product from a product set. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - product_set_id: Id of the product set. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product set. - product_set_path = client.product_set_path( - project=project_id, location=location, - product_set=product_set_id) - - # Get the full path of the product. - product_path = client.product_path( - project=project_id, location=location, product=product_id) - - # Remove the product from the product set. - client.remove_product_from_product_set( - name=product_set_path, product=product_path) - print('Product removed from product set.') -# [END vision_product_search_remove_product_from_product_set] - - -# [START vision_product_search_purge_products_in_product_set] -def purge_products_in_product_set( - project_id, location, product_set_id, force): - """Delete all products in a product set. - Args: - project_id: Id of the project. - location: A compute region name. - product_set_id: Id of the product set. - force: Perform the purge only when force is set to True. - """ - client = vision.ProductSearchClient() - - parent = f"projects/{project_id}/locations/{location}" - - product_set_purge_config = vision.ProductSetPurgeConfig( - product_set_id=product_set_id) - - # The purge operation is async. - operation = client.purge_products(request={ - "parent": parent, - "product_set_purge_config": product_set_purge_config, - # The operation is irreversible and removes multiple products. - # The user is required to pass in force=True to actually perform the - # purge. - # If force is not set to True, the service raises an exception. - "force": force - }) - - operation.result(timeout=500) - - print('Deleted products in product set.') -# [END vision_product_search_purge_products_in_product_set] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - subparsers = parser.add_subparsers(dest='command') - parser.add_argument( - '--project_id', - help='Project id. Required', - required=True) - parser.add_argument( - '--location', - help='Compute region name', - default='us-west1') - - add_product_to_product_set_parser = subparsers.add_parser( - 'add_product_to_product_set', help=add_product_to_product_set.__doc__) - add_product_to_product_set_parser.add_argument('product_id') - add_product_to_product_set_parser.add_argument('product_set_id') - - list_products_in_product_set_parser = subparsers.add_parser( - 'list_products_in_product_set', - help=list_products_in_product_set.__doc__) - list_products_in_product_set_parser.add_argument('product_set_id') - - remove_product_from_product_set_parser = subparsers.add_parser( - 'remove_product_from_product_set', - help=remove_product_from_product_set.__doc__) - remove_product_from_product_set_parser.add_argument('product_id') - remove_product_from_product_set_parser.add_argument('product_set_id') - - purge_products_in_product_set_parser = subparsers.add_parser( - 'purge_products_in_product_set', - help=purge_products_in_product_set.__doc__) - purge_products_in_product_set_parser.add_argument('product_set_id') - purge_products_in_product_set_parser.add_argument( - '--force', action='store_true') - - args = parser.parse_args() - - if args.command == 'add_product_to_product_set': - add_product_to_product_set( - args.project_id, args.location, args.product_id, - args.product_set_id) - elif args.command == 'list_products_in_product_set': - list_products_in_product_set( - args.project_id, args.location, args.product_set_id) - elif args.command == 'remove_product_from_product_set': - remove_product_from_product_set( - args.project_id, args.location, args.product_id, - args.product_set_id) - elif args.command == 'purge_products_in_product_set': - purge_products_in_product_set( - args.project_id, args.location, args.product_set_id, args.force) diff --git a/samples/snippets/product_search/product_in_product_set_management_test.py b/samples/snippets/product_search/product_in_product_set_management_test.py deleted file mode 100644 index 779b84d8..00000000 --- a/samples/snippets/product_search/product_in_product_set_management_test.py +++ /dev/null @@ -1,92 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import pytest - -from product_in_product_set_management import ( - add_product_to_product_set, list_products_in_product_set, - purge_products_in_product_set, remove_product_from_product_set) -from product_management import create_product, delete_product, list_products -from product_set_management import ( - create_product_set, delete_product_set) - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -PRODUCT_SET_DISPLAY_NAME = 'fake_product_set_display_name_for_testing' - -PRODUCT_DISPLAY_NAME = 'fake_product_display_name_for_testing' -PRODUCT_CATEGORY = 'homegoods' - - -@pytest.fixture(scope="function") -def test_resources(): - # set up - product_set_id = f'test_set_{uuid.uuid4()}' - product_id = f'test_product_{uuid.uuid4()}' - create_product_set( - PROJECT_ID, LOCATION, product_set_id, PRODUCT_SET_DISPLAY_NAME) - create_product( - PROJECT_ID, LOCATION, product_id, - PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY) - - yield product_set_id, product_id - - # tear down - delete_product(PROJECT_ID, LOCATION, product_id) - delete_product_set(PROJECT_ID, LOCATION, product_set_id) - - -def test_add_product_to_product_set(capsys, test_resources): - product_set_id, product_id = test_resources - add_product_to_product_set( - PROJECT_ID, LOCATION, product_id, product_set_id) - list_products_in_product_set(PROJECT_ID, LOCATION, product_set_id) - out, _ = capsys.readouterr() - assert 'Product id: {}'.format(product_id) in out - - -def test_remove_product_from_product_set(capsys, test_resources): - product_set_id, product_id = test_resources - add_product_to_product_set( - PROJECT_ID, LOCATION, product_id, product_set_id) - list_products_in_product_set(PROJECT_ID, LOCATION, product_set_id) - out, _ = capsys.readouterr() - assert 'Product id: {}'.format(product_id) in out - - remove_product_from_product_set( - PROJECT_ID, LOCATION, product_id, product_set_id) - list_products_in_product_set(PROJECT_ID, LOCATION, product_set_id) - out, _ = capsys.readouterr() - assert 'Product id: {}'.format(product_id) not in out - - -def test_purge_products_in_product_set(capsys, test_resources): - product_set_id, product_id = test_resources - add_product_to_product_set( - PROJECT_ID, LOCATION, product_id, product_set_id) - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert 'Product id: {}'.format(product_id) in out - - purge_products_in_product_set( - PROJECT_ID, LOCATION, product_set_id, force=True) - - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert 'Product id: {}'.format(product_id) not in out diff --git a/samples/snippets/product_search/product_management.py b/samples/snippets/product_search/product_management.py deleted file mode 100755 index 75697ddf..00000000 --- a/samples/snippets/product_search/product_management.py +++ /dev/null @@ -1,274 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This application demonstrates how to perform basic operations on Product -in Cloud Vision Product Search. - -For more information, see the tutorial page at -https://cloud.google.com/vision/product-search/docs/ -""" - -import argparse - -# [START vision_product_search_create_product] -# [START vision_product_search_delete_product] -# [START vision_product_search_list_products] -# [START vision_product_search_get_product] -# [START vision_product_search_update_product_labels] -# [START vision_product_search_purge_orphan_products] -from google.cloud import vision -from google.protobuf import field_mask_pb2 as field_mask - -# [END vision_product_search_create_product] -# [END vision_product_search_delete_product] -# [END vision_product_search_list_products] -# [END vision_product_search_get_product] -# [END vision_product_search_update_product_labels] -# [END vision_product_search_purge_orphan_products] - - -# [START vision_product_search_create_product] -def create_product( - project_id, location, product_id, product_display_name, - product_category): - """Create one product. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - product_display_name: Display name of the product. - product_category: Category of the product. - """ - client = vision.ProductSearchClient() - - # A resource that represents Google Cloud Platform location. - location_path = f"projects/{project_id}/locations/{location}" - - # Create a product with the product specification in the region. - # Set product display name and product category. - product = vision.Product( - display_name=product_display_name, - product_category=product_category) - - # The response is the product with the `name` field populated. - response = client.create_product( - parent=location_path, - product=product, - product_id=product_id) - - # Display the product information. - print('Product name: {}'.format(response.name)) -# [END vision_product_search_create_product] - - -# [START vision_product_search_list_products] -def list_products(project_id, location): - """List all products. - Args: - project_id: Id of the project. - location: A compute region name. - """ - client = vision.ProductSearchClient() - - # A resource that represents Google Cloud Platform location. - location_path = f"projects/{project_id}/locations/{location}" - - # List all the products available in the region. - products = client.list_products(parent=location_path) - - # Display the product information. - for product in products: - print('Product name: {}'.format(product.name)) - print('Product id: {}'.format(product.name.split('/')[-1])) - print('Product display name: {}'.format(product.display_name)) - print('Product description: {}'.format(product.description)) - print('Product category: {}'.format(product.product_category)) - print('Product labels: {}\n'.format(product.product_labels)) -# [END vision_product_search_list_products] - - -# [START vision_product_search_get_product] -def get_product(project_id, location, product_id): - """Get information about a product. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product. - product_path = client.product_path( - project=project_id, location=location, product=product_id) - - # Get complete detail of the product. - product = client.get_product(name=product_path) - - # Display the product information. - print('Product name: {}'.format(product.name)) - print('Product id: {}'.format(product.name.split('/')[-1])) - print('Product display name: {}'.format(product.display_name)) - print('Product description: {}'.format(product.description)) - print('Product category: {}'.format(product.product_category)) - print('Product labels: {}'.format(product.product_labels)) -# [END vision_product_search_get_product] - - -# [START vision_product_search_update_product_labels] -def update_product_labels( - project_id, location, product_id, key, value): - """Update the product labels. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - key: The key of the label. - value: The value of the label. - """ - client = vision.ProductSearchClient() - - # Get the name of the product. - product_path = client.product_path( - project=project_id, location=location, product=product_id) - - # Set product name, product label and product display name. - # Multiple labels are also supported. - key_value = vision.Product.KeyValue(key=key, value=value) - product = vision.Product( - name=product_path, - product_labels=[key_value]) - - # Updating only the product_labels field here. - update_mask = field_mask.FieldMask(paths=['product_labels']) - - # This overwrites the product_labels. - updated_product = client.update_product( - product=product, update_mask=update_mask) - - # Display the updated product information. - print('Product name: {}'.format(updated_product.name)) - print('Updated product labels: {}'.format(product.product_labels)) -# [END vision_product_search_update_product_labels] - - -# [START vision_product_search_delete_product] -def delete_product(project_id, location, product_id): - """Delete the product and all its reference images. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product. - product_path = client.product_path( - project=project_id, location=location, product=product_id) - - # Delete a product. - client.delete_product(name=product_path) - print('Product deleted.') -# [END vision_product_search_delete_product] - - -# [START vision_product_search_purge_orphan_products] -def purge_orphan_products(project_id, location, force): - """Delete all products not in any product sets. - Args: - project_id: Id of the project. - location: A compute region name. - """ - client = vision.ProductSearchClient() - - parent = f"projects/{project_id}/locations/{location}" - - # The purge operation is async. - operation = client.purge_products(request={ - "parent": parent, - "delete_orphan_products": True, - # The operation is irreversible and removes multiple products. - # The user is required to pass in force=True to actually perform the - # purge. - # If force is not set to True, the service raises an exception. - "force": force - }) - - operation.result(timeout=500) - - print('Orphan products deleted.') -# [END vision_product_search_purge_orphan_products] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument( - '--project_id', - help='Project id. Required', - required=True) - parser.add_argument( - '--location', - help='Compute region name', - default='us-west1') - - subparsers = parser.add_subparsers(dest='command') - - create_product_parser = subparsers.add_parser( - 'create_product', help=create_product.__doc__) - create_product_parser.add_argument('product_id') - create_product_parser.add_argument('product_display_name') - create_product_parser.add_argument('product_category') - - list_products_parser = subparsers.add_parser( - 'list_products', help=list_products.__doc__) - - get_product_parser = subparsers.add_parser( - 'get_product', help=get_product.__doc__) - get_product_parser.add_argument('product_id') - - update_product_labels_parser = subparsers.add_parser( - 'update_product_labels', help=update_product_labels.__doc__) - update_product_labels_parser.add_argument('product_id') - update_product_labels_parser.add_argument('key') - update_product_labels_parser.add_argument('value') - - delete_product_parser = subparsers.add_parser( - 'delete_product', help=delete_product.__doc__) - delete_product_parser.add_argument('product_id') - - purge_orphan_products_parser = subparsers.add_parser( - 'purge_orphan_products', help=purge_orphan_products.__doc__) - purge_orphan_products_parser.add_argument('--force', action='store_true') - - args = parser.parse_args() - - if args.command == 'create_product': - create_product( - args.project_id, args.location, args.product_id, - args.product_display_name, args.product_category) - elif args.command == 'list_products': - list_products(args.project_id, args.location) - elif args.command == 'get_product': - get_product(args.project_id, args.location, args.product_id) - elif args.command == 'update_product_labels': - update_product_labels( - args.project_id, args.location, args.product_id, - args.key, args.value) - elif args.command == 'delete_product': - delete_product(args.project_id, args.location, args.product_id) - elif args.command == 'purge_orphan_products': - purge_orphan_products(args.project_id, args.location, args.force) diff --git a/samples/snippets/product_search/product_management_test.py b/samples/snippets/product_search/product_management_test.py deleted file mode 100644 index a0f4dcc6..00000000 --- a/samples/snippets/product_search/product_management_test.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import pytest - -from product_management import ( - create_product, delete_product, list_products, - purge_orphan_products, update_product_labels) - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -PRODUCT_DISPLAY_NAME = 'fake_product_display_name_for_testing' -PRODUCT_CATEGORY = 'homegoods' -PRODUCT_ID = 'test_{}'.format(uuid.uuid4()) -KEY = 'fake_key_for_testing' -VALUE = 'fake_value_for_testing' - - -@pytest.fixture(scope="function", autouse=True) -def setup_teardown(): - # set up - create_product( - PROJECT_ID, LOCATION, PRODUCT_ID, - PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY) - - yield None - - # tear down - delete_product(PROJECT_ID, LOCATION, PRODUCT_ID) - - -def test_delete_product(capsys): - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_ID in out - - delete_product(PROJECT_ID, LOCATION, PRODUCT_ID) - - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_ID not in out - - -def test_update_product_labels(capsys): - update_product_labels(PROJECT_ID, LOCATION, PRODUCT_ID, KEY, VALUE) - out, _ = capsys.readouterr() - assert KEY in out - assert VALUE in out - - -def test_purge_orphan_products(capsys): - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_ID in out - - purge_orphan_products(PROJECT_ID, LOCATION, force=True) - - list_products(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_ID not in out diff --git a/samples/snippets/product_search/product_search.py b/samples/snippets/product_search/product_search.py deleted file mode 100755 index 095f28e1..00000000 --- a/samples/snippets/product_search/product_search.py +++ /dev/null @@ -1,205 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This tutorial demonstrates how users query the product set with their -own images and find the products similer to the image using the Cloud -Vision Product Search API. - -For more information, see the tutorial page at -https://cloud.google.com/vision/product-search/docs/ -""" - -import argparse - -# [START vision_product_search_get_similar_products] -# [START vision_product_search_get_similar_products_gcs] -from google.cloud import vision - -# [END vision_product_search_get_similar_products] -# [END vision_product_search_get_similar_products_gcs] - - -# [START vision_product_search_get_similar_products] -def get_similar_products_file( - project_id, - location, - product_set_id, - product_category, - file_path, - filter, - max_results -): - """Search similar products to image. - Args: - project_id: Id of the project. - location: A compute region name. - product_set_id: Id of the product set. - product_category: Category of the product. - file_path: Local file path of the image to be searched. - filter: Condition to be applied on the labels. - Example for filter: (color = red OR color = blue) AND style = kids - It will search on all products with the following labels: - color:red AND style:kids - color:blue AND style:kids - max_results: The maximum number of results (matches) to return. If omitted, all results are returned. - """ - # product_search_client is needed only for its helper methods. - product_search_client = vision.ProductSearchClient() - image_annotator_client = vision.ImageAnnotatorClient() - - # Read the image as a stream of bytes. - with open(file_path, 'rb') as image_file: - content = image_file.read() - - # Create annotate image request along with product search feature. - image = vision.Image(content=content) - - # product search specific parameters - product_set_path = product_search_client.product_set_path( - project=project_id, location=location, - product_set=product_set_id) - product_search_params = vision.ProductSearchParams( - product_set=product_set_path, - product_categories=[product_category], - filter=filter) - image_context = vision.ImageContext( - product_search_params=product_search_params) - - # Search products similar to the image. - response = image_annotator_client.product_search( - image, - image_context=image_context, - max_results=max_results - ) - - index_time = response.product_search_results.index_time - print('Product set index time: ') - print(index_time) - - results = response.product_search_results.results - - print('Search results:') - for result in results: - product = result.product - - print('Score(Confidence): {}'.format(result.score)) - print('Image name: {}'.format(result.image)) - - print('Product name: {}'.format(product.name)) - print('Product display name: {}'.format( - product.display_name)) - print('Product description: {}\n'.format(product.description)) - print('Product labels: {}\n'.format(product.product_labels)) -# [END vision_product_search_get_similar_products] - - -# [START vision_product_search_get_similar_products_gcs] -def get_similar_products_uri( - project_id, location, product_set_id, product_category, - image_uri, filter): - """Search similar products to image. - Args: - project_id: Id of the project. - location: A compute region name. - product_set_id: Id of the product set. - product_category: Category of the product. - image_uri: Cloud Storage location of image to be searched. - filter: Condition to be applied on the labels. - Example for filter: (color = red OR color = blue) AND style = kids - It will search on all products with the following labels: - color:red AND style:kids - color:blue AND style:kids - """ - # product_search_client is needed only for its helper methods. - product_search_client = vision.ProductSearchClient() - image_annotator_client = vision.ImageAnnotatorClient() - - # Create annotate image request along with product search feature. - image_source = vision.ImageSource(image_uri=image_uri) - image = vision.Image(source=image_source) - - # product search specific parameters - product_set_path = product_search_client.product_set_path( - project=project_id, location=location, - product_set=product_set_id) - product_search_params = vision.ProductSearchParams( - product_set=product_set_path, - product_categories=[product_category], - filter=filter) - image_context = vision.ImageContext( - product_search_params=product_search_params) - - # Search products similar to the image. - response = image_annotator_client.product_search( - image, image_context=image_context) - - index_time = response.product_search_results.index_time - print('Product set index time: ') - print(index_time) - - results = response.product_search_results.results - - print('Search results:') - for result in results: - product = result.product - - print('Score(Confidence): {}'.format(result.score)) - print('Image name: {}'.format(result.image)) - - print('Product name: {}'.format(product.name)) - print('Product display name: {}'.format( - product.display_name)) - print('Product description: {}\n'.format(product.description)) - print('Product labels: {}\n'.format(product.product_labels)) -# [END vision_product_search_get_similar_products_gcs] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - subparsers = parser.add_subparsers(dest='command') - parser.add_argument( - '--project_id', - help='Project id. Required', - required=True) - parser.add_argument( - '--location', - help='Compute region name', - default='us-west1') - parser.add_argument('--product_set_id') - parser.add_argument('--product_category') - parser.add_argument('--filter', default='') - parser.add_argument('--max_results', default='') - - get_similar_products_file_parser = subparsers.add_parser( - 'get_similar_products_file', help=get_similar_products_file.__doc__) - get_similar_products_file_parser.add_argument('--file_path') - - get_similar_products_uri_parser = subparsers.add_parser( - 'get_similar_products_uri', help=get_similar_products_uri.__doc__) - get_similar_products_uri_parser.add_argument('--image_uri') - - args = parser.parse_args() - - if args.command == 'get_similar_products_file': - get_similar_products_file( - args.project_id, args.location, args.product_set_id, - args.product_category, args.file_path, args.filter, args.max_results) - elif args.command == 'get_similar_products_uri': - get_similar_products_uri( - args.project_id, args.location, args.product_set_id, - args.product_category, args.image_uri, args.filter, args.max_results) diff --git a/samples/snippets/product_search/product_search_test.py b/samples/snippets/product_search/product_search_test.py deleted file mode 100644 index c7d00998..00000000 --- a/samples/snippets/product_search/product_search_test.py +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os - -import pytest - -from product_search import get_similar_products_file, get_similar_products_uri - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -PRODUCT_SET_ID = 'indexed_product_set_id_for_testing' -PRODUCT_CATEGORY = 'apparel' -PRODUCT_ID_1 = 'indexed_product_id_for_testing_1' -PRODUCT_ID_2 = 'indexed_product_id_for_testing_2' - -FILE_PATH_1 = 'resources/shoes_1.jpg' -IMAGE_URI_1 = 'gs://cloud-samples-data/vision/product_search/shoes_1.jpg' -FILTER = 'style=womens' -MAX_RESULTS = 6 - - -@pytest.mark.flaky(max_runs=5, min_passes=1) -def test_get_similar_products_file(capsys): - get_similar_products_file( - PROJECT_ID, LOCATION, PRODUCT_SET_ID, PRODUCT_CATEGORY, FILE_PATH_1, - '', MAX_RESULTS) - out, _ = capsys.readouterr() - assert PRODUCT_ID_1 in out - assert PRODUCT_ID_2 in out - - -def test_get_similar_products_uri(capsys): - get_similar_products_uri( - PROJECT_ID, LOCATION, PRODUCT_SET_ID, PRODUCT_CATEGORY, IMAGE_URI_1, - '') - out, _ = capsys.readouterr() - assert PRODUCT_ID_1 in out - assert PRODUCT_ID_2 in out - - -def test_get_similar_products_file_with_filter(capsys): - get_similar_products_file( - PROJECT_ID, LOCATION, PRODUCT_SET_ID, PRODUCT_CATEGORY, FILE_PATH_1, - FILTER, MAX_RESULTS) - out, _ = capsys.readouterr() - assert PRODUCT_ID_1 in out - assert PRODUCT_ID_2 not in out - - -def test_get_similar_products_uri_with_filter(capsys): - get_similar_products_uri( - PROJECT_ID, LOCATION, PRODUCT_SET_ID, PRODUCT_CATEGORY, IMAGE_URI_1, - FILTER) - out, _ = capsys.readouterr() - assert PRODUCT_ID_1 in out - assert PRODUCT_ID_2 not in out diff --git a/samples/snippets/product_search/product_set_management.py b/samples/snippets/product_search/product_set_management.py deleted file mode 100755 index 995fc472..00000000 --- a/samples/snippets/product_search/product_set_management.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This application demonstrates how to perform operations -on Product set in Cloud Vision Product Search. - -For more information, see the tutorial page at -https://cloud.google.com/vision/product-search/docs/ -""" - -import argparse - -# [START vision_product_search_delete_product_set] -# [START vision_product_search_list_product_sets] -# [START vision_product_search_get_product_set] -# [START vision_product_search_create_product_set] -from google.cloud import vision - -# [END vision_product_search_delete_product_set] -# [END vision_product_search_list_product_sets] -# [END vision_product_search_get_product_set] -# [END vision_product_search_create_product_set] - - -# [START vision_product_search_create_product_set] -def create_product_set( - project_id, location, product_set_id, product_set_display_name): - """Create a product set. - Args: - project_id: Id of the project. - location: A compute region name. - product_set_id: Id of the product set. - product_set_display_name: Display name of the product set. - """ - client = vision.ProductSearchClient() - - # A resource that represents Google Cloud Platform location. - location_path = f"projects/{project_id}/locations/{location}" - - # Create a product set with the product set specification in the region. - product_set = vision.ProductSet( - display_name=product_set_display_name) - - # The response is the product set with `name` populated. - response = client.create_product_set( - parent=location_path, - product_set=product_set, - product_set_id=product_set_id) - - # Display the product set information. - print('Product set name: {}'.format(response.name)) -# [END vision_product_search_create_product_set] - - -# [START vision_product_search_list_product_sets] -def list_product_sets(project_id, location): - """List all product sets. - Args: - project_id: Id of the project. - location: A compute region name. - """ - client = vision.ProductSearchClient() - - # A resource that represents Google Cloud Platform location. - location_path = f"projects/{project_id}/locations/{location}" - - # List all the product sets available in the region. - product_sets = client.list_product_sets(parent=location_path) - - # Display the product set information. - for product_set in product_sets: - print('Product set name: {}'.format(product_set.name)) - print('Product set id: {}'.format(product_set.name.split('/')[-1])) - print('Product set display name: {}'.format(product_set.display_name)) - print('Product set index time: ') - print(product_set.index_time) -# [END vision_product_search_list_product_sets] - - -# [START vision_product_search_get_product_set] -def get_product_set(project_id, location, product_set_id): - """Get info about the product set. - Args: - project_id: Id of the project. - location: A compute region name. - product_set_id: Id of the product set. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product set. - product_set_path = client.product_set_path( - project=project_id, location=location, - product_set=product_set_id) - - # Get complete detail of the product set. - product_set = client.get_product_set(name=product_set_path) - - # Display the product set information. - print('Product set name: {}'.format(product_set.name)) - print('Product set id: {}'.format(product_set.name.split('/')[-1])) - print('Product set display name: {}'.format(product_set.display_name)) - print('Product set index time: ') - print(product_set.index_time) -# [END vision_product_search_get_product_set] - - -# [START vision_product_search_delete_product_set] -def delete_product_set(project_id, location, product_set_id): - """Delete a product set. - Args: - project_id: Id of the project. - location: A compute region name. - product_set_id: Id of the product set. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product set. - product_set_path = client.product_set_path( - project=project_id, location=location, - product_set=product_set_id) - - # Delete the product set. - client.delete_product_set(name=product_set_path) - print('Product set deleted.') -# [END vision_product_search_delete_product_set] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - subparsers = parser.add_subparsers(dest='command') - parser.add_argument( - '--project_id', - help='Project id. Required', - required=True) - parser.add_argument( - '--location', - help='Compute region name', - default='us-west1') - - create_product_set_parser = subparsers.add_parser( - 'create_product_set', help=create_product_set.__doc__) - create_product_set_parser.add_argument('product_set_id') - create_product_set_parser.add_argument('product_set_display_name') - - list_product_sets_parser = subparsers.add_parser( - 'list_product_sets', help=list_product_sets.__doc__) - - get_product_set_parser = subparsers.add_parser( - 'get_product_set', help=get_product_set.__doc__) - get_product_set_parser.add_argument('product_set_id') - - delete_product_set_parser = subparsers.add_parser( - 'delete_product_set', help=delete_product_set.__doc__) - delete_product_set_parser.add_argument('product_set_id') - - args = parser.parse_args() - - if args.command == 'create_product_set': - create_product_set( - args.project_id, args.location, args.product_set_id, - args.product_set_display_name) - elif args.command == 'list_product_sets': - list_product_sets(args.project_id, args.location) - elif args.command == 'get_product_set': - get_product_set(args.project_id, args.location, args.product_set_id) - elif args.command == 'delete_product_set': - delete_product_set( - args.project_id, args.location, args.product_set_id) diff --git a/samples/snippets/product_search/product_set_management_test.py b/samples/snippets/product_search/product_set_management_test.py deleted file mode 100644 index 9d8248de..00000000 --- a/samples/snippets/product_search/product_set_management_test.py +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import pytest - -from product_set_management import ( - create_product_set, delete_product_set, list_product_sets) - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -PRODUCT_SET_DISPLAY_NAME = 'fake_product_set_display_name_for_testing' -PRODUCT_SET_ID = 'test_{}'.format(uuid.uuid4()) - - -@pytest.fixture(scope="function", autouse=True) -def setup(): - # set up - create_product_set( - PROJECT_ID, LOCATION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME) - - -def test_delete_product_set(capsys): - list_product_sets(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_SET_ID in out - - delete_product_set(PROJECT_ID, LOCATION, PRODUCT_SET_ID) - - list_product_sets(PROJECT_ID, LOCATION) - out, _ = capsys.readouterr() - assert PRODUCT_SET_ID not in out diff --git a/samples/snippets/product_search/reference_image_management.py b/samples/snippets/product_search/reference_image_management.py deleted file mode 100755 index 4eebc3bf..00000000 --- a/samples/snippets/product_search/reference_image_management.py +++ /dev/null @@ -1,200 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2018 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""This application demonstrates how to perform basic operations on reference -images in Cloud Vision Product Search. - -For more information, see the tutorial page at -https://cloud.google.com/vision/product-search/docs/ -""" - -import argparse - -# [START vision_product_search_create_reference_image] -# [START vision_product_search_delete_reference_image] -# [START vision_product_search_list_reference_images] -# [START vision_product_search_get_reference_image] -from google.cloud import vision - -# [END vision_product_search_create_reference_image] -# [END vision_product_search_delete_reference_image] -# [END vision_product_search_list_reference_images] -# [END vision_product_search_get_reference_image] - - -# [START vision_product_search_create_reference_image] -def create_reference_image( - project_id, location, product_id, reference_image_id, gcs_uri): - """Create a reference image. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - reference_image_id: Id of the reference image. - gcs_uri: Google Cloud Storage path of the input image. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product. - product_path = client.product_path( - project=project_id, location=location, product=product_id) - - # Create a reference image. - reference_image = vision.ReferenceImage(uri=gcs_uri) - - # The response is the reference image with `name` populated. - image = client.create_reference_image( - parent=product_path, - reference_image=reference_image, - reference_image_id=reference_image_id) - - # Display the reference image information. - print('Reference image name: {}'.format(image.name)) - print('Reference image uri: {}'.format(image.uri)) -# [END vision_product_search_create_reference_image] - - -# [START vision_product_search_list_reference_images] -def list_reference_images( - project_id, location, product_id): - """List all images in a product. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - """ - client = vision.ProductSearchClient() - - # Get the full path of the product. - product_path = client.product_path( - project=project_id, location=location, product=product_id) - - # List all the reference images available in the product. - reference_images = client.list_reference_images(parent=product_path) - - # Display the reference image information. - for image in reference_images: - print('Reference image name: {}'.format(image.name)) - print('Reference image id: {}'.format(image.name.split('/')[-1])) - print('Reference image uri: {}'.format(image.uri)) - print('Reference image bounding polygons: {}'.format( - image.bounding_polys)) -# [END vision_product_search_list_reference_images] - - -# [START vision_product_search_get_reference_image] -def get_reference_image( - project_id, location, product_id, reference_image_id): - """Get info about a reference image. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - reference_image_id: Id of the reference image. - """ - client = vision.ProductSearchClient() - - # Get the full path of the reference image. - reference_image_path = client.reference_image_path( - project=project_id, location=location, product=product_id, - reference_image=reference_image_id) - - # Get complete detail of the reference image. - image = client.get_reference_image(name=reference_image_path) - - # Display the reference image information. - print('Reference image name: {}'.format(image.name)) - print('Reference image id: {}'.format(image.name.split('/')[-1])) - print('Reference image uri: {}'.format(image.uri)) - print('Reference image bounding polygons: {}'.format(image.bounding_polys)) -# [END vision_product_search_get_reference_image] - - -# [START vision_product_search_delete_reference_image] -def delete_reference_image( - project_id, location, product_id, reference_image_id): - """Delete a reference image. - Args: - project_id: Id of the project. - location: A compute region name. - product_id: Id of the product. - reference_image_id: Id of the reference image. - """ - client = vision.ProductSearchClient() - - # Get the full path of the reference image. - reference_image_path = client.reference_image_path( - project=project_id, location=location, product=product_id, - reference_image=reference_image_id) - - # Delete the reference image. - client.delete_reference_image(name=reference_image_path) - print('Reference image deleted from product.') -# [END vision_product_search_delete_reference_image] - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - subparsers = parser.add_subparsers(dest='command') - parser.add_argument( - '--project_id', - help='Project id. Required', - required=True) - parser.add_argument( - '--location', - help='Compute region name', - default='us-west1') - - create_reference_image_parser = subparsers.add_parser( - 'create_reference_image', help=create_reference_image.__doc__) - create_reference_image_parser.add_argument('product_id') - create_reference_image_parser.add_argument('reference_image_id') - create_reference_image_parser.add_argument('gcs_uri') - - list_reference_images_parser = subparsers.add_parser( - 'list_reference_images', - help=list_reference_images.__doc__) - list_reference_images_parser.add_argument('product_id') - - get_reference_image_parser = subparsers.add_parser( - 'get_reference_image', help=get_reference_image.__doc__) - get_reference_image_parser.add_argument('product_id') - get_reference_image_parser.add_argument('reference_image_id') - - delete_reference_image_parser = subparsers.add_parser( - 'delete_reference_image', help=delete_reference_image.__doc__) - delete_reference_image_parser.add_argument('product_id') - delete_reference_image_parser.add_argument('reference_image_id') - - args = parser.parse_args() - - if args.command == 'create_reference_image': - create_reference_image( - args.project_id, args.location, args.product_id, - args.reference_image_id, args.gcs_uri) - elif args.command == 'list_reference_images': - list_reference_images( - args.project_id, args.location, args.product_id) - elif args.command == 'get_reference_image': - get_reference_image( - args.project_id, args.location, args.product_id, - args.reference_image_id) - elif args.command == 'delete_reference_image': - delete_reference_image( - args.project_id, args.location, args.product_id, - args.reference_image_id) diff --git a/samples/snippets/product_search/reference_image_management_test.py b/samples/snippets/product_search/reference_image_management_test.py deleted file mode 100644 index 5e6f8ac4..00000000 --- a/samples/snippets/product_search/reference_image_management_test.py +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import os -import uuid - -import pytest - -from product_management import create_product, delete_product -from reference_image_management import ( - create_reference_image, delete_reference_image, list_reference_images) - - -PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') -LOCATION = 'us-west1' - -PRODUCT_DISPLAY_NAME = 'fake_product_display_name_for_testing' -PRODUCT_CATEGORY = 'homegoods' -PRODUCT_ID = 'test_{}'.format(uuid.uuid4()) - -REFERENCE_IMAGE_ID = 'fake_reference_image_id_for_testing' -GCS_URI = 'gs://cloud-samples-data/vision/product_search/shoes_1.jpg' - - -@pytest.fixture(scope="function", autouse=True) -def setup_teardown(): - # set up - create_product( - PROJECT_ID, LOCATION, PRODUCT_ID, - PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY) - - yield None - - # tear down - delete_product(PROJECT_ID, LOCATION, PRODUCT_ID) - - -def test_create_reference_image(capsys): - create_reference_image( - PROJECT_ID, LOCATION, PRODUCT_ID, REFERENCE_IMAGE_ID, - GCS_URI) - list_reference_images(PROJECT_ID, LOCATION, PRODUCT_ID) - out, _ = capsys.readouterr() - assert REFERENCE_IMAGE_ID in out - - -def test_delete_reference_image(capsys): - create_reference_image( - PROJECT_ID, LOCATION, PRODUCT_ID, REFERENCE_IMAGE_ID, - GCS_URI) - list_reference_images(PROJECT_ID, LOCATION, PRODUCT_ID) - out, _ = capsys.readouterr() - assert REFERENCE_IMAGE_ID in out - - delete_reference_image( - PROJECT_ID, LOCATION, PRODUCT_ID, REFERENCE_IMAGE_ID) - list_reference_images(PROJECT_ID, LOCATION, PRODUCT_ID) - out, _ = capsys.readouterr() - assert REFERENCE_IMAGE_ID not in out diff --git a/samples/snippets/product_search/requirements-test.txt b/samples/snippets/product_search/requirements-test.txt deleted file mode 100644 index f9e03740..00000000 --- a/samples/snippets/product_search/requirements-test.txt +++ /dev/null @@ -1,2 +0,0 @@ -pytest==7.1.3 -flaky==3.7.0 \ No newline at end of file diff --git a/samples/snippets/product_search/requirements.txt b/samples/snippets/product_search/requirements.txt deleted file mode 100644 index ab0921e1..00000000 --- a/samples/snippets/product_search/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -google-cloud-vision==3.1.3 -google-cloud-storage==2.5.0 diff --git a/samples/snippets/product_search/resources/indexed_product_sets.csv b/samples/snippets/product_search/resources/indexed_product_sets.csv deleted file mode 100644 index 329ac216..00000000 --- a/samples/snippets/product_search/resources/indexed_product_sets.csv +++ /dev/null @@ -1,2 +0,0 @@ -"gs://cloud-samples-data/vision/product_search/shoes_1.jpg","indexed_product_set_id_for_testing","indexed_product_id_for_testing_1","apparel","style=womens","0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9" -"gs://cloud-samples-data/vision/product_search/shoes_2.jpg","indexed_product_set_id_for_testing","indexed_product_id_for_testing_2","apparel",, \ No newline at end of file diff --git a/samples/snippets/product_search/resources/product_sets.csv b/samples/snippets/product_search/resources/product_sets.csv deleted file mode 100644 index 68657eed..00000000 --- a/samples/snippets/product_search/resources/product_sets.csv +++ /dev/null @@ -1,2 +0,0 @@ -"gs://cloud-samples-data/vision/product_search/shoes_1.jpg","fake_product_set_id_for_testing","fake_product_id_for_testing_1","apparel","style=womens","0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9" -"gs://cloud-samples-data/vision/product_search/shoes_2.jpg","fake_product_set_id_for_testing","fake_product_id_for_testing_2","apparel",, \ No newline at end of file diff --git a/samples/snippets/product_search/resources/shoes_1.jpg b/samples/snippets/product_search/resources/shoes_1.jpg deleted file mode 100644 index 78318eef..00000000 Binary files a/samples/snippets/product_search/resources/shoes_1.jpg and /dev/null differ diff --git a/samples/snippets/product_search/resources/shoes_2.jpg b/samples/snippets/product_search/resources/shoes_2.jpg deleted file mode 100644 index cdfa80dd..00000000 Binary files a/samples/snippets/product_search/resources/shoes_2.jpg and /dev/null differ diff --git a/samples/snippets/quickstart/README.rst b/samples/snippets/quickstart/README.rst deleted file mode 100644 index aa4be034..00000000 --- a/samples/snippets/quickstart/README.rst +++ /dev/null @@ -1,101 +0,0 @@ -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Vision API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/quickstart/README.rst - - -This directory contains samples for Google Cloud Vision API. `Google Cloud Vision API`_ allows developers to easily integrate vision detection features within applications, including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. - -- See the `migration guide`_ for information about migrating to Python client library v0.25.1. - -.. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - - - - -.. _Google Cloud Vision API: https://cloud.google.com/vision/docs - -Setup -------------------------------------------------------------------------------- - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 2.7 and 3.4+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - -Samples -------------------------------------------------------------------------------- - -Quickstart -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/quickstart/quickstart.py,vision/cloud-client/quickstart/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python quickstart.py - - - - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ \ No newline at end of file diff --git a/samples/snippets/quickstart/README.rst.in b/samples/snippets/quickstart/README.rst.in deleted file mode 100644 index bd650a6c..00000000 --- a/samples/snippets/quickstart/README.rst.in +++ /dev/null @@ -1,29 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Vision API - short_name: Cloud Vision API - url: https://cloud.google.com/vision/docs - description: > - `Google Cloud Vision API`_ allows developers to easily integrate vision - detection features within applications, including image labeling, face and - landmark detection, optical character recognition (OCR), and tagging of - explicit content. - - - - See the `migration guide`_ for information about migrating to Python client library v0.25.1. - - - .. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - -setup: -- auth -- install_deps - -samples: -- name: Quickstart - file: quickstart.py - -cloud_client_library: true - -folder: vision/cloud-client/quickstart \ No newline at end of file diff --git a/samples/snippets/quickstart/noxfile.py b/samples/snippets/quickstart/noxfile.py deleted file mode 100644 index 0398d72f..00000000 --- a/samples/snippets/quickstart/noxfile.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, List, Optional - -import nox - - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--import-order-style=google", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") - else: - session.install("flake8", "flake8-import-order", "flake8-annotations") - - local_names = _determine_local_import_names(".") - args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob("**/test_*.py", recursive=True) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install( - "-r", "requirements-test.txt", "-c", "constraints-test.txt" - ) - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(['--workers', 'auto', '--tests-per-worker', 'auto']) - elif "pytest-xdist" in packages: - concurrent_args.extend(['-n', 'auto']) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/quickstart/quickstart.py b/samples/snippets/quickstart/quickstart.py deleted file mode 100644 index 521a1c18..00000000 --- a/samples/snippets/quickstart/quickstart.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2016 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -def run_quickstart(): - # [START vision_quickstart] - import io - import os - - # Imports the Google Cloud client library - # [START vision_python_migration_import] - from google.cloud import vision - # [END vision_python_migration_import] - - # Instantiates a client - # [START vision_python_migration_client] - client = vision.ImageAnnotatorClient() - # [END vision_python_migration_client] - - # The name of the image file to annotate - file_name = os.path.abspath('resources/wakeupcat.jpg') - - # Loads the image into memory - with io.open(file_name, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - # Performs label detection on the image file - response = client.label_detection(image=image) - labels = response.label_annotations - - print('Labels:') - for label in labels: - print(label.description) - # [END vision_quickstart] - - -if __name__ == '__main__': - run_quickstart() diff --git a/samples/snippets/quickstart/requirements-test.txt b/samples/snippets/quickstart/requirements-test.txt deleted file mode 100644 index e0716850..00000000 --- a/samples/snippets/quickstart/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.1.3 diff --git a/samples/snippets/quickstart/requirements.txt b/samples/snippets/quickstart/requirements.txt deleted file mode 100644 index 391b7617..00000000 --- a/samples/snippets/quickstart/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -google-cloud-vision==3.1.3 diff --git a/samples/snippets/quickstart/resources/wakeupcat.jpg b/samples/snippets/quickstart/resources/wakeupcat.jpg deleted file mode 100644 index 139cf461..00000000 Binary files a/samples/snippets/quickstart/resources/wakeupcat.jpg and /dev/null differ diff --git a/samples/snippets/web/README.rst b/samples/snippets/web/README.rst deleted file mode 100644 index fe3e900b..00000000 --- a/samples/snippets/web/README.rst +++ /dev/null @@ -1,136 +0,0 @@ - -.. This file is automatically generated. Do not edit this file directly. - -Google Cloud Vision API Python Samples -=============================================================================== - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/web/README.rst - - -This directory contains samples for Google Cloud Vision API. `Google Cloud Vision API`_ allows developers to easily integrate vision detection features within applications, including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. - -- See the `migration guide`_ for information about migrating to Python client library v0.25.1. - -.. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - - - - -.. _Google Cloud Vision API: https://cloud.google.com/vision/docs - - -Setup -------------------------------------------------------------------------------- - - - -Authentication -++++++++++++++ - -This sample requires you to have authentication setup. Refer to the -`Authentication Getting Started Guide`_ for instructions on setting up -credentials for applications. - -.. _Authentication Getting Started Guide: - https://cloud.google.com/docs/authentication/getting-started - - - - -Install Dependencies -++++++++++++++++++++ - -#. Clone python-docs-samples and change directory to the sample directory you want to use. - - .. code-block:: bash - - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git - -#. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. - - .. _Python Development Environment Setup Guide: - https://cloud.google.com/python/setup - -#. Create a virtualenv. Samples are compatible with Python 3.6+. - - .. code-block:: bash - - $ virtualenv env - $ source env/bin/activate - -#. Install the dependencies needed to run the samples. - - .. code-block:: bash - - $ pip install -r requirements.txt - -.. _pip: https://pip.pypa.io/ -.. _virtualenv: https://virtualenv.pypa.io/ - - - - - - -Samples -------------------------------------------------------------------------------- - - -Web -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -.. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=vision/cloud-client/web/web_detect.py,vision/cloud-client/web/README.rst - - - - -To run this sample: - -.. code-block:: bash - - $ python web_detect.py - - - usage: web_detect.py [-h] image_url - - Demonstrates web detection using the Google Cloud Vision API. - - Example usage: - python web_detect.py https://goo.gl/X4qcB6 - python web_detect.py ../detect/resources/landmark.jpg - python web_detect.py gs://your-bucket/image.png - - positional arguments: - image_url The image to detect, can be web URI, Google Cloud Storage, or - path to local file. - - optional arguments: - -h, --help show this help message and exit - - - - - - - - - -The client library -------------------------------------------------------------------------------- - -This sample uses the `Google Cloud Client Library for Python`_. -You can read the documentation for more details on API usage and use GitHub -to `browse the source`_ and `report issues`_. - -.. _Google Cloud Client Library for Python: - https://googlecloudplatform.github.io/google-cloud-python/ -.. _browse the source: - https://github.com/GoogleCloudPlatform/google-cloud-python -.. _report issues: - https://github.com/GoogleCloudPlatform/google-cloud-python/issues - - - -.. _Google Cloud SDK: https://cloud.google.com/sdk/ diff --git a/samples/snippets/web/README.rst.in b/samples/snippets/web/README.rst.in deleted file mode 100644 index 8b8533b5..00000000 --- a/samples/snippets/web/README.rst.in +++ /dev/null @@ -1,30 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Vision API - short_name: Cloud Vision API - url: https://cloud.google.com/vision/docs - description: > - `Google Cloud Vision API`_ allows developers to easily integrate vision - detection features within applications, including image labeling, face and - landmark detection, optical character recognition (OCR), and tagging of - explicit content. - - - - See the `migration guide`_ for information about migrating to Python client library v0.25.1. - - - .. _migration guide: https://cloud.google.com/vision/docs/python-client-migration - -setup: -- auth -- install_deps - -samples: -- name: Web - file: web_detect.py - show_help: True - -cloud_client_library: true - -folder: vision/cloud-client/web \ No newline at end of file diff --git a/samples/snippets/web/noxfile.py b/samples/snippets/web/noxfile.py deleted file mode 100644 index 0398d72f..00000000 --- a/samples/snippets/web/noxfile.py +++ /dev/null @@ -1,312 +0,0 @@ -# Copyright 2019 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, List, Optional - -import nox - - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # An envvar key for determining the project id to use. Change it - # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a - # build specific Cloud project. You can also use your own string - # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", - # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -def _determine_local_import_names(start_dir: str) -> List[str]: - """Determines all import names that should be considered "local". - - This is used when running the linter to insure that import order is - properly checked. - """ - file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] - return [ - basename - for basename, extension in file_ext_pairs - if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") - ] - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--import-order-style=google", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8", "flake8-import-order") - else: - session.install("flake8", "flake8-import-order", "flake8-annotations") - - local_names = _determine_local_import_names(".") - args = FLAKE8_COMMON_ARGS + [ - "--application-import-names", - ",".join(local_names), - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob("**/test_*.py", recursive=True) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install( - "-r", "requirements-test.txt", "-c", "constraints-test.txt" - ) - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(['--workers', 'auto', '--tests-per-worker', 'auto']) - elif "pytest-xdist" in packages: - concurrent_args.extend(['-n', 'auto']) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """ Returns the root folder of the project. """ - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/web/requirements-test.txt b/samples/snippets/web/requirements-test.txt deleted file mode 100644 index 42e12d41..00000000 --- a/samples/snippets/web/requirements-test.txt +++ /dev/null @@ -1,2 +0,0 @@ -flaky==3.7.0 -pytest==7.1.3 diff --git a/samples/snippets/web/requirements.txt b/samples/snippets/web/requirements.txt deleted file mode 100644 index 391b7617..00000000 --- a/samples/snippets/web/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -google-cloud-vision==3.1.3 diff --git a/samples/snippets/web/web_detect.py b/samples/snippets/web/web_detect.py deleted file mode 100644 index 52b921e9..00000000 --- a/samples/snippets/web/web_detect.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python - -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Demonstrates web detection using the Google Cloud Vision API. - -Example usage: - python web_detect.py https://goo.gl/X4qcB6 - python web_detect.py ../detect/resources/landmark.jpg - python web_detect.py gs://your-bucket/image.png -""" -# [START vision_web_detection_tutorial] -# [START vision_web_detection_tutorial_imports] -import argparse -import io - -from google.cloud import vision -# [END vision_web_detection_tutorial_imports] - - -def annotate(path): - """Returns web annotations given the path to an image.""" - # [START vision_web_detection_tutorial_annotate] - client = vision.ImageAnnotatorClient() - - if path.startswith('http') or path.startswith('gs:'): - image = vision.Image() - image.source.image_uri = path - - else: - with io.open(path, 'rb') as image_file: - content = image_file.read() - - image = vision.Image(content=content) - - web_detection = client.web_detection(image=image).web_detection - # [END vision_web_detection_tutorial_annotate] - - return web_detection - - -def report(annotations): - """Prints detected features in the provided web annotations.""" - # [START vision_web_detection_tutorial_print_annotations] - if annotations.pages_with_matching_images: - print('\n{} Pages with matching images retrieved'.format( - len(annotations.pages_with_matching_images))) - - for page in annotations.pages_with_matching_images: - print('Url : {}'.format(page.url)) - - if annotations.full_matching_images: - print('\n{} Full Matches found: '.format( - len(annotations.full_matching_images))) - - for image in annotations.full_matching_images: - print('Url : {}'.format(image.url)) - - if annotations.partial_matching_images: - print('\n{} Partial Matches found: '.format( - len(annotations.partial_matching_images))) - - for image in annotations.partial_matching_images: - print('Url : {}'.format(image.url)) - - if annotations.web_entities: - print('\n{} Web entities found: '.format( - len(annotations.web_entities))) - - for entity in annotations.web_entities: - print('Score : {}'.format(entity.score)) - print('Description: {}'.format(entity.description)) - # [END vision_web_detection_tutorial_print_annotations] - - -if __name__ == '__main__': - # [START vision_web_detection_tutorial_run_application] - parser = argparse.ArgumentParser( - description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - path_help = str('The image to detect, can be web URI, ' - 'Google Cloud Storage, or path to local file.') - parser.add_argument('image_url', help=path_help) - args = parser.parse_args() - - report(annotate(args.image_url)) - # [END vision_web_detection_tutorial_run_application] -# [END vision_web_detection_tutorial] diff --git a/samples/snippets/web/web_detect_test.py b/samples/snippets/web/web_detect_test.py deleted file mode 100644 index 83f8c84f..00000000 --- a/samples/snippets/web/web_detect_test.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2017 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import pytest - -import web_detect - -ASSET_BUCKET = "cloud-samples-data" - - -def test_detect_file(capsys): - file_name = ('../detect/resources/landmark.jpg') - web_detect.report(web_detect.annotate(file_name)) - out, _ = capsys.readouterr() - assert 'description' in out.lower() - - -@pytest.mark.flaky(max_runs=3, min_passes=1) -def test_detect_web_gsuri(capsys): - file_name = ('gs://{}/vision/landmark/pofa.jpg'.format( - ASSET_BUCKET)) - web_detect.report(web_detect.annotate(file_name)) - out, _ = capsys.readouterr() - assert 'description:' in out.lower() diff --git a/scripts/fixup_vision_v1_keywords.py b/scripts/fixup_vision_v1_keywords.py index 6071ce4b..251291f6 100644 --- a/scripts/fixup_vision_v1_keywords.py +++ b/scripts/fixup_vision_v1_keywords.py @@ -1,6 +1,6 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -40,30 +39,29 @@ def partition( class visionCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_product_to_product_set': ('name', 'product', ), - 'async_batch_annotate_files': ('requests', 'parent', ), - 'async_batch_annotate_images': ('requests', 'output_config', 'parent', ), - 'batch_annotate_files': ('requests', 'parent', ), - 'batch_annotate_images': ('requests', 'parent', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_product_set': ('parent', 'product_set', 'product_set_id', ), - 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), - 'delete_product': ('name', ), - 'delete_product_set': ('name', ), - 'delete_reference_image': ('name', ), - 'get_product': ('name', ), - 'get_product_set': ('name', ), - 'get_reference_image': ('name', ), - 'import_product_sets': ('parent', 'input_config', ), - 'list_products': ('parent', 'page_size', 'page_token', ), - 'list_product_sets': ('parent', 'page_size', 'page_token', ), - 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), - 'list_reference_images': ('parent', 'page_size', 'page_token', ), - 'purge_products': ('parent', 'product_set_purge_config', 'delete_orphan_products', 'force', ), - 'remove_product_from_product_set': ('name', 'product', ), - 'update_product': ('product', 'update_mask', ), - 'update_product_set': ('product_set', 'update_mask', ), - + 'add_product_to_product_set': ('name', 'product', ), + 'async_batch_annotate_files': ('requests', 'parent', ), + 'async_batch_annotate_images': ('requests', 'output_config', 'parent', ), + 'batch_annotate_files': ('requests', 'parent', ), + 'batch_annotate_images': ('requests', 'parent', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_product_set': ('parent', 'product_set', 'product_set_id', ), + 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), + 'delete_product': ('name', ), + 'delete_product_set': ('name', ), + 'delete_reference_image': ('name', ), + 'get_product': ('name', ), + 'get_product_set': ('name', ), + 'get_reference_image': ('name', ), + 'import_product_sets': ('parent', 'input_config', ), + 'list_products': ('parent', 'page_size', 'page_token', ), + 'list_product_sets': ('parent', 'page_size', 'page_token', ), + 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), + 'list_reference_images': ('parent', 'page_size', 'page_token', ), + 'purge_products': ('parent', 'product_set_purge_config', 'delete_orphan_products', 'force', ), + 'remove_product_from_product_set': ('name', 'product', ), + 'update_product': ('product', 'update_mask', ), + 'update_product_set': ('product_set', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -82,7 +80,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) @@ -94,7 +92,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_vision_v1p1beta1_keywords.py b/scripts/fixup_vision_v1p1beta1_keywords.py index 363a3f75..9df19d42 100644 --- a/scripts/fixup_vision_v1p1beta1_keywords.py +++ b/scripts/fixup_vision_v1p1beta1_keywords.py @@ -1,6 +1,6 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -40,8 +39,7 @@ def partition( class visionCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'batch_annotate_images': ('requests', ), - + 'batch_annotate_images': ('requests', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -60,7 +58,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) @@ -72,7 +70,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_vision_v1p2beta1_keywords.py b/scripts/fixup_vision_v1p2beta1_keywords.py index a345a1f7..794746cd 100644 --- a/scripts/fixup_vision_v1p2beta1_keywords.py +++ b/scripts/fixup_vision_v1p2beta1_keywords.py @@ -1,6 +1,6 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -40,9 +39,8 @@ def partition( class visionCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'async_batch_annotate_files': ('requests', ), - 'batch_annotate_images': ('requests', ), - + 'async_batch_annotate_files': ('requests', ), + 'batch_annotate_images': ('requests', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -61,7 +59,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) @@ -73,7 +71,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_vision_v1p3beta1_keywords.py b/scripts/fixup_vision_v1p3beta1_keywords.py index 9fcddd5b..2a2a5f13 100644 --- a/scripts/fixup_vision_v1p3beta1_keywords.py +++ b/scripts/fixup_vision_v1p3beta1_keywords.py @@ -1,6 +1,6 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -40,27 +39,26 @@ def partition( class visionCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_product_to_product_set': ('name', 'product', ), - 'async_batch_annotate_files': ('requests', ), - 'batch_annotate_images': ('requests', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_product_set': ('parent', 'product_set', 'product_set_id', ), - 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), - 'delete_product': ('name', ), - 'delete_product_set': ('name', ), - 'delete_reference_image': ('name', ), - 'get_product': ('name', ), - 'get_product_set': ('name', ), - 'get_reference_image': ('name', ), - 'import_product_sets': ('parent', 'input_config', ), - 'list_products': ('parent', 'page_size', 'page_token', ), - 'list_product_sets': ('parent', 'page_size', 'page_token', ), - 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), - 'list_reference_images': ('parent', 'page_size', 'page_token', ), - 'remove_product_from_product_set': ('name', 'product', ), - 'update_product': ('product', 'update_mask', ), - 'update_product_set': ('product_set', 'update_mask', ), - + 'add_product_to_product_set': ('name', 'product', ), + 'async_batch_annotate_files': ('requests', ), + 'batch_annotate_images': ('requests', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_product_set': ('parent', 'product_set', 'product_set_id', ), + 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), + 'delete_product': ('name', ), + 'delete_product_set': ('name', ), + 'delete_reference_image': ('name', ), + 'get_product': ('name', ), + 'get_product_set': ('name', ), + 'get_reference_image': ('name', ), + 'import_product_sets': ('parent', 'input_config', ), + 'list_products': ('parent', 'page_size', 'page_token', ), + 'list_product_sets': ('parent', 'page_size', 'page_token', ), + 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), + 'list_reference_images': ('parent', 'page_size', 'page_token', ), + 'remove_product_from_product_set': ('name', 'product', ), + 'update_product': ('product', 'update_mask', ), + 'update_product_set': ('product_set', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -79,7 +77,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) @@ -91,7 +89,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_vision_v1p4beta1_keywords.py b/scripts/fixup_vision_v1p4beta1_keywords.py index 7877329b..6ce7137f 100644 --- a/scripts/fixup_vision_v1p4beta1_keywords.py +++ b/scripts/fixup_vision_v1p4beta1_keywords.py @@ -1,6 +1,6 @@ +#! /usr/bin/env python3 # -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -40,30 +39,29 @@ def partition( class visionCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_product_to_product_set': ('name', 'product', ), - 'async_batch_annotate_files': ('requests', ), - 'async_batch_annotate_images': ('requests', 'output_config', ), - 'batch_annotate_files': ('requests', ), - 'batch_annotate_images': ('requests', ), - 'create_product': ('parent', 'product', 'product_id', ), - 'create_product_set': ('parent', 'product_set', 'product_set_id', ), - 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), - 'delete_product': ('name', ), - 'delete_product_set': ('name', ), - 'delete_reference_image': ('name', ), - 'get_product': ('name', ), - 'get_product_set': ('name', ), - 'get_reference_image': ('name', ), - 'import_product_sets': ('parent', 'input_config', ), - 'list_products': ('parent', 'page_size', 'page_token', ), - 'list_product_sets': ('parent', 'page_size', 'page_token', ), - 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), - 'list_reference_images': ('parent', 'page_size', 'page_token', ), - 'purge_products': ('parent', 'product_set_purge_config', 'delete_orphan_products', 'force', ), - 'remove_product_from_product_set': ('name', 'product', ), - 'update_product': ('product', 'update_mask', ), - 'update_product_set': ('product_set', 'update_mask', ), - + 'add_product_to_product_set': ('name', 'product', ), + 'async_batch_annotate_files': ('requests', ), + 'async_batch_annotate_images': ('requests', 'output_config', ), + 'batch_annotate_files': ('requests', ), + 'batch_annotate_images': ('requests', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_product_set': ('parent', 'product_set', 'product_set_id', ), + 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), + 'delete_product': ('name', ), + 'delete_product_set': ('name', ), + 'delete_reference_image': ('name', ), + 'get_product': ('name', ), + 'get_product_set': ('name', ), + 'get_reference_image': ('name', ), + 'import_product_sets': ('parent', 'input_config', ), + 'list_products': ('parent', 'page_size', 'page_token', ), + 'list_product_sets': ('parent', 'page_size', 'page_token', ), + 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), + 'list_reference_images': ('parent', 'page_size', 'page_token', ), + 'purge_products': ('parent', 'product_set_purge_config', 'delete_orphan_products', 'force', ), + 'remove_product_from_product_set': ('name', 'product', ), + 'update_product': ('product', 'update_mask', ), + 'update_product_set': ('product_set', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -82,7 +80,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: return updated kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, + lambda a: a.keyword.value not in self.CTRL_PARAMS, kwargs ) @@ -94,7 +92,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/setup.py b/setup.py index f6d14c0e..bb3f0b88 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,46 @@ -# Copyright 2018 Google LLC +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - +# import io import os -import setuptools +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) name = "google-cloud-vision" -description = "Cloud Vision API API client library" -version = "3.1.4" -release_status = "Development Status :: 5 - Production/Stable" + + +description = "Google Cloud Vision API client library" + +version = {} +with open(os.path.join(package_root, "google/cloud/vision/gapic_version.py")) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + dependencies = [ - "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", "proto-plus >= 1.22.0, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] - -extras = {"libcst": "libcst >= 0.2.5"} +url = "https://github.com/googleapis/python-vision" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -53,7 +66,7 @@ author="Google LLC", author_email="googleapis-packages@google.com", license="Apache 2.0", - url="https://github.com/googleapis/python-vision", + url=url, classifiers=[ release_status, "Intended Audience :: Developers", @@ -69,17 +82,9 @@ ], platforms="Posix; MacOS X; Windows", packages=packages, + python_requires=">=3.7", namespace_packages=namespaces, install_requires=dependencies, - extras_require=extras, - python_requires=">=3.7", - scripts=[ - "scripts/fixup_vision_v1_keywords.py", - "scripts/fixup_vision_v1p1beta1_keywords.py", - "scripts/fixup_vision_v1p2beta1_keywords.py", - "scripts/fixup_vision_v1p3beta1_keywords.py", - "scripts/fixup_vision_v1p4beta1_keywords.py", - ], include_package_data=True, zip_safe=False, ) diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt index e69de29b..ed7f9aed 100644 --- a/testing/constraints-3.10.txt +++ b/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt index e69de29b..ed7f9aed 100644 --- a/testing/constraints-3.11.txt +++ b/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 5dcaa6fd..6c44adfe 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -1,10 +1,9 @@ # This constraints file is used to check that lower bounds # are correct in setup.py -# List *all* library dependencies and extras in this file. +# List all library dependencies and extras in this file. # Pin the version to the lower bound. -# -# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", -# Then this file should have foo==1.14.0 -google-api-core==1.32.0 +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 proto-plus==1.22.0 protobuf==3.19.5 diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index e69de29b..ed7f9aed 100644 --- a/testing/constraints-3.8.txt +++ b/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index e69de29b..ed7f9aed 100644 --- a/testing/constraints-3.9.txt +++ b/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/tests/__init__.py b/tests/__init__.py index e69de29b..e8e1c384 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py index e69de29b..e8e1c384 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..e8e1c384 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/vision_v1/test_product_search.py b/tests/unit/gapic/vision_v1/test_product_search.py index 9f980bac..f8731d52 100644 --- a/tests/unit/gapic/vision_v1/test_product_search.py +++ b/tests/unit/gapic/vision_v1/test_product_search.py @@ -50,6 +50,7 @@ from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore diff --git a/tests/unit/gapic/vision_v1p4beta1/test_product_search.py b/tests/unit/gapic/vision_v1p4beta1/test_product_search.py index b270f873..9191539f 100644 --- a/tests/unit/gapic/vision_v1p4beta1/test_product_search.py +++ b/tests/unit/gapic/vision_v1p4beta1/test_product_search.py @@ -52,6 +52,7 @@ from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore