python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
import logging from typing import List import sqlite3 import multiprocessing from multiprocessing import Process from allennlp.common.file_utils import cached_path logger = logging.getLogger(__name__) MULTIPROCESSING_LOGGER = multiprocessing.get_logger() class SqlExecutor: """ This class evaluates SQL queri...
allennlp-semparse-master
allennlp_semparse/parsimonious_languages/executors/sql_executor.py
""" Executors are classes that deterministically transform programs in domain specific languages into denotations. We have one executor defined for each language-domain pair that we handle. """ from allennlp_semparse.parsimonious_languages.executors.sql_executor import SqlExecutor
allennlp-semparse-master
allennlp_semparse/parsimonious_languages/executors/__init__.py
import torch from allennlp.common.util import JsonDict from allennlp.data import Instance from allennlp.predictors.predictor import Predictor @Predictor.register("wikitables-parser") class WikiTablesParserPredictor(Predictor): """ Wrapper for the :class:`~allennlp.models.encoder_decoders.wikitables_seman...
allennlp-semparse-master
allennlp_semparse/predictors/wikitables_parser.py
from allennlp_semparse.predictors.atis_parser import AtisParserPredictor from allennlp_semparse.predictors.nlvr_parser import NlvrParserPredictor from allennlp_semparse.predictors.wikitables_parser import WikiTablesParserPredictor
allennlp-semparse-master
allennlp_semparse/predictors/__init__.py
from allennlp.common.util import JsonDict from allennlp.data import Instance from allennlp.predictors.predictor import Predictor @Predictor.register("atis-parser") class AtisParserPredictor(Predictor): """ Predictor for the :class:`~allennlp_semparse.models.atis.AtisSemanticParser` model. """ def _js...
allennlp-semparse-master
allennlp_semparse/predictors/atis_parser.py
import json from allennlp.common.util import JsonDict from allennlp.data import Instance from allennlp.predictors.predictor import Predictor @Predictor.register("nlvr-parser") class NlvrParserPredictor(Predictor): def _json_to_instance(self, json_dict: JsonDict) -> Instance: sentence = json_dict["senten...
allennlp-semparse-master
allennlp_semparse/predictors/nlvr_parser.py
from allennlp_semparse.models.atis.atis_semantic_parser import AtisSemanticParser from allennlp_semparse.models.nlvr.nlvr_coverage_semantic_parser import NlvrCoverageSemanticParser from allennlp_semparse.models.nlvr.nlvr_direct_semantic_parser import NlvrDirectSemanticParser from allennlp_semparse.models.text2sql_parse...
allennlp-semparse-master
allennlp_semparse/models/__init__.py
import logging from typing import Any, Dict, List, Tuple, Optional from collections import defaultdict import difflib import sqlparse import torch from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import Attention, Seq2SeqEncoder, TextFieldEmbedder, Embedding from all...
allennlp-semparse-master
allennlp_semparse/models/text2sql_parser.py
from typing import Any, Dict, List, Mapping, Sequence, Tuple import torch from allennlp.common.checks import check_dimensions_match from allennlp.common.util import pad_sequence_to_length from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import ( Embedding, Se...
allennlp-semparse-master
allennlp_semparse/models/wikitables/wikitables_semantic_parser.py
allennlp-semparse-master
allennlp_semparse/models/wikitables/__init__.py
from typing import Any, Dict, List import torch from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import ( Attention, FeedForward, Seq2SeqEncoder, Seq2VecEncoder, TextFieldEmbedder, ) from allennlp_semparse.domain_languages import WikiTablesLangua...
allennlp-semparse-master
allennlp_semparse/models/wikitables/wikitables_mml_semantic_parser.py
import logging import os from functools import partial from typing import Dict, List, Tuple, Set, Any import torch from allennlp.data import Vocabulary from allennlp.models.archival import load_archive, Archive from allennlp.models.model import Model from allennlp.modules import ( Attention, FeedForward, ...
allennlp-semparse-master
allennlp_semparse/models/wikitables/wikitables_erm_semantic_parser.py
import logging import os from functools import partial from typing import Any, Callable, Dict, List, Tuple, Union import torch from allennlp.data.vocabulary import Vocabulary from allennlp.models.archival import Archive, load_archive from allennlp.models.model import Model from allennlp.modules import Attention, Seq2S...
allennlp-semparse-master
allennlp_semparse/models/nlvr/nlvr_coverage_semantic_parser.py
allennlp-semparse-master
allennlp_semparse/models/nlvr/__init__.py
import logging from typing import Any, Dict, List import torch from allennlp.data.vocabulary import Vocabulary from allennlp.models.model import Model from allennlp.modules import Attention, Seq2SeqEncoder, TextFieldEmbedder from allennlp.nn import Activation, util from allennlp_semparse.domain_languages import NlvrL...
allennlp-semparse-master
allennlp_semparse/models/nlvr/nlvr_direct_semantic_parser.py
import logging from typing import Dict, List, Tuple import torch from allennlp.data.vocabulary import Vocabulary from allennlp.models.model import Model from allennlp.modules import TextFieldEmbedder, Seq2SeqEncoder, Embedding from allennlp.nn import util from allennlp.training.metrics import Average from allennlp_...
allennlp-semparse-master
allennlp_semparse/models/nlvr/nlvr_semantic_parser.py
allennlp-semparse-master
allennlp_semparse/models/atis/__init__.py
import logging from typing import Any, Dict, Iterable, List, Tuple import difflib import sqlparse import torch from allennlp.common.util import pad_sequence_to_length from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import Attention, Seq2SeqEncoder, TextFieldEmbedder...
allennlp-semparse-master
allennlp_semparse/models/atis/atis_semantic_parser.py
from collections import defaultdict from typing import Dict, List, Optional, Set, Tuple, Union import torch def construct_prefix_tree( targets: Union[torch.Tensor, List[List[List[int]]]], target_mask: Optional[Union[torch.Tensor, List[List[List[int]]]]] = None, ) -> List[Dict[Tuple[int, ...], Set[int]]]: ...
allennlp-semparse-master
allennlp_semparse/state_machines/util.py
""" This module contains code for using state machines in a model to do transition-based decoding. "Transition-based decoding" is where you start in some state, iteratively transition between states, and have some kind of supervision signal that tells you which end states, or which transition sequences, are "good". Ty...
allennlp-semparse-master
allennlp_semparse/state_machines/__init__.py
from collections import defaultdict from typing import Dict, Generic, List, TypeVar, Tuple import torch from allennlp.common.registrable import FromParams from allennlp_semparse.state_machines import util from allennlp_semparse.state_machines.states import State from allennlp_semparse.state_machines.transition_funct...
allennlp-semparse-master
allennlp_semparse/state_machines/beam_search.py
from collections import defaultdict from typing import Dict, List, Optional import torch from allennlp_semparse.state_machines import util from allennlp_semparse.state_machines.states import State from allennlp_semparse.state_machines.transition_functions import TransitionFunction class ConstrainedBeamSearch: "...
allennlp-semparse-master
allennlp_semparse/state_machines/constrained_beam_search.py
from typing import Callable, Dict, List, TypeVar from collections import defaultdict import torch from allennlp.nn import util as nn_util from allennlp_semparse.state_machines.states import State from allennlp_semparse.state_machines.trainers.decoder_trainer import DecoderTrainer from allennlp_semparse.state_machine...
allennlp-semparse-master
allennlp_semparse/state_machines/trainers/expected_risk_minimization.py
from typing import Dict, Generic, TypeVar import torch from allennlp_semparse.state_machines.states import State from allennlp_semparse.state_machines.transition_functions import TransitionFunction SupervisionType = TypeVar("SupervisionType") class DecoderTrainer(Generic[SupervisionType]): """ ``DecoderTra...
allennlp-semparse-master
allennlp_semparse/state_machines/trainers/decoder_trainer.py
from allennlp_semparse.state_machines.trainers.decoder_trainer import DecoderTrainer from allennlp_semparse.state_machines.trainers.expected_risk_minimization import ( ExpectedRiskMinimization, ) from allennlp_semparse.state_machines.trainers.maximum_marginal_likelihood import ( MaximumMarginalLikelihood, )
allennlp-semparse-master
allennlp_semparse/state_machines/trainers/__init__.py
import logging from typing import Dict, List, Tuple import torch from allennlp.nn import util from allennlp_semparse.state_machines.constrained_beam_search import ConstrainedBeamSearch from allennlp_semparse.state_machines.states import State from allennlp_semparse.state_machines.trainers.decoder_trainer import Deco...
allennlp-semparse-master
allennlp_semparse/state_machines/trainers/maximum_marginal_likelihood.py
from collections import defaultdict from typing import Any, Dict, List, Tuple import torch from allennlp.common.checks import check_dimensions_match from allennlp.modules import Attention, FeedForward from allennlp.nn import Activation from allennlp_semparse.state_machines.states import GrammarBasedState from allen...
allennlp-semparse-master
allennlp_semparse/state_machines/transition_functions/linking_transition_function.py
""" This module contains ``TransitionFunctions`` for state-machine-based decoders. The ``TransitionFunction`` parameterizes transitions between ``States``. These ``TransitionFunctions`` are all pytorch `Modules`` that have trainable parameters. The :class:`BasicTransitionFunction` is simply an LSTM decoder with atte...
allennlp-semparse-master
allennlp_semparse/state_machines/transition_functions/__init__.py
from typing import Generic, List, Set, TypeVar import torch from allennlp_semparse.state_machines.states import State StateType = TypeVar("StateType", bound=State) class TransitionFunction(torch.nn.Module, Generic[StateType]): """ A ``TransitionFunction`` is a module that assigns scores to state transition...
allennlp-semparse-master
allennlp_semparse/state_machines/transition_functions/transition_function.py
from collections import defaultdict from typing import Any, Dict, List, Set, Tuple import torch from torch.nn.modules.rnn import LSTM, LSTMCell from torch.nn.modules.linear import Linear from allennlp.modules import Attention from allennlp.nn import util, Activation from allennlp_semparse.state_machines.states impo...
allennlp-semparse-master
allennlp_semparse/state_machines/transition_functions/basic_transition_function.py
from collections import defaultdict from typing import Any, Dict, List, Tuple import torch from torch.nn import Parameter from allennlp.common.checks import check_dimensions_match from allennlp.modules import Attention, FeedForward from allennlp.nn import Activation from allennlp_semparse.state_machines.states impo...
allennlp-semparse-master
allennlp_semparse/state_machines/transition_functions/linking_coverage_transition_function.py
from collections import defaultdict from typing import Any, Dict, List, Tuple import torch from torch.nn import Parameter from allennlp.modules import Attention from allennlp.nn import Activation from allennlp_semparse.state_machines.states import CoverageState, ChecklistStatelet from allennlp_semparse.state_machin...
allennlp-semparse-master
allennlp_semparse/state_machines/transition_functions/coverage_transition_function.py
from typing import Any, List, Sequence import torch from allennlp.nn import util from allennlp_semparse.fields.production_rule_field import ProductionRule from allennlp_semparse.state_machines.states.checklist_statelet import ChecklistStatelet from allennlp_semparse.state_machines.states.grammar_based_state import G...
allennlp-semparse-master
allennlp_semparse/state_machines/states/coverage_state.py
from typing import Callable, Dict, Generic, List, TypeVar from allennlp.nn import util ActionRepresentation = TypeVar("ActionRepresentation") class GrammarStatelet(Generic[ActionRepresentation]): """ A ``GrammarStatelet`` keeps track of the currently valid actions at every step of decoding. This class ...
allennlp-semparse-master
allennlp_semparse/state_machines/states/grammar_statelet.py
""" This module contains the ``State`` abstraction for defining state-machine-based decoders, and some pre-built concrete ``State`` classes for various kinds of decoding (e.g., a ``GrammarBasedState`` for doing grammar-based decoding, where the output is a sequence of production rules from a grammar). The module also ...
allennlp-semparse-master
allennlp_semparse/state_machines/states/__init__.py
from typing import List import torch from allennlp.nn import util class RnnStatelet: """ This class keeps track of all of decoder-RNN-related variables that you need during decoding. This includes things like the current decoder hidden state, the memory cell (for LSTM decoders), the encoder output t...
allennlp-semparse-master
allennlp_semparse/state_machines/states/rnn_statelet.py
from typing import Any, Dict, List, Sequence, Tuple import torch from allennlp_semparse.fields.production_rule_field import ProductionRule from allennlp_semparse.state_machines.states.grammar_statelet import GrammarStatelet from allennlp_semparse.state_machines.states.rnn_statelet import RnnStatelet from allennlp_sem...
allennlp-semparse-master
allennlp_semparse/state_machines/states/grammar_based_state.py
from typing import Callable, Dict, List, Tuple import torch from allennlp.nn import util # We're not actually inhereting from `GrammarStatelet` here because there's very little logic that # would actually be shared. Doing that doesn't solve our type problems, anyway, because List isn't # covariant... class LambdaG...
allennlp-semparse-master
allennlp_semparse/state_machines/states/lambda_grammar_statelet.py
from typing import Dict import torch from allennlp.nn import util class ChecklistStatelet: """ This class keeps track of checklist related variables that are used while training a coverage based semantic parser (or any other kind of transition based constrained decoder). This is intended to be used ...
allennlp-semparse-master
allennlp_semparse/state_machines/states/checklist_statelet.py
from typing import Generic, List, TypeVar import torch # Note that the bound here is `State` itself. This is what lets us have methods that take # lists of a `State` subclass and output structures with the subclass. Really ugly that we # have to do this generic typing _for our own class_, but it makes mypy happy an...
allennlp-semparse-master
allennlp_semparse/state_machines/states/state.py
from typing import List NUMBER_CHARACTERS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "-"} MONTH_NUMBERS = { "january": 1, "jan": 1, "february": 2, "feb": 2, "march": 3, "mar": 3, "april": 4, "apr": 4, "may": 5, "june": 6, "jun": 6, "july": 7, "jul": 7...
allennlp-semparse-master
allennlp_semparse/common/util.py
""" A ``KnowledgeGraph`` is a graphical representation of some structured knowledge source: say a table, figure or an explicit knowledge base. """ from typing import Dict, List, Set class KnowledgeGraph: """ A ``KnowledgeGraph`` represents a collection of entities and their relationships. The ``Knowledg...
allennlp-semparse-master
allennlp_semparse/common/knowledge_graph.py
from allennlp_semparse.common.date import Date from allennlp_semparse.common.errors import ParsingError, ExecutionError from allennlp_semparse.common.util import ( NUMBER_CHARACTERS, MONTH_NUMBERS, ORDER_OF_MAGNITUDE_WORDS, NUMBER_WORDS, )
allennlp-semparse-master
allennlp_semparse/common/__init__.py
from collections import defaultdict from typing import List, Dict, Set import logging from allennlp.common.util import START_SYMBOL from allennlp_semparse.domain_languages.domain_language import DomainLanguage logger = logging.getLogger(__name__) class ActionSpaceWalker: """ ``ActionSpaceWalker`` takes a ...
allennlp-semparse-master
allennlp_semparse/common/action_space_walker.py
class ParsingError(Exception): """ This exception gets raised when there is a parsing error during logical form processing. This might happen because you're not handling the full set of possible logical forms, for instance, and having this error provides a consistent way to catch those errors and log h...
allennlp-semparse-master
allennlp_semparse/common/errors.py
from allennlp_semparse.common.errors import ExecutionError class Date: def __init__(self, year: int, month: int, day: int) -> None: self.year = year self.month = month self.day = day def __eq__(self, other) -> bool: # Note that the logic below renders equality to be non-transi...
allennlp-semparse-master
allennlp_semparse/common/date.py
import re import csv from typing import Union, Dict, List, Tuple, Set from collections import defaultdict from unidecode import unidecode from allennlp.data.tokenizers import Token from allennlp_semparse.common import Date, NUMBER_CHARACTERS, NUMBER_WORDS, ORDER_OF_MAGNITUDE_WORDS from allennlp_semparse.common.knowle...
allennlp-semparse-master
allennlp_semparse/common/wikitables/table_question_context.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is the official evaluator taken from the original dataset. I made minimal changes to make it Python 3 compatible, and conform to our style guidelines. """ # Official Evaluator for WikiTableQuestions Dataset # # There are 3 value types # 1. String (unicode) # 2. N...
allennlp-semparse-master
allennlp_semparse/common/wikitables/wikitables_evaluator.py
from allennlp_semparse.common.wikitables.table_question_context import ( TableQuestionContext, CellValueType, )
allennlp-semparse-master
allennlp_semparse/common/wikitables/__init__.py
""" Utility functions for reading the standardised text2sql datasets presented in `"Improving Text to SQL Evaluation Methodology" <https://arxiv.org/abs/1806.09029>`_ """ from typing import List, Dict, NamedTuple, Iterable, Tuple, Set from collections import defaultdict from allennlp.common import JsonDict class Sql...
allennlp-semparse-master
allennlp_semparse/common/sql/text2sql_utils.py
allennlp-semparse-master
allennlp_semparse/common/sql/__init__.py
from collections import defaultdict from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Type, Union import inspect import logging import sys import traceback import types from nltk import Tree from allennlp.common.util import START_SYMBOL from allennlp_semparse.common import util, ParsingEr...
allennlp-semparse-master
allennlp_semparse/domain_languages/domain_language.py
from collections import defaultdict # We use "Number" in a bunch of places throughout to try to generalize ints and floats. # Unfortunately, mypy doesn't like this very much, so we have to "type: ignore" a bunch of things. # But it makes for a nicer induced grammar, so it's worth it. from numbers import Number from ty...
allennlp-semparse-master
allennlp_semparse/domain_languages/wikitables_language.py
from allennlp_semparse.domain_languages.domain_language import ( DomainLanguage, START_SYMBOL, predicate, predicate_with_side_args, ) from allennlp_semparse.domain_languages.nlvr_language import NlvrLanguage from allennlp_semparse.domain_languages.wikitables_language import WikiTablesLanguage
allennlp-semparse-master
allennlp_semparse/domain_languages/__init__.py
from collections import defaultdict from typing import Callable, Dict, List, NamedTuple, Set from allennlp.common.util import JsonDict from allennlp_semparse.domain_languages.domain_language import DomainLanguage, predicate class Object: """ ``Objects`` are the geometric shapes in the NLVR domain. They have...
allennlp-semparse-master
allennlp_semparse/domain_languages/nlvr_language.py
from typing import Dict, List, Optional, NamedTuple import torch from allennlp.data.fields.field import Field from allennlp.data.vocabulary import Vocabulary class ProductionRule(NamedTuple): rule: str is_global_rule: bool rule_id: Optional[torch.LongTensor] = None nonterminal: Optional[str] = None...
allennlp-semparse-master
allennlp_semparse/fields/production_rule_field.py
from allennlp_semparse.fields.knowledge_graph_field import KnowledgeGraphField from allennlp_semparse.fields.production_rule_field import ProductionRuleField
allennlp-semparse-master
allennlp_semparse/fields/__init__.py
""" ``KnowledgeGraphField`` is a ``Field`` which stores a knowledge graph representation. """ from typing import Callable, Dict, List, Set import editdistance import torch from allennlp.common import util from allennlp.common.checks import ConfigurationError from allennlp.data.fields import Field, ListField, TextFie...
allennlp-semparse-master
allennlp_semparse/fields/knowledge_graph_field.py
allennlp-semparse-master
allennlp_semparse/nltk_languages/__init__.py
allennlp-semparse-master
allennlp_semparse/nltk_languages/contexts/__init__.py
from typing import List, Dict, Set, Tuple from collections import defaultdict import logging import re from nltk import Tree from nltk.sem.logic import ApplicationExpression, Expression, LambdaExpression, BasicType, Type from allennlp_semparse.common import util from allennlp_semparse.common.errors import ParsingErro...
allennlp-semparse-master
allennlp_semparse/nltk_languages/worlds/world.py
allennlp-semparse-master
allennlp_semparse/nltk_languages/worlds/__init__.py
allennlp-semparse-master
allennlp_semparse/nltk_languages/type_declarations/__init__.py
""" This module defines some classes that are generally useful for defining a type system for a new domain. We inherit the type logic in ``nltk.sem.logic`` and add some functionality on top of it here. There are two main improvements: 1) Firstly, we allow defining multiple basic types with their own names (see ``NamedB...
allennlp-semparse-master
allennlp_semparse/nltk_languages/type_declarations/type_declaration.py
import json import os import sys from collections import defaultdict from typing import Dict, Any, Iterable, Tuple import glob import argparse sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) JsonDict = Dict[str, Any] def process_dataset(data: JsonDict, split_type: str) -> Ite...
allennlp-semparse-master
scripts/reformat_text2sql_data.py
import json import os import sys import argparse sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) from allennlp.data.dataset_readers.dataset_utils.text2sql_utils import process_sql_data from allennlp.semparse.contexts.sql_context_utils import SqlVisitor, format_grammar_string fr...
allennlp-semparse-master
scripts/examine_sql_coverage.py
#!/usr/bin/env python3 import argparse from typing import Dict def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("version_type", choices=["stable", "latest", "current"]) parser.add_argument("--minimal", action="store_true", default=False) return parser.parse_args() def post_p...
allennlp-semparse-master
scripts/get_version.py
import json import logging import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", level=logging.DEBUG ) from allennlp.commands.train import datasets_from_params from allennlp.co...
allennlp-semparse-master
scripts/wikitables/preprocess_data.py
#! /usr/bin/env python import sys import os import argparse import gzip import logging import math from multiprocessing import Process sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) ) from allennlp.common.util import JsonDict from allennlp.data.tokenizers...
allennlp-semparse-master
scripts/wikitables/search_for_logical_forms.py
#! /usr/bin/env python import sys import os import gzip import argparse sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) ) from allennlp.data.dataset_readers import WikiTablesDatasetReader from allennlp.data.dataset_readers.semantic_parsing.wikitables impo...
allennlp-semparse-master
scripts/wikitables/generate_data_from_erm_model.py
#! /usr/bin/env python """ NLVR dataset has at most four worlds corresponding to each sentence (with 93% of the sentences appearing with four worlds), identified by the prefixes in identifiers. This script groups the worlds and corresponding labels together to enable training a parser with this information. """ impor...
allennlp-semparse-master
scripts/nlvr/group_nlvr_worlds.py
#! /usr/bin/env python import json import argparse from typing import Tuple, List import os import sys sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) ) from allennlp.common.util import JsonDict from allennlp.semparse.domain_languages import NlvrLanguage fr...
allennlp-semparse-master
scripts/nlvr/get_nlvr_logical_forms.py
#! /usr/bin/env python import sys import os import json import argparse sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) ) from allennlp.data.dataset_readers import NlvrDatasetReader from allennlp.models import NlvrCoverageSemanticParser from allennlp.mode...
allennlp-semparse-master
scripts/nlvr/generate_data_from_erm_model.py
import torch from transformers import BertTokenizer from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import BertForSequenceClassification, AdamW, BertConfig, BertModel, AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained('allenai/scibert_scivocab...
covid-sim-master
demo-env/download_bert_model.py
# -*- coding: utf-8 -*- import requests import time import math import signal def is_ok(url: str) -> bool: """ Returns True if the provided URL responds with a 2XX when fetched via a HTTP GET request. """ try: resp = requests.get(url) except: return False return True if mat...
covid-sim-master
sonar/ping.py
import torch from transformers import BertTokenizer from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import BertForSequenceClassification, AdamW, BertConfig, BertModel, AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained('allenai/scibert_scivocab...
covid-sim-master
api/download_bert_model.py
import argparse import faiss import numpy as np from sklearn.decomposition import PCA import pandas as pd import subprocess import tqdm import pickle def file_len(fname): p = subprocess.Popen(['wc', '-l', fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) res...
covid-sim-master
api/covid-ai2/build_index.py
import torch from transformers import BertTokenizer import csv from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import BertForSequenceClassification, AdamW, BertConfig, BertModel, AutoTokenizer, AutoModel import time import datetime import random import numpy as...
covid-sim-master
api/covid-ai2/run_bert.py
import pandas as pd import tqdm import pickle import random import itertools import torch from transformers import BertTokenizer from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import AutoTokenizer, AutoModel, AutoConfig from transformers import BertForSequenc...
covid-sim-master
api/covid-ai2/alignment_supervised2.py
#import bert import numpy as np from sklearn.metrics.pairwise import cosine_similarity #import matplotlib.pyplot as plt #import spike_queries #from termcolor import colored #import random from collections import Counter, defaultdict #from viterbi_trellis import ViterbiTrellis import streamlit as st from annot import a...
covid-sim-master
api/covid-ai2/alignment.py
import streamlit as st import pandas as pd import numpy as np import pandas as pd import faiss import bert from bert import BertEncoder import pickle import spike_queries import sklearn import time from sklearn.cluster import KMeans as Kmeans @st.cache(allow_output_mutation=True) def load_sents_and_ids(): with st...
covid-sim-master
api/covid-ai2/clustering-demo.py
# FROM THE PACKAGE st-annotated-text https://github.com/tvst/st-annotated-text import streamlit.components.v1 from htbuilder import HtmlElement, div, span, styles from htbuilder.units import px, rem, em def annotation(body, label="", background="#ddd", color="#333", **style): """Build an HtmlElement span object...
covid-sim-master
api/covid-ai2/annot.py
import torch from transformers import BertTokenizer, BertModel, BertForMaskedLM, BertConfig, RobertaModel, RobertaForMaskedLM, \ RobertaTokenizer, RobertaConfig from transformers import AutoTokenizer, AutoModel, AutoConfig #from transformers import AlbertTokenizer, AlbertModel, AlbertConfig #from transformers impor...
covid-sim-master
api/covid-ai2/bert_all_seq.py
import streamlit as st import pandas as pd import numpy as np import pandas as pd import faiss import bert from bert import BertEncoder import pickle import spike_queries import sklearn import random import time import alignment import bert_all_seq #import alignment_supervised2 as alignment_supervised import alignment_...
covid-sim-master
api/covid-ai2/demo2.py
import pandas as pd import tqdm import pickle import random import itertools import torch from transformers import BertTokenizer from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import AutoTokenizer, AutoModel, AutoConfig from transformers import BertForSequen...
covid-sim-master
api/covid-ai2/alignment_model.py
import torch from typing import List, Dict import random import numpy as np class Dataset(torch.utils.data.Dataset): """Simple torch dataset class""" def __init__(self, data: List[Dict], device = "cpu", negative_prob = 0.0): self.data = data self.device = device self.negative_prob = n...
covid-sim-master
api/covid-ai2/dataset.py
import pandas as pd import numpy as np import spike_queries import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description='download covid dataset', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--num-results', dest=...
covid-sim-master
api/covid-ai2/download_data.py
"""Hack to add per-session state to Streamlit. Usage ----- >>> import SessionState >>> >>> session_state = SessionState.get(user_name='', favorite_color='black') >>> session_state.user_name '' >>> session_state.user_name = 'Mary' >>> session_state.favorite_color 'black' Since you set user_name above, next time your scr...
covid-sim-master
api/covid-ai2/SessionState.py
import torch from transformers import BertTokenizer from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import BertForSequenceClassification, AdamW, BertConfig, BertModel, AutoTokenizer, AutoModel import numpy as np from typing import List import tqdm class BertEn...
covid-sim-master
api/covid-ai2/bert.py
import requests import pandas as pd import streamlit as st COVID_URL = "https://spike.staging.apps.allenai.org/api/3/search/query" #"http://35.242.203.108:5000/api/3/search/query" COVID_BASE_URL = "https://spike.staging.apps.allenai.org" #"http://35.242.203.108:5000" PUBMED_URL = "http://34.89.172.235:5000/api/3/sear...
covid-sim-master
api/covid-ai2/spike_queries.py
import streamlit as st import pandas as pd import numpy as np import pandas as pd import faiss import bert from bert import BertEncoder import pickle import spike_queries import sklearn import random import time import alignment import bert_all_seq #import alignment_supervised2 as alignment_supervised import alignment_...
covid-sim-master
api/covid-ai2/demo.py
import pandas as pd import tqdm import pickle import random import itertools import torch from transformers import BertTokenizer from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import AutoTokenizer, AutoModel, AutoConfig from transformers import BertForSequenc...
covid-sim-master
api/covid-ai2/alignment_supervised.py
import os from pathlib import Path ABS_PATH_OF_REARRANGE_TOP_LEVEL_DIR = os.path.abspath(os.path.dirname(Path(__file__))) IOU_THRESHOLD = 0.5 OPENNESS_THRESHOLD = 0.2 POSITION_DIFF_BARRIER = 2.0
ai2thor-rearrangement-main
rearrange_constants.py
"""Inference loop for the AI2-THOR object rearrangement task.""" from allenact.utils.misc_utils import NumpyJSONEncoder from baseline_configs.one_phase.one_phase_rgb_base import ( OnePhaseRGBBaseExperimentConfig, ) from baseline_configs.two_phase.two_phase_rgb_base import ( TwoPhaseRGBBaseExperimentConfig, ) f...
ai2thor-rearrangement-main
example.py
"""Include the Task and TaskSampler to train on a single unshuffle instance.""" import copy import itertools import os import random import traceback from abc import ABC from typing import Any, Tuple, Optional, Dict, Sequence, List, Union, cast, Set import canonicaljson import compress_pickle import gym.spaces import ...
ai2thor-rearrangement-main
rearrange/tasks.py
from typing import Any, Optional, Union import gym.spaces import numpy as np from allenact.base_abstractions.sensor import Sensor try: from allenact.embodiedai.sensors.vision_sensors import RGBSensor except ImportError: raise ImportError("Please update to allenact>=0.4.0.") from allenact.utils.misc_utils imp...
ai2thor-rearrangement-main
rearrange/sensors.py
"""Definitions for a greedy expert for the `Unshuffle` task.""" import copy import random from collections import defaultdict from typing import ( Dict, Tuple, Any, Optional, Union, List, Sequence, TYPE_CHECKING, ) import ai2thor.controller import ai2thor.server import networkx as nx i...
ai2thor-rearrangement-main
rearrange/expert.py
import os from pathlib import Path MAX_HAND_METERS = 0.5 FOV = 90 REQUIRED_THOR_VERSION = "5.0.0" STARTER_DATA_DIR = os.path.join( os.path.abspath(os.path.dirname(Path(__file__))), "../data", "2023", ) THOR_COMMIT_ID = "a9ccb07faf771377c9ff1615bfe7e0ad01968663" STEP_SIZE = 0.25 # fmt: off REARRANGE_SIM_OBJECTS ...
ai2thor-rearrangement-main
rearrange/constants.py
ai2thor-rearrangement-main
rearrange/__init__.py
from typing import ( Optional, Tuple, Sequence, Union, Dict, Any, ) import gym import gym.spaces import numpy as np import torch import torch.nn as nn from torch import Tensor from allenact.algorithms.onpolicy_sync.policy import ( ActorCriticModel, DistributionType, LinearActorCrit...
ai2thor-rearrangement-main
rearrange/baseline_models.py