python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
#!/usr/bin/env python # Tsung-Yi Lin <tl483@cornell.edu> # Ramakrishna Vedantam <vrama91@vt.edu> import copy from collections import defaultdict import numpy as np import pdb import math def precook(s, n=4, out=False): """ Takes a string as input and returns an object that can be given to either cook_refs...
comet-atomic-2020-master
system_eval/evaluation/cider/cider_scorer.py
#!/usr/bin/env python # Python wrapper for METEOR implementation, by Xinlei Chen # Acknowledge Michael Denkowski for the generous discussion and help import os import sys import nltk from nltk.translate.meteor_score import meteor_score # Assumes meteor-1.5.jar is in the same directory as meteor.py. Change as neede...
comet-atomic-2020-master
system_eval/evaluation/meteor/meteor_nltk.py
__author__ = 'tylin'
comet-atomic-2020-master
system_eval/evaluation/meteor/__init__.py
#!/usr/bin/env python # Python wrapper for METEOR implementation, by Xinlei Chen # Acknowledge Michael Denkowski for the generous discussion and help import os import sys import subprocess import threading # Assumes meteor-1.5.jar is in the same directory as meteor.py. Change as needed. METEOR_JAR = 'meteor-1.5.ja...
comet-atomic-2020-master
system_eval/evaluation/meteor/meteor.py
#!/usr/bin/env python # # File Name : bleu.py # # Description : Wrapper for BLEU scorer. # # Creation Date : 06-01-2015 # Last Modified : Thu 19 Mar 2015 09:13:28 PM PDT # Authors : Hao Fang <hfang@uw.edu> and Tsung-Yi Lin <tl483@cornell.edu> from evaluation.bleu.bleu_scorer import BleuScorer class Bleu: def __...
comet-atomic-2020-master
system_eval/evaluation/bleu/bleu.py
__author__ = 'tylin'
comet-atomic-2020-master
system_eval/evaluation/bleu/__init__.py
#!/usr/bin/env python # bleu_scorer.py # David Chiang <chiang@isi.edu> # Copyright (c) 2004-2006 University of Maryland. All rights # reserved. Do not redistribute without permission from the # author. Not for commercial use. # Modified by: # Hao Fang <hfang@uw.edu> # Tsung-Yi Lin <tl483@cornell.edu> '''Provides: ...
comet-atomic-2020-master
system_eval/evaluation/bleu/bleu_scorer.py
from bert_score import score # Code for BertScore reused from original implementation: https://github.com/Tiiiger/bert_score class BertScore: def __init__(self): self._hypo_for_image = {} self.ref_for_image = {} def compute_score(self, gts, res): assert(gts.keys() == res.keys()) ...
comet-atomic-2020-master
system_eval/evaluation/bert_score/bert_score.py
comet-atomic-2020-master
system_eval/evaluation/bert_score/__init__.py
import torch from math import log from itertools import chain from collections import defaultdict, Counter from multiprocessing import Pool from functools import partial from tqdm.auto import tqdm __all__ = ['bert_types'] bert_types = [ 'bert-base-uncased', 'bert-large-uncased', 'bert-base-cased', 'be...
comet-atomic-2020-master
system_eval/evaluation/bert_score/utils.py
import os import time import argparse import torch from collections import defaultdict from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM import matplotlib import matplotlib.pyplot as plt import numpy as np from .utils import get_idf_dict, bert_cos_score_idf,\ get_bert_emb...
comet-atomic-2020-master
system_eval/evaluation/bert_score/score.py
#!/usr/bin/env python # # File Name : rouge.py # # Description : Computes ROUGE-L metric as described by Lin and Hovey (2004) # # Creation Date : 2015-01-07 06:03 # Author : Ramakrishna Vedantam <vrama91@vt.edu> import numpy as np import pdb def my_lcs(string, sub): """ Calculates longest common subsequence ...
comet-atomic-2020-master
system_eval/evaluation/rouge/rouge.py
__author__ = 'vrama91'
comet-atomic-2020-master
system_eval/evaluation/rouge/__init__.py
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="aries", version="0.1.0", author="Mike D'Arcy", author_email="miked@collaborator.allenai.org", description="Code for the ARIES project", long_description=long_description, long_desc...
aries-master
setup.py
from aries.util.edit import levenshtein_distance, basic_token_align, find_overlapping_substrings def test_basic_token_align(): seq1 = ['this', 'is', 'my', 'sentence'] seq2 = ['this', 'is', 'my', 'sentence'] d, align = basic_token_align(seq1, seq2) assert d == 0 assert align == [0, 1, 2, 3] se...
aries-master
tests/test_edit.py
from . import *
aries-master
aries/__init__.py
import datetime import json import logging import os import sqlite3 import time import openai import tiktoken import tqdm logger = logging.getLogger(__name__) class Gpt3CacheClient: def __init__(self, cache_db_path): self.cache_db = self._init_cache_db(cache_db_path) if openai.api_key is None: ...
aries-master
aries/util/gpt3.py
import logging import os import pprint from typing import Callable, List, Union logger = logging.getLogger(__name__) def init_logging(logfile=None, level=logging.INFO): handlers = [ logging.StreamHandler(), ] if logfile: handlers.append(logging.FileHandler(logfile)) logging.basicConf...
aries-master
aries/util/logging.py
import re # Adapted from jupyterlab css COLOR_TABLE = { "black": {"hex": "3e424d", "ansi": "30"}, "red": {"hex": "e75c58", "ansi": "31"}, "green": {"hex": "00a050", "ansi": "32"}, "yellow": {"hex": "ddbb33", "ansi": "33"}, "blue": {"hex": "2090ff", "ansi": "34"}, "magenta": {"hex": "d060c0", "a...
aries-master
aries/util/color.py
aries-master
aries/util/__init__.py
import collections import difflib import itertools from typing import Iterable, List, Tuple, Union import numpy as np import tqdm from cffi import FFI from .color import colorify, colorprint def init_levenshtein_c(): ffibuilder = FFI() ffibuilder.set_source( "_levenshtein", r""" ...
aries-master
aries/util/edit.py
import json import logging import os import sqlite3 import sys import tqdm logger = logging.getLogger(__name__) def fuse_back_matter(s2json): """Fuse back matter into body text (mutating the input object) and return the mutated s2orc object. Often the parser puts whatever is on the last pdf page into b...
aries-master
aries/util/s2orc.py
import collections import json import logging import os import torch import transformers from .logging import pprint_metrics logger = logging.getLogger(__name__) class TrainLoggerCallback(transformers.TrainerCallback): def __init__(self, logger): self.logger = logger def on_log(self, args, state, ...
aries-master
aries/util/training.py
import glob import gzip import itertools import json import lzma import os import sqlite3 from typing import Any, Callable, Dict, Iterable, Iterator, List, Union import numpy as np try: import zstandard except ImportError: zstandard = None try: import orjson except ImportError: orjson = json class ...
aries-master
aries/util/data.py
import itertools import logging import gensim logger = logging.getLogger(__name__) def stem_tokens(tokens): return list(map(gensim.parsing.preprocessing.stem, tokens)) class InMemoryTextCorpus(gensim.corpora.textcorpus.TextCorpus): def __init__(self, texts, dictionary=None, **kwargs): self.texts =...
aries-master
aries/util/gensim.py
import difflib import itertools import json import logging import os import sys import gensim import numpy as np import tqdm import aries.util.data import aries.util.edit import aries.util.gensim from aries.alignment.eval import full_tune_optimal_thresholds logger = logging.getLogger(__name__) class BM25Aligner: ...
aries-master
aries/alignment/bm25.py
import logging logger = logging.getLogger(__name__) class MultiStageAligner: def __init__(self, config, aligners): self.config = config self.aligners = aligners self.prune_candidates = config.get("prune_candidates", False) def train(self, train_recs, dev_recs): logger.info("...
aries-master
aries/alignment/other.py
import functools import logging import os import sys import datasets import numpy as np import torch import tqdm import transformers from aries.alignment.eval import AlignerEvalCallback from aries.util.edit import make_word_diff from aries.util.training import TrainLoggerCallback logger = logging.getLogger(__name__)...
aries-master
aries/alignment/cross_encoder.py
import collections import difflib import html import io import itertools import logging import re import sys from typing import Any, Dict, List, Optional, Tuple, Union import nltk.corpus import nltk.util import numpy as np import tqdm from nltk.util import ngrams import aries.util.data import aries.util.edit import a...
aries-master
aries/alignment/doc_edits.py
import collections import json import logging import os import sys import numpy as np import sklearn.exceptions import sklearn.metrics import transformers from aries.util.data import index_by from aries.util.logging import pprint_metrics logger = logging.getLogger(__name__) class AlignerEvalCallback(transformers.T...
aries-master
aries/alignment/eval.py
import json import logging import os import sys from aries.util.data import index_by, openc logger = logging.getLogger(__name__) class PrecomputedEditsAligner: def __init__(self, config): self.config = config def train(self, train_recs, dev_recs): logger.warning("{} doesn't train; ignoring ...
aries-master
aries/alignment/precomputed.py
import functools import logging import os import sys import datasets import numpy as np import torch import tqdm import transformers from aries.alignment.eval import AlignerEvalCallback from aries.util.data import batch_iter from aries.util.edit import make_word_diff from aries.util.training import TrainLoggerCallbac...
aries-master
aries/alignment/biencoder.py
import itertools import json import logging import os import sys import tqdm from aries.util.data import index_by from aries.util.edit import make_word_diff from aries.util.gpt3 import Gpt3CacheClient logger = logging.getLogger(__name__) class GptChatAligner: def __init__(self, config): self.config = c...
aries-master
aries/alignment/gpt.py
import collections import itertools import json import logging import os import re import sys import time import nltk import nltk.util import numpy as np import tqdm from nltk.util import ngrams import aries.util.data import aries.util.s2orc from aries.alignment.doc_edits import make_full_aligns from aries.util.data ...
aries-master
scripts/generate_synthetic_data.py
import collections import itertools import json import logging import os import sys import numpy as np import sacrebleu import torch import tqdm import transformers import aries.util.data import aries.util.s2orc from aries.alignment.biencoder import BiencoderTransformerAligner from aries.alignment.bm25 import BM25Ali...
aries-master
scripts/train_revision_alignment.py
import json import logging import os import sys import tqdm import aries.util.data import aries.util.s2orc from aries.util.data import index_by, iter_jsonl_files from aries.util.gpt3 import Gpt3CacheClient from aries.util.logging import init_logging logger = logging.getLogger(__name__) def generate_edits_for_doc_c...
aries-master
scripts/generate_edits.py
import unittest import datastore from typing import * class TestDatastore(unittest.TestCase): """These tests require access to the public AI2 datastore.""" def test_download_file(self): p = datastore.public.file("org.allenai.datastore", "DatastoreCli.jar", 1) assert p.is_file() def test_d...
datastore-master
python/datastore_test.py
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='datastore', version='3.2.1', de...
datastore-master
python/setup.py
#!/usr/bin/python3 import logging from typing import * import boto3 import platform from pathlib import Path import os import time import atexit import shutil import tempfile import zipfile import botocore def _mkpath(p: Path) -> None: p.mkdir(mode=0o755, parents=True, exist_ok=True) # # Cleanup stuff # _cleanu...
datastore-master
python/datastore.py
import sys import os sys.path.append(os.path.abspath(os.path.join("..", "nla_semparse"))) from nla_semparse.nla_metric import NlaMetric def test_metric_basic(): metric = NlaMetric() metric(['2'], ['2']) assert metric.get_metric() == {"well_formedness": 1.0, "denotation...
allennlp-guide-examples-master
nla_semparse/tests/nla_metric_test.py
allennlp-guide-examples-master
nla_semparse/nla_semparse/__init__.py
from allennlp_semparse import DomainLanguage, predicate class NlaLanguage(DomainLanguage): def __init__(self): super().__init__( start_types={int}, allowed_constants={ "0": 0, "1": 1, "2": 2, "3": 3, "4...
allennlp-guide-examples-master
nla_semparse/nla_semparse/nla_language.py
from typing import Dict, List, Optional from overrides import overrides from allennlp.training.metrics.metric import Metric from allennlp_semparse.domain_languages.domain_language import ExecutionError from .nla_language import NlaLanguage @Metric.register('nla_metric') class NlaMetric(Metric): """ Metric fo...
allennlp-guide-examples-master
nla_semparse/nla_semparse/nla_metric.py
import sys import os import random import math import argparse from typing import List, Dict sys.path.append(os.path.abspath(os.path.join('..', 'nla_semparse'))) from nla_semparse.nla_language import NlaLanguage class DataGenerator: """ Generator for data points for natural language arithmetic. """ ...
allennlp-guide-examples-master
nla_semparse/scripts/generate_data.py
import tempfile from typing import Dict, Iterable, List, Tuple import torch import allennlp from allennlp.common import JsonDict from allennlp.data import DataLoader, DatasetReader, Instance from allennlp.data import Vocabulary from allennlp.data.fields import LabelField, TextField from allennlp.data.token_indexers i...
allennlp-guide-examples-master
quick_start/predict.py
allennlp-guide-examples-master
quick_start/__init__.py
import tempfile from typing import Dict, Iterable, List, Tuple import allennlp import torch from allennlp.data import DataLoader, DatasetReader, Instance, Vocabulary from allennlp.data.fields import LabelField, TextField from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer from allennlp.data.tok...
allennlp-guide-examples-master
quick_start/train.py
import tempfile from typing import Dict, Iterable, List, Tuple import torch import allennlp from allennlp.data import DataLoader, DatasetReader, Instance, Vocabulary from allennlp.data.fields import LabelField, TextField from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer from allennlp.data.to...
allennlp-guide-examples-master
quick_start/evaluate.py
from .dataset_readers import * from .models import * from .predictors import *
allennlp-guide-examples-master
quick_start/my_text_classifier/__init__.py
from .classification_tsv import ClassificationTsvReader
allennlp-guide-examples-master
quick_start/my_text_classifier/dataset_readers/__init__.py
from typing import Dict, Iterable, List from allennlp.data import DatasetReader, Instance from allennlp.data.fields import LabelField, TextField from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer from allennlp.data.tokenizers import Token, Tokenizer, WhitespaceTokenizer @DatasetReader.regist...
allennlp-guide-examples-master
quick_start/my_text_classifier/dataset_readers/classification_tsv.py
from .sentence_classifier_predictor import SentenceClassifierPredictor
allennlp-guide-examples-master
quick_start/my_text_classifier/predictors/__init__.py
from allennlp.common import JsonDict from allennlp.data import DatasetReader, Instance from allennlp.models import Model from allennlp.predictors import Predictor from overrides import overrides @Predictor.register("sentence_classifier") class SentenceClassifierPredictor(Predictor): def predict(self, sentence: st...
allennlp-guide-examples-master
quick_start/my_text_classifier/predictors/sentence_classifier_predictor.py
from .simple_classifier import SimpleClassifier
allennlp-guide-examples-master
quick_start/my_text_classifier/models/__init__.py
from typing import Dict import torch from allennlp.data import Vocabulary from allennlp.data import TextFieldTensors from allennlp.models import Model from allennlp.modules import TextFieldEmbedder, Seq2VecEncoder from allennlp.nn import util from allennlp.training.metrics import CategoricalAccuracy @Model.register(...
allennlp-guide-examples-master
quick_start/my_text_classifier/models/simple_classifier.py
#!/usr/bin/python import os import setuptools requirements_file = os.path.join( os.path.dirname(__file__), 'requirements.txt') requirements = open(requirements_file).read().split('\n') requirements = [r for r in requirements if not '-e' in r] setuptools.setup( name='deepfigures-open', version='0.0.1'...
deepfigures-open-master
setup.py
"""Management commands for the deepfigures project. ``manage.py`` provides an interface to the scripts automating development activities found in the `scripts` directory. See the ``scripts`` directory for examples. """ import logging import sys import click from scripts import ( build, detectfigures, g...
deepfigures-open-master
manage.py
"""Build docker images for deepfigures. See ``build.py --help`` for more information. """ import logging import click from deepfigures import settings from scripts import execute logger = logging.getLogger(__name__) @click.command( context_settings={ 'help_option_names': ['-h', '--help'] }) def ...
deepfigures-open-master
scripts/build.py
"""Detect the figures in a PDF.""" import logging import os import click logger = logging.getLogger(__name__) @click.command( context_settings={ 'help_option_names': ['-h', '--help'] }) @click.argument( 'output_directory', type=click.Path(file_okay=False)) @click.argument( 'pdf_pat...
deepfigures-open-master
scripts/rundetection.py
"""Generate pubmed data for deepfigures. See ``generatepubmed.py --help`` for more information. """ import logging import click from deepfigures import settings from scripts import build, execute logger = logging.getLogger(__name__) @click.command( context_settings={ 'help_option_names': ['-h', '--h...
deepfigures-open-master
scripts/generatepubmed.py
"""Run figure detection on a PDF. See ``detectfigures.py --help`` for more information. """ import logging import os import click from deepfigures import settings from scripts import build, execute logger = logging.getLogger(__name__) @click.command( context_settings={ 'help_option_names': ['-h', '-...
deepfigures-open-master
scripts/detectfigures.py
"""Scripts automating development tasks for deepfigures.""" import subprocess def execute( command, logger, quiet=False, raise_error=True): """Execute ``command``. Parameters ---------- command : str The command to execute in the shell. logger : logging.Ro...
deepfigures-open-master
scripts/__init__.py
"""Generate arxiv data for deepfigures. Generate the arxiv data for deepfigures. This data generation process requires pulling down all the arxiv source files from S3 which the requester (person executing this script) must pay for. See ``generatearxiv.py --help`` for more information. """ import logging import clic...
deepfigures-open-master
scripts/generatearxiv.py
"""Run tests for deepfigures.""" import logging import click from scripts import execute logger = logging.getLogger(__name__) @click.command( context_settings={ 'help_option_names': ['-h', '--help'] }) def runtests(): """Run tests for deepfigures.""" # init logging logger.setLevel(lo...
deepfigures-open-master
scripts/runtests.py
"""Run unit tests for deepfigures. Run unit tests for deepfigures locally in a docker container, building the required docker images before hand. See ``testunits.py --help`` for more information. """ import logging import click from deepfigures import settings from scripts import build, execute logger = logging....
deepfigures-open-master
scripts/testunits.py
deepfigures-open-master
deepfigures/__init__.py
"""Constants and settings for deepfigures.""" import logging import os logger = logging.getLogger(__name__) # path to the deepfigures project root BASE_DIR = os.path.dirname( os.path.dirname(os.path.realpath(__file__))) # version number for the current release VERSION = '0.0.1' # descriptions of the docker i...
deepfigures-open-master
deepfigures/settings.py
"""Miscellaneous utilities.""" import hashlib def read_chunks(input_path, block_size): """Iterate over ``block_size`` chunks of file at ``input_path``. :param str input_path: the path to the input file to iterate over. :param int block_size: the size of the chunks to return at each iteration. ...
deepfigures-open-master
deepfigures/utils/misc.py
"""Classes for serializing data to json.""" import typing import traitlets JsonData = typing.Union[list, dict, str, int, float] class JsonSerializable(traitlets.HasTraits): def to_dict(self) -> dict: """Recursively convert objects to dicts to allow json serialization.""" return { J...
deepfigures-open-master
deepfigures/utils/config.py
deepfigures-open-master
deepfigures/utils/__init__.py
import errno import io import json import logging import os import pickle import string import random import tarfile import typing import tempfile import hashlib import subprocess from os.path import abspath, dirname, join from gzip import GzipFile import arrow import boto3 ROOT = abspath(dirname(dirname(dirname(__fi...
deepfigures-open-master
deepfigures/utils/file_util.py
"""Utilities for tests with deepfigures.""" import json import logging logger = logging.getLogger(__name__) def test_deepfigures_json( self, expected_json, actual_json): """Run tests comparing two deepfigures JSON files. Compare two json files outputted from deepfigures and verify ...
deepfigures-open-master
deepfigures/utils/test.py
import os import typing import numpy as np from scipy import misc from deepfigures.utils import file_util import logging class FileTooLargeError(Exception): pass def read_tensor(path: str, maxsize: int=None) -> typing.Optional[np.ndarray]: """ Load a saved a tensor, saved either as an image file for stan...
deepfigures-open-master
deepfigures/utils/image_util.py
import typing import traitlets T1 = typing.TypeVar('T1') T2 = typing.TypeVar('T2') T3 = typing.TypeVar('T3') T4 = typing.TypeVar('T4') T = typing.TypeVar('T') K = typing.TypeVar('K') V = typing.TypeVar('V') # Define wrappers for traitlets classes. These simply provide Python type hints # that correspond to actual...
deepfigures-open-master
deepfigures/utils/traits.py
"""Utilities for managing settings.""" from importlib import import_module def import_setting(import_string): """Import and return the object defined by import_string. This function is helpful because by the nature of settings files, they often end up with circular imports, i.e. ``foo`` will import ...
deepfigures-open-master
deepfigures/utils/settings_utils.py
import cffi import os ffibuilder = cffi.FFI() cur_dir = os.path.dirname(os.path.abspath(__file__)) with open(cur_dir + '/stringmatch.cpp') as f: code = f.read() ffibuilder.set_source( '_stringmatch', code, source_extension='.cpp', ) ffibuilder.cdef(''' typedef struct { int start_pos; int end_pos; ...
deepfigures-open-master
deepfigures/utils/stringmatch/stringmatch_builder.py
from _stringmatch import lib def match(key: str, text: str): ''' Find the location of the substring in text with the minimum edit distance (Levenshtein) to key. ''' return lib.match(key, text)
deepfigures-open-master
deepfigures/utils/stringmatch/__init__.py
#!/usr/bin/env python from deepfigures.utils.stringmatch import match def test_match(): m = match('hello', 'hello') assert m.cost == 0 assert m.start_pos == 0 assert m.end_pos == 5 m = match('e', 'hello') assert m.cost == 0 assert m.start_pos == 1 assert m.end_pos == 2 m = match...
deepfigures-open-master
deepfigures/utils/stringmatch/test_stringmatch.py
"""Test miscellaneous utilities.""" import hashlib import os import unittest from deepfigures.utils import misc class TestReadChunks(unittest.TestCase): """Test deepfigures.utils.misc.read_chunks.""" def test_read_chunks(self): """Test read_chunks.""" chunks_path = os.path.join( ...
deepfigures-open-master
deepfigures/utils/tests/test_misc.py
import os import glob import datetime import tempfile import tarfile import logging import multiprocessing import multiprocessing.pool import re import time import functools import collections from typing import List, Optional, Tuple import numpy as np from scipy.ndimage import imread from scipy.misc import imsave fro...
deepfigures-open-master
deepfigures/data_generation/arxiv_pipeline.py
import collections import datetime import glob import logging import math import multiprocessing import os import re import subprocess from typing import List, Tuple, Optional, Dict, Iterable import bs4 from bs4 import BeautifulSoup import cv2 import editdistance import numpy as np import scipy as sp from PIL import I...
deepfigures-open-master
deepfigures/data_generation/pubmed_pipeline.py
"""Functions for detecting and extracting figures.""" import os from typing import List, Tuple, Iterable import cv2 # Need to import OpenCV before tensorflow to avoid import error from scipy.misc import imread, imsave import numpy as np from deepfigures.extraction import ( tensorbox_fourchannel, pdffigures...
deepfigures-open-master
deepfigures/extraction/detection.py
"""The model used to detect figures.""" import copy import os import tempfile from typing import List, Tuple, Iterable import numpy as np import tensorflow as tf from deepfigures import settings from deepfigures.extraction.datamodels import ( BoxClass, Figure, PdfDetectionResult, CaptionOnly) from de...
deepfigures-open-master
deepfigures/extraction/tensorbox_fourchannel.py
import collections import os import subprocess from typing import Callable, Dict, Iterable, List, Tuple, TypeVar from matplotlib import axes import matplotlib.pyplot as plt import numpy as np import scipy as sp from deepfigures.utils import file_util from deepfigures.extraction.renderers import PDFRenderer from deepfi...
deepfigures-open-master
deepfigures/extraction/figure_utils.py
"""Data models for deepfigures. This subpackage contains models for various data dealt with by the deepfigures package. """ from typing import List, Optional, Tuple, Union from matplotlib import patches import numpy as np from deepfigures.utils import traits from deepfigures.utils.config import JsonSerializable fr...
deepfigures-open-master
deepfigures/extraction/datamodels.py
"""Code for extracting figures from PDFs. This subpackage implements the main functionality for deepfigures, running deep models to detect figures as well as other code to render the pages, etc. """
deepfigures-open-master
deepfigures/extraction/__init__.py
"""PDF Rendering engines for deepfigures.""" import glob import json import logging import lxml import os import re import shutil import string import subprocess import typing import bs4 from deepfigures.utils import file_util from deepfigures.extraction import exceptions from deepfigures import settings logger = ...
deepfigures-open-master
deepfigures/extraction/renderers.py
import os import subprocess from typing import List, Optional, Iterable import tempfile from deepfigures.utils import file_util from deepfigures.extraction import datamodels from deepfigures import settings import logging import shlex import contextlib import more_itertools # DPI used by pdffigures for json outputs; ...
deepfigures-open-master
deepfigures/extraction/pdffigures_wrapper.py
"""The figure extraction pipeline for deepfigures. The ``deepfigures.extraction.pipeline`` module defines the figure extraction pipeline for deepfigures, including copying the PDF to a location, rendering a PDF, finding captions for figures, detecting the figures and cropping out the images. """ import hashlib import...
deepfigures-open-master
deepfigures/extraction/pipeline.py
"""Exceptions for deepfigures.""" class LatexException(OSError): """An exception thrown for errors in rendering LaTeX.""" def __init__(self, cmd, code, stdout): self.code = code self.stdout = stdout def __str__(self): return ( 'Return code: %s, stdout: %s' % ...
deepfigures-open-master
deepfigures/extraction/exceptions.py
"""Tests for deepfigures.extraction.renderers""" import contextlib import logging import os import shutil import time import tempfile import unittest import numpy as np from scipy.misc import imread import pytest from deepfigures.extraction import renderers from deepfigures import settings logger = logging.getLogg...
deepfigures-open-master
deepfigures/extraction/tests/test_renderers.py
"""Test deepfigures.extraction.pipeline""" import logging import tempfile import unittest from deepfigures.extraction import pipeline from deepfigures.utils import test logger = logging.getLogger(__name__) class TestFigureExtractionPipeline(unittest.TestCase): """Test ``FigureExtractionPipeline``.""" def...
deepfigures-open-master
deepfigures/extraction/tests/test_pipeline.py
#!/usr/bin/env python import sys from setuptools import setup, Extension, find_packages tf_include = '/'.join(sys.executable.split('/')[:-2]) + \ '/lib/python%d.%d/site-packages/tensorflow/include' % sys.version_info[:2] import os extra_defs = [] if os.uname().sysname == 'Darwin': extra_defs.app...
deepfigures-open-master
vendor/tensorboxresnet/setup.py
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/__init__.py
#!/usr/bin/env python import os import json import tensorflow.contrib.slim as slim import datetime import random import time import argparse import os import threading from scipy import misc import tensorflow as tf import numpy as np from distutils.version import LooseVersion if LooseVersion(tf.__version__) >= LooseVe...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/train.py
from tensorboxresnet.utils.slim_nets import inception_v1 as inception from tensorboxresnet.utils.slim_nets import resnet_v1 as resnet import tensorflow.contrib.slim as slim def model(x, H, reuse, is_training=True): if H['slim_basename'] == 'resnet_v1_101': with slim.arg_scope(resnet.resnet_arg_scope()): ...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/googlenet_load.py
import numpy as np import random import os import cv2 import itertools import tensorflow as tf import multiprocessing import multiprocessing.pool import queue from tensorboxresnet.utils.data_utils import ( annotation_jitter, annotation_to_h5 ) from tensorboxresnet.utils.annolist import AnnotationLib as al from ten...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/train_utils.py
import tensorflow as tf from distutils.version import LooseVersion TENSORFLOW_VERSION = LooseVersion(tf.__version__) def tf_concat(axis, values, **kwargs): if TENSORFLOW_VERSION >= LooseVersion('1.0'): return tf.concat(values, axis, **kwargs) else: return tf.concat(axis, values, **kwargs)
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/__init__.py
class Rect(object): def __init__(self, cx, cy, width, height, confidence): self.cx = cx self.cy = cy self.width = width self.height = height self.confidence = confidence self.true_confidence = confidence def overlaps(self, other): if abs(self.cx - other.c...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/rect.py
import cv2 import numpy as np import copy import tensorboxresnet.utils.annolist.AnnotationLib as al def annotation_to_h5(H, a, cell_width, cell_height, max_len): region_size = H['region_size'] assert H['region_size'] == H['image_height'] / H['grid_height'] assert H['region_size'] == H['image_width'] / H['...
deepfigures-open-master
vendor/tensorboxresnet/tensorboxresnet/utils/data_utils.py