python_code stringlengths 0 456k |
|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Softmax(Base):
@staticmethod
def export(): # type: () -> No... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Atan(Base):
@staticmethod
def export(): # type: () -> None
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Atanh(Base):
@staticmethod
def export(): # type: () -> None... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Acos(Base):
@staticmethod
def export(): # type: () -> None
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Expand(Base):
@staticmethod
def export_dim_changed(): # typ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class QLinearConv(Base):
@staticmethod
def export(): # type: () ->... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Sin(Base):
@staticmethod
def export(): # type: () -> None
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
# The below GatherElements' numpy implementation is from https://stackoverf... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Selu(Base):
@staticmethod
def export(): # type: () -> None
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Reciprocal(Base):
@staticmethod
def export(): # type: () ->... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
def argmin_use_numpy(data, axis=0, keepdims=1): # type: (np.ndarray, int, ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class DepthToSpace(Base):
@staticmethod
def export_default_mode_ex... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class And(Base):
@staticmethod
def export(): # type: () -> None
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pytest # type: ignore
from .coverage import Coverage
from typing import Dict, Text, Sequence, Any, List
_coverage = Coverage()
_marks = {} # type: Dict[Text, S... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import defaultdict, OrderedDict
import os
import csv
import datetime
from tabulate import tabulate # type: ignore
import onnx
from onnx import defs, h... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
class ReporterBase(object):
pass
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
def abs(input): # type: (np.ndarray) -> np.ndarray
return np.abs(input)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import importlib
import inspect
import sys
import pkgutil
from typing import Dict, Text
from types import ModuleType
def collect_sample_implementations(): # type: () -... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from onnx import defs
def main(): # type: () -> None
# domain -> support level -> name -> [schema]
with_inference = []
without_inference = []
for schem... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from onnx import AttributeProto, FunctionProto
import onnx.onnx_cpp2py_export.defs as C
from collections import defaultdict
from typing import List, Dict
ONNX_DOMAIN = ... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import defaultdict
import io
import os
import sys
import numpy as np # type: ignore
from onnx import defs, FunctionProto, helper... |
import distutils.command.clean
import glob
import os
import shutil
import subprocess
import sys
import torch
from setuptools import find_packages, setup
from torch.utils.cpp_extension import (
BuildExtension,
CppExtension,
CUDA_HOME,
CUDAExtension,
)
version = open("version.txt", "r").read().strip()
s... |
# -*- coding: utf-8 -*-
"""Helper script to package wheels and relocate binaries."""
import glob
import hashlib
import io
# Standard library imports
import os
import os.path as osp
import platform
import shutil
import subprocess
import sys
import zipfile
from base64 import urlsafe_b64encode
# Third party imports
if... |
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
|
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import math
import os
import random
import time
import unittest
import numpy as np
import torch
from Crypto.Ciph... |
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torchcsprng._C import *
try:
from .version import __version__, git_version # noqa: F401... |
#!/usr/bin/env python
"""
TODO: This was hard to read in pkg_helpers.bash, so I've extracted it
to its own script. This script is not yet being called by
pkg_helpers.bash yet.
"""
import os
import sys
import json
import re
cuver = os.environ.get('CU_VERSION')
cuver = (cuver[:-1] + '.' + cuver[-1]).replace('cu', 'c... |
#!/usr/bin/env python3
import os.path
import unittest
import subprocess
import sys
import os
TIMEOUT = 2 * 60 * 60 # 2 hours
def run(command, timeout=None):
"""
Returns (return-code, stdout, stderr)
"""
completed = subprocess.run(command, stdout=subprocess.PIPE,
... |
import re
import subprocess32
import sys
PY3 = sys.version_info >= (3, 0)
reinforce_cmd = 'python examples/reinforcement_learning/reinforce.py'
actor_critic_cmd = 'python examples/reinforcement_learning/actor_critic.py'
def run(command, timeout):
"""
Returns (return-code, stdout, stderr)
"""
p = sub... |
import re
import subprocess
import sys
import os
PY3 = sys.version_info >= (3, 0)
def run(command, timeout):
"""
Returns (return-code, stdout, stderr)
"""
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, err = p.communicate(timeout=timeout)
rc... |
#!/usr/bin/env python
import zipfile
import re
import sys
def unzip(path):
"""
Unzips /path/to/some.zip to ./some
Doesn't work with - or _ in 'some'
"""
match = re.search("(\w+)\.zip", path)
if match is None:
print("Could not parse path")
return
dest = match.group(1)
... |
import re
import subprocess
import sys
import argparse
PY3 = sys.version_info >= (3, 0)
blacklist = [
"./advanced_source/super_resolution_with_caffe2.py",
# The docker image's python has some trouble with decoding unicode
"./intermediate_source/char_rnn_classification_tutorial.py",
]
visual = [
"./ad... |
# Logic copied from PEP 513
def is_manylinux1_compatible():
# Only Linux, and only x86-64 / i686
from distutils.util import get_platform
if get_platform() not in ["linux-x86_64", "linux-i686"]:
return False
# Check for presence of _manylinux module
try:
import _manylinux
re... |
# cf. https://github.com/pypa/manylinux/issues/53
GOOD_SSL = "https://google.com"
BAD_SSL = "https://self-signed.badssl.com"
import sys
print("Testing SSL certificate checking for Python:", sys.version)
if (sys.version_info[:2] < (2, 7)
or sys.version_info[:2] < (3, 4)):
print("This version never checks SSL... |
# Utility script to print the python tag + the abi tag for a Python
# See PEP 425 for exactly what these are, but an example would be:
# cp27-cp27mu
from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag
print("{0}{1}-{2}".format(get_abbr_impl(), get_impl_ver(), get_abi_tag())) |
import json
import sys
# Usage:
# write_json.py input_file output_file
# Reads a file of '<platform> <log_name> <size>' into a json file
inputfile = sys.argv[1]
outputfile = sys.argv[2]
data = []
with open(inputfile, 'r') as infile:
for line in infile:
platform, pkg_type, py_ver, cu_ver, size = line.s... |
import json
import sys
# Usage:
# parse_conda_json.py input_file output_file
# Reads the result of a `conda search --json` into lines of '<platform>
# <log_name> <size>'
inputfile = sys.argv[1]
outputfile = sys.argv[2]
data = []
with open(inputfile, 'rb') as jsonfile:
rawdata = json.load(jsonfile)
# cond... |
#!/usr/bin/env python3.7
from datetime import datetime, time
import json
import requests
import itertools
import sqlite3
import os
import sys
from typing import Callable, Dict, List, MutableSet, Optional, Sequence
def get_executor_price_rate(executor):
(etype, eclass) = executor['type'], executor['resource_class']... |
#!/usr/bin/env python3
# Tool for analyzing sizes of CUDA kernels for various GPU architectures
import os
import struct
import sys
# Try to auto-import elftools
try:
from elftools.elf.elffile import ELFFile
except ModuleNotFoundError:
print(f'elftools module not found, trying to install it from pip')
from ... |
from collections import defaultdict
from datetime import datetime, timedelta, timezone
import gzip
import multiprocessing
import os
import re
import urllib
from tqdm import tqdm
import botocore
import boto3
S3 = boto3.resource('s3')
CLIENT = boto3.client('s3')
BUCKET = S3.Bucket('pytorch')
class CacheEntry:
_siz... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
from pathlib import Path
from setuptools import setup
PKG_NAME = "python-doctr"
VERSION = os.getenv("BUILD_VERSION", "0.... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import cv2
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
from doctr.file_utils import is_tf_available
f... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import numpy as np
import tensorflow as tf
from doctr.models import ocr_predictor
from doctr.models.predictor import OCRPredictor
... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import numpy as np
import torch
from doctr.models import ocr_predictor
from doctr.models.predictor import OCRPredictor
DET_ARCHS =... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
"""
Image classification latency benchmark
"""
import argparse
import os
import time
import numpy as np
import tensorflow as tf
o... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
"""
Image classification latency benchmark
"""
import argparse
import os
import time
import numpy as np
import torch
os.environ["... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TF"] = "1"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import datetime
import multiprocessing as mp
import ... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import math
import matplotlib.pyplot as plt
import numpy as np
def plot_samples(images, targets):
# Unnormalize image
num... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TORCH"] = "1"
import datetime
import logging
import multiprocessing as mp
import time
import numpy as n... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
"""
Text recognition latency benchmark
"""
import argparse
import os
import time
import numpy as np
import tensorflow as tf
os.en... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
"""
Text recognition latency benchmark
"""
import argparse
import os
import time
import numpy as np
import torch
os.environ["USE_... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TF"] = "1"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import datetime
import hashlib
import multiprocessin... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TORCH"] = "1"
import multiprocessing as mp
import time
import torch
from torch.utils.data import DataLo... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TF"] = "1"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import multiprocessing as mp
import time
import ten... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import math
import matplotlib.pyplot as plt
import numpy as np
def plot_samples(images, targets):
# Unnormalize image
num... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TORCH"] = "1"
import datetime
import hashlib
import logging
import multiprocessing as mp
import time
fro... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TORCH"] = "1"
import datetime
import hashlib
import multiprocessing
import time
from pathlib import Path... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
"""
Text detection latency benchmark
"""
import argparse
import os
import time
import numpy as np
import tensorflow as tf
os.envi... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
"""
Text detection latency benchmark
"""
import argparse
import os
import time
import numpy as np
import torch
os.environ["USE_TO... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TF"] = "1"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import datetime
import hashlib
import multiprocessin... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
from doctr.file_utils import CLASS_NAME
os.environ["USE_TORCH"] = "1"
import logging
import multiprocessing as mp
impor... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
from doctr.file_utils import CLASS_NAME
os.environ["USE_TF"] = "1"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import mult... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import pickle
from typing import Dict, List
import cv2
import matplotlib.pyplot as plt
import numpy as np
def plot_samples(images... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TORCH"] = "1"
import datetime
import hashlib
import logging
import multiprocessing as mp
import time
im... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
"""
Object detection latency benchmark
"""
import argparse
import os
import time
import numpy as np
import torch
os.environ["USE_... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
from typing import Dict, List
import cv2
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.cm import get_cmap
de... |
# Copyright (C) 2021-2023, Mindee.
# This program is licensed under the Apache License 2.0.
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import os
os.environ["USE_TORCH"] = "1"
import datetime
import logging
import multiprocessing as mp
import time
import numpy as n... |
import json
import shutil
import tempfile
from io import BytesIO
import cv2
import hdf5storage
import numpy as np
import pytest
import requests
import scipy.io as sio
from PIL import Image
from doctr.datasets.generator.base import synthesize_text_img
from doctr.io import reader
from doctr.utils import geometry
@pyt... |
import os
from doctr.io import DocumentFile
from doctr.models.artefacts import BarCodeDetector, FaceDetector
def test_qr_code_detector(mock_image_folder):
detector = BarCodeDetector()
for img in os.listdir(mock_image_folder):
image = DocumentFile.from_images(os.path.join(mock_image_folder, img))[0]
... |
from PIL.ImageFont import FreeTypeFont, ImageFont
from doctr.utils.fonts import get_font
def test_get_font():
# Attempts to load recommended OS font
font = get_font()
assert isinstance(font, (ImageFont, FreeTypeFont))
|
import numpy as np
import pytest
from doctr.file_utils import CLASS_NAME
from doctr.io import Document
from doctr.io.elements import KIEDocument
from doctr.models import builder
words_per_page = 10
boxes_1 = {CLASS_NAME: np.random.rand(words_per_page, 6)} # dict format
boxes_1[CLASS_NAME][:2] *= boxes_1[CLASS_NAME]... |
from copy import deepcopy
from math import hypot
import numpy as np
import pytest
from doctr.io import DocumentFile
from doctr.utils import geometry
def test_bbox_to_polygon():
assert geometry.bbox_to_polygon(((0, 0), (1, 1))) == ((0, 0), (1, 0), (0, 1), (1, 1))
def test_polygon_to_bbox():
assert geometry... |
import numpy as np
import pytest
from test_io_elements import _mock_pages
from doctr.utils import visualization
def test_visualize_page():
pages = _mock_pages()
image = np.ones((300, 200, 3))
visualization.visualize_page(pages[0].export(), image, words_only=False)
visualization.visualize_page(pages[0... |
import numpy as np
import pytest
from doctr.datasets import utils
@pytest.mark.parametrize(
"input_str, vocab, output_str",
[
["f orêt", "latin", "foret"],
["f or êt", "french", "forêt"],
["¢¾©téØßřůž", "french", "¢■■té■■ruz"],
["Ûæëð", "french", "Û■ë■"],
["Ûæë<àð", "l... |
from pathlib import Path
import numpy as np
import pytest
from doctr import datasets
def test_visiondataset():
url = "https://data.deepai.org/mnist.zip"
with pytest.raises(ValueError):
datasets.datasets.VisionDataset(url, download=False)
dataset = datasets.datasets.VisionDataset(url, download=T... |
import numpy as np
import pytest
from doctr.models.detection.differentiable_binarization.base import DBPostProcessor
from doctr.models.detection.linknet.base import LinkNetPostProcessor
def test_dbpostprocessor():
postprocessor = DBPostProcessor(assume_straight_pages=True)
r_postprocessor = DBPostProcessor(a... |
import doctr
def test_version():
assert len(doctr.__version__.split(".")) == 3
def test_is_tf_available():
assert doctr.is_tf_available()
def test_is_torch_available():
assert not doctr.is_torch_available()
|
import os
from pathlib import PosixPath
from unittest.mock import patch
import pytest
from doctr.utils.data import download_from_url
@patch("doctr.utils.data._urlretrieve")
@patch("pathlib.Path.mkdir")
@patch.dict(os.environ, {"HOME": "/"}, clear=True)
def test_download_from_url(mkdir_mock, urlretrieve_mock):
d... |
from io import BytesIO
import numpy as np
import pytest
import requests
from doctr import io
def _check_doc_content(doc_tensors, num_pages):
# 1 doc of 8 pages
assert len(doc_tensors) == num_pages
assert all(isinstance(page, np.ndarray) for page in doc_tensors)
assert all(page.dtype == np.uint8 for ... |
import pytest
from doctr.models.recognition.utils import merge_multi_strings, merge_strings
@pytest.mark.parametrize(
"a, b, merged",
[
["abc", "def", "abcdef"],
["abcd", "def", "abcdef"],
["abcde", "def", "abcdef"],
["abcdef", "def", "abcdef"],
["abcccc", "cccccc", "a... |
import numpy as np
import pytest
from doctr.utils import metrics
@pytest.mark.parametrize(
"gt, pred, raw, caseless, unidecode, unicase",
[
[["grass", "56", "True", "EUR"], ["grass", "56", "true", "€"], 0.5, 0.75, 0.75, 1],
[["éléphant", "ça"], ["elephant", "ca"], 0, 0, 1, 1],
],
)
def te... |
from io import BytesIO
import cv2
import numpy as np
import pytest
import requests
from doctr.io import reader
from doctr.models._utils import estimate_orientation, get_bitmap_angle, get_language, invert_data_structure
from doctr.utils import geometry
@pytest.fixture(scope="function")
def mock_image(tmpdir_factory)... |
import numpy as np
import pytest
from doctr.transforms import modules as T
from doctr.transforms.functional.base import expand_line
def test_imagetransform():
transfo = T.ImageTransform(lambda x: 1 - x)
assert transfo(0, 1) == (1, 1)
def test_samplecompose():
transfos = [lambda x, y: (1 - x, y), lambda... |
import numpy as np
import pytest
from doctr.models.recognition.predictor._utils import remap_preds, split_crops
@pytest.mark.parametrize(
"crops, max_ratio, target_ratio, dilation, channels_last, num_crops",
[
# No split required
[[np.zeros((32, 128, 3), dtype=np.uint8)], 8, 4, 1.4, True, 1],... |
import os
from multiprocessing.pool import ThreadPool
from unittest.mock import patch
import pytest
from doctr.utils.multithreading import multithread_exec
@pytest.mark.parametrize(
"input_seq, func, output_seq",
[
[[1, 2, 3], lambda x: 2 * x, [2, 4, 6]],
[[1, 2, 3], lambda x: x**2, [1, 4, 9... |
"""Test for python files copyright headers."""
from datetime import datetime
from pathlib import Path
def test_copyright_header():
copyright_header = "".join(
[
f"# Copyright (C) {2021}-{datetime.now().year}, Mindee.\n\n",
"# This program is licensed under the Apache License 2.0.\... |
from xml.etree.ElementTree import ElementTree
import numpy as np
import pytest
from doctr.file_utils import CLASS_NAME
from doctr.io import elements
def _mock_words(size=(1.0, 1.0), offset=(0, 0), confidence=0.9):
return [
elements.Word(
"hello", confidence, ((offset[0], offset[1]), (size[0]... |
from doctr.file_utils import is_tf_available
def test_file_utils():
assert is_tf_available()
|
import math
import numpy as np
import pytest
import tensorflow as tf
from doctr import transforms as T
from doctr.transforms.functional import crop_detection, rotate_sample
def test_resize():
output_size = (32, 32)
transfo = T.Resize(output_size)
input_t = tf.cast(tf.fill([64, 64, 3], 1), dtype=tf.float... |
import os
import shutil
import tempfile
import numpy as np
import onnxruntime
import pytest
import tensorflow as tf
from doctr.io import DocumentFile
from doctr.models import recognition
from doctr.models.preprocessor import PreProcessor
from doctr.models.recognition.crnn.tensorflow import CTCPostProcessor
from doctr... |
import numpy as np
import pytest
from doctr import models
from doctr.file_utils import CLASS_NAME
from doctr.io import Document, DocumentFile
from doctr.io.elements import KIEDocument
from doctr.models import detection, recognition
from doctr.models.detection.predictor import DetectionPredictor
from doctr.models.detec... |
import os
import pytest
import tensorflow as tf
from tensorflow.keras import Sequential, layers
from tensorflow.keras.applications import ResNet50
from doctr.models.utils import IntermediateLayerGetter, conv_sequence, load_pretrained_params
def test_load_pretrained_params(tmpdir_factory):
model = Sequential([la... |
import numpy as np
import pytest
import tensorflow as tf
from doctr.models.preprocessor import PreProcessor
@pytest.mark.parametrize(
"batch_size, output_size, input_tensor, expected_batches, expected_value",
[
[2, (128, 128), np.full((3, 256, 128, 3), 255, dtype=np.uint8), 1, 0.5], # numpy uint8
... |
from typing import List, Tuple
import tensorflow as tf
from doctr.datasets import DataLoader
class MockDataset:
def __init__(self, input_size):
self.data: List[Tuple[float, bool]] = [
(1, True),
(0, False),
(0.5, True),
]
self.input_size = input_size
... |
import os
import tempfile
import cv2
import numpy as np
import onnxruntime
import pytest
import tensorflow as tf
from doctr.models import classification
from doctr.models.classification.predictor import CropOrientationPredictor
from doctr.models.utils import export_model_to_onnx
@pytest.mark.parametrize(
"arch_... |
import os
from shutil import move
import numpy as np
import pytest
import tensorflow as tf
from doctr import datasets
from doctr.datasets import DataLoader
from doctr.file_utils import CLASS_NAME
from doctr.transforms import Resize
def _validate_dataset(ds, input_size, batch_size=2, class_indices=False, is_polygons... |
import os
import tempfile
import numpy as np
import onnxruntime
import pytest
import tensorflow as tf
from doctr.file_utils import CLASS_NAME
from doctr.io import DocumentFile
from doctr.models import detection
from doctr.models.detection._utils import dilate, erode
from doctr.models.detection.predictor import Detect... |
import json
import os
import tempfile
import pytest
import tensorflow as tf
from doctr import models
from doctr.models.factory import _save_model_and_config_for_hf_hub, from_hub, push_to_hf_hub
def test_push_to_hf_hub():
model = models.classification.resnet18(pretrained=False)
with pytest.raises(ValueError)... |
import numpy as np
import pytest
import tensorflow as tf
from doctr.io import decode_img_as_tensor, read_img_as_tensor, tensor_from_numpy
def test_read_img_as_tensor(mock_image_path):
img = read_img_as_tensor(mock_image_path)
assert isinstance(img, tf.Tensor)
assert img.dtype == tf.float32
assert im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.