python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
""" Copyright (c) Facebook, Inc. and its affiliates. """ class StopCondition: def __init__(self, agent): self.agent = agent def check(self) -> bool: raise NotImplementedError("Implemented by subclass") class NeverStopCondition(StopCondition): def __init__(self, agent): super()._...
craftassist-master
python/base_agent/stop_condition.py
from condition import NeverCondition DEFAULT_THROTTLING_TICK = 16 THROTTLING_TICK_UPPER_LIMIT = 64 THROTTLING_TICK_LOWER_LIMIT = 4 # put a counter and a max_count so can't get stuck? class Task(object): def __init__(self): self.memid = None self.interrupted = False self.finished = False ...
craftassist-master
python/base_agent/task.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ from collections import defaultdict, namedtuple import binascii import hashlib import logging import numpy as np import time import traceback from word2number.w2n import word_to_num from typing import Tuple, List, TypeVar import uuid ##FFS FIXME!!!! arrange uti...
craftassist-master
python/base_agent/base_util.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ MAP_YES = [ "yes", "true", "i agree", "tru dat", "yep", "ya", "yah", "yeah", "definitely", "def", "sure", "ok", "o k", ] MAP_NO = ["no", "nope", "false", "definitely not"] MAP_MAYBE = ["maybe", "unknown", "i ...
craftassist-master
python/base_agent/string_lists.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ """This file has functions to preprocess the chat from user before querying the dialogue manager""" import string from spacy.lang.en import English from typing import List tokenizer = English().Defaults.create_tokenizer() def word_tokenize(st) -> str: ch...
craftassist-master
python/base_agent/preprocess.py
from typing import List SELFID = "0" * 32 def maybe_and(sql, a): if a: return sql + " AND " else: return sql def maybe_or(sql, a): if a: return sql + " OR " else: return sql # TODO counts def get_property_value(agent_memory, mem, prop): # order of precedence: ...
craftassist-master
python/base_agent/memory_filters.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ """This file defines the DialogueStack class and helper functions to support it.""" import logging from base_agent.base_util import NextDialogueStep, ErrorWithResponse class DialogueStack(object): """This class represents a dialogue stack that holds Dialo...
craftassist-master
python/base_agent/dialogue_stack.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ ###TODO put dances back import gzip import logging import numpy as np import os import pickle import sqlite3 import uuid from itertools import zip_longest from typing import cast, Optional, List, Tuple, Sequence, Union from base_agent.base_util import XYZ, Time ...
craftassist-master
python/base_agent/sql_memory.py
import os import sys sys.path.append(os.path.dirname(__file__))
craftassist-master
python/base_agent/__init__.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ class BaseAgent: def __init__(self, opts, name=None): self.opts = opts self.name = name or "bot" self.count = 0 self.init_memory() self.init_controller() self.init_perception() def start(self): wh...
craftassist-master
python/base_agent/core.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import numpy as np from memory_filters import ReferenceObjectSearcher, get_property_value from base_util import TICKS_PER_SEC, TICKS_PER_MINUTE, TICKS_PER_HOUR # attribute has function signature list(mems) --> list(float) class Attribute: def __init__(self,...
craftassist-master
python/base_agent/condition.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import copy import json import logging import os import re import spacy from typing import Tuple, Dict, Optional from glob import glob import sentry_sdk import preprocess from base_agent.memory_nodes import ProgramNode from base_agent.dialogue_manager import D...
craftassist-master
python/base_agent/nsp_dialogue_manager.py
import uuid import ast from typing import Optional, List, Dict, cast from base_util import XYZ, POINT_AT_TARGET, to_player_struct from task import Task class MemoryNode: TABLE_COLUMNS = ["uuid"] PROPERTIES_BLACKLIST = ["agent_memory", "forgetme"] NODE_TYPE: Optional[str] = None @classmethod def n...
craftassist-master
python/base_agent/memory_nodes.py
""" Copyright (c) Facebook, Inc. and its affiliates. The current control flow of dialogue is: 1. A chat comes in and Dialogue manager reads it or the bot triggers a dialogue because of memory/perception/task state 2. The dialogue manager puts a DialogueObject on the DialogueStack. 3. The DialogueStack calls .st...
craftassist-master
python/base_agent/dialogue_manager.py
import sys import logging import random import re import time from core import BaseAgent from base_util import hash_user random.seed(0) # a BaseAgent with: # 1: a controller that is (mostly) a dialogue manager, and the dialogue manager # is powered by a neural semantic parser. # 2: has a turnable head, can poi...
craftassist-master
python/base_agent/loco_mc_agent.py
import copy # move location inside reference_object for Fill and Destroy actions def fix_fill_and_destroy_location(action_dict): action_name = action_dict["action_type"] if action_name in ["FILL", "DESTROY"]: if "location" in action_dict: if "reference_object" not in action_dict: ...
craftassist-master
python/base_agent/post_process_logical_form.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # TODO rewrite functions in intepreter and helpers as classes # finer granularity of (code) objects # interpreter is an input to interpret ref object, maybe clean that up? class ReferenceObjectInterpreter: def __init__(self, interpret_reference_object): ...
craftassist-master
python/base_agent/dialogue_objects/reference_object_helpers.py
from condition import ( LinearExtentValue, LinearExtentAttribute, FixedValue, convert_comparison_value, ) from base_util import ErrorWithResponse, number_from_span from base_agent.memory_nodes import ReferenceObjectNode from dialogue_object_utils import tags_from_dict def interpret_span_value(interpre...
craftassist-master
python/base_agent/dialogue_objects/attribute_helper.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import logging import numpy as np import random from string_lists import MAP_YES, MAP_NO from base_util import pos_to_np from enum import Enum class DialogueObject(object): def __init__(self, agent, memory, dialogue_stack, featurizer=None, max_steps=50): ...
craftassist-master
python/base_agent/dialogue_objects/dialogue_object.py
import os import sys sys.path.append(os.path.dirname(__file__)) from dialogue_object import ( AwaitResponse, BotCapabilities, BotGreet, BotLocationStatus, BotStackStatus, DialogueObject, GetReward, ConfirmTask, ConfirmReferenceObject, Say, ) from dialogue_object_utils import (...
craftassist-master
python/base_agent/dialogue_objects/__init__.py
from typing import Optional from base_util import ErrorWithResponse from condition import ( Condition, NeverCondition, AndCondition, OrCondition, Comparator, MemoryColumnValue, FixedValue, TimeCondition, TableColumn, ) from attribute_helper import interpret_linear_extent, interpret_s...
craftassist-master
python/base_agent/dialogue_objects/condition_helper.py
from copy import deepcopy SPEAKERLOOK = {"reference_object": {"special_reference": "SPEAKER_LOOK"}} SPEAKERPOS = {"reference_object": {"special_reference": "SPEAKER"}} AGENTPOS = {"reference_object": {"special_reference": "AGENT"}} def strip_prefix(s, pre): if s.startswith(pre): return s[len(pre) :] ...
craftassist-master
python/base_agent/dialogue_objects/dialogue_object_utils.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file has the definitions and properties of the components that go into the action tree. Following is a list of component nodes: - Schematic, that can be of type: - CategoryObject - Shape, that can be of type: - BlockShape - RectanguloidS...
craftassist-master
python/base_agent/ttad/generation_dialogues/tree_components.py
import numpy as np import random from generate_dialogue import generate_actions import sys import os import uuid import json TTAD_GEN_DIR = os.path.dirname(os.path.realpath(__file__)) CRAFTASSIST_DIR = os.path.join(TTAD_GEN_DIR, "../../") sys.path.append(CRAFTASSIST_DIR) from generate_data import * import re from dial...
craftassist-master
python/base_agent/ttad/generation_dialogues/build_scene.py
import os import sys sys.path.append(os.path.dirname(__file__))
craftassist-master
python/base_agent/ttad/generation_dialogues/__init__.py
if __name__ == "__main__": import argparse import pickle import os from tqdm import tqdm from build_scene import * from block_data import COLOR_BID_MAP BLOCK_DATA = pickle.load( open("/private/home/aszlam/minecraft_specs/block_images/block_data", "rb") ) allowed_blocktypes ...
craftassist-master
python/base_agent/ttad/generation_dialogues/build_scene_flat_script.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file generates action trees and language based on options from command line. """ import json from generate_data import * class Action(ActionNode): """options for Actions""" CHOICES = [ Move, Build, Destroy, Noop, ...
craftassist-master
python/base_agent/ttad/generation_dialogues/generate_dialogue.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains utility functions used for the generation pipeline. """ import random import re ABERRANT_PLURAL_MAP = { "appendix": "appendices", "barracks": "barracks", "cactus": "cacti", "child": "children", "criterion": "criteria", "d...
craftassist-master
python/base_agent/ttad/generation_dialogues/generate_utils.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with Undo command. """ import random from .template_object import * ##################### ### UNDO TEMPLATES ## ##################### class ActionBuild(TemplateObject): """This template object repesents that the...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/undo_commands.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with BlockObjects. """ import random from generate_utils import * from tree_components import * from .template_object import * from .location import * ############################# ### BLOCKOBJECT TEMPLATES ### #####...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/block_object.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with the Mob tree component. """ import random from generate_utils import * from tree_components import * from .template_object import * ##################### ### MOB TEMPLATES ### ##################### def set_mob_...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/mob.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated specifically with the Answer action. """ import random from generate_utils import * from tree_components import * from .template_object import * ######################## ### ANSWER TEMPLATES ### #####################...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/answer.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with repeats and stop conditions. """ import random from generate_utils import * from tree_components import * from .template_object import * ################################ ### STOP CONDITION TEMPLATES ### #########...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/repeat_and_condition.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with Fill action. """ import random from generate_utils import * from tree_components import * from .template_object import * from .dig import * ##################### ## FILL TEMPLATES ### ##################### clas...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/fill.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains common template objects used across different templates. """ import random from generate_utils import * from tree_components import * from .template_object import * ####################### ## DANCE TEMPLATES ## ####################### """ Fly ...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/dance.py
# fmt: off from .action_names import * from .answer import * from .block_object import * from .common import * from .dig import * from .fill import * from .location import * from .mob import * from .schematics import * from .special_shape_commands import * from .repeat_and_condition import * from .string_output import ...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/__init__.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains generic template objects associated with Dilogue. """ from generate_utils import * from tree_components import * from .template_object import * class Human(TemplateObject): def generate_description(self, arg_index=0, index=0, templ_index=0):...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/dialogue_generic.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects that generate only strings. """ import random from generate_utils import * from tree_components import * from .template_object import * ################################ ### GENERIC TEXT TEMPLATES ### ##########################...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/string_output.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with the Location tree component. """ import random from generate_utils import * from tree_components import * from .template_object import * ########################## ### LOCATION TEMPLATES ### #####################...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/location.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with Dig action. """ import random from generate_utils import * from tree_components import * from .template_object import * ##################### ### DIG TEMPLATES ### ##################### dig_shapes = ["hole", "cav...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/dig.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated directly with Action names. """ import random from generate_utils import * from tree_components import * from .template_object import * class Dance(TemplateObject): """This template object repesents a single word...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/action_names.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains common template objects used across different templates. """ import random from generate_utils import * from tree_components import * from .template_object import * ####################### ## COMMON TEMPLATES ## ####################### """Thi...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/common.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with special shape commands like : Wall, Stack, Place etc """ import random from generate_utils import * from tree_components import * from .template_object import * ################################## ## SPECIAL COMMA...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/special_shape_commands.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with Schematics. """ import random from generate_utils import * from tree_components import * from .template_object import * ########################### ### SCHEMATIC TEMPLATES ### ########################### class ...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/schematics.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with human-bot dialogues. """ from generate_utils import * from tree_components import * from .template_object import * action_reference_object_map = { "BUILD": "building", "DESTROY": "destroying", "SPAWN":...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/dialogue_human_bot.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file defines the TemplateObject class and other data structures used across template objects. """ from generate_utils import * from tree_components import * SCHEMATIC_TYPES = [ RectanguloidShape, HollowRectanguloidShape, CubeShape, HollowCubeS...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/template_object.py
""" Copyright (c) Facebook, Inc. and its affiliates. This file contains template objects associated with the Tag action """ import random from generate_utils import * from tree_components import * from .template_object import * ##################### ### TAG TEMPLATES ### ##################### tag_map = {"colour": C...
craftassist-master
python/base_agent/ttad/generation_dialogues/template_objects/tag.py
""" Copyright (c) Facebook, Inc. and its affiliates. Actions: - GetMemory (filters, answer_type) - PutMemory (filters, info_type) Top-Level = { "dialogue_type": { `action_type`: {Action} } } e.g. { "get_memory" : { "filters" : { "type" : "action", "temporal"...
craftassist-master
python/base_agent/ttad/generation_dialogues/generate_data/human_bot_dialogue.py
# fmt: off from .action_node import * from .human_human_dialogue import * from .human_bot_dialogue import *
craftassist-master
python/base_agent/ttad/generation_dialogues/generate_data/__init__.py
""" Copyright (c) Facebook, Inc. and its affiliates. Actions: - Move (optional<Location>, optional<StopCondition>, optional<Repeat>) - Build (optional<Schematic>, optional<Location>, optional<Repeat>) - Destroy (optional<BlockObject>) - Dig (optional<has_length>, optional<has_width>, optional<has_depth>, option...
craftassist-master
python/base_agent/ttad/generation_dialogues/generate_data/human_human_dialogue.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import random from generate_utils import * from templates.templates import get_template class ActionNode: """This class is an Action Node that represents the "Action" in the action_tree. A node can have a list of child nodes (ARG_TYPES) or a list of ...
craftassist-master
python/base_agent/ttad/generation_dialogues/generate_data/action_node.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Undo templates are written for an action name and represents the intent for the action: Undo. This action represents reverting something ...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/undo_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Stop templates are written for an action name and represents the intent for the action: Stop. This action represents stopping an action ...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/stop_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Spawn templates are written for a MobName and represent the intent for the action: Spawn. Examples: [Human, Spawn, MobName] - spawn a pi...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/spawn_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Fill templates are written for a Location and represents the intent for the action: Fill. This action intends to fill a hole or a negativ...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/fill_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Resume templates are written for an action name and represents the intent for the action: Resume. This action represents resuming a given...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/resume_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Destroy templates are written only for BlockObject and represent the intent for the action: Destroy. This action destroys a physical bloc...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/destroy_templates.py
import os import sys sys.path.append(os.path.dirname(__file__))
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/__init__.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ """This file picks a template for a given action, at random. The templates use template_objects as their children to help construct a sentence and the dictionary. TemplateObject is defined in template_objects.py Each template captures how to phrase the intent....
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off """ Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Build templates are written for Schematics and may have a Location, and represent the intent for the action: Build. This action builds a ...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/build_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Move templates are written with respect to a Location and represent the intent for the action: Move. This action specifies the location t...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/move_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off """ Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py PutMemory templates are written for filters and have an answer_type They represent the action of writing to the memory using the filters....
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/put_memory_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off """ Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py GetMemory templates are written for filters and have an answer_type They represent the action of fetching from the memory using the filte...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/get_memory_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Dig templates are written for a Location and represent the intent for the action: Dig. This action intends to dig a hole at a certain loc...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/dig_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Copy templates are written for a BlockObject and may have a Location, and represent the intent for the action: Copy. This action builds a...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/copy_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Freebuild templates are written for : - either a BlockObject or a Location. and represents the intent for the action: Freebuild. This ac...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/freebuild_templates.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # fmt: off ''' Every template contains an ordered list of TemplateObjects. TemplateObject is defined in template_objects.py Dance templates are written with an optional location and stop condition. Examples: [Human, DanceSingle] - do a dance - dance [Human, D...
craftassist-master
python/base_agent/ttad/generation_dialogues/templates/dance_templates.py
import torch from dataset import * from huggingface_modeling_gpt2 import * from transformer import * def compute_accuracy(outputs, y, tokenizer): """Compute model accuracy given predictions and targets. Used in validation. """ # Do not include [CLS] token target_tokens = y[:, 1:] predicted_tokens ...
craftassist-master
python/base_agent/ttad/back_translation/train_utils.py
from transformers import GPT2Tokenizer, BertTokenizer from dataset import * # from transformers.modeling_gpt2 import * from huggingface_modeling_gpt2 import * from transformer import * import argparse import numpy as np import torch.nn.functional as F # make sure GPT2 appends EOS in begin and end def build_inputs_wit...
craftassist-master
python/base_agent/ttad/back_translation/generate.py
from transformers import AutoConfig, AutoTokenizer from dataset import * from modeling_gpt2 import * from transformer import * from torch.utils.data import DataLoader import argparse from os.path import join as pjoin import torch from train_utils import * def main(): parser = argparse.ArgumentParser() parser....
craftassist-master
python/base_agent/ttad/back_translation/train_custom_gpt2.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License...
craftassist-master
python/base_agent/ttad/back_translation/modeling_gpt2.py
craftassist-master
python/base_agent/ttad/back_translation/__init__.py
import torch import argparse import random class Tree2TextDataset(torch.utils.data.Dataset): """Dataset class extending pytorch Dataset definition. """ def __init__(self, prog, chat): """Initialize paired data, tokenizer, dictionaries. """ assert len(prog) == len(chat) sel...
craftassist-master
python/base_agent/ttad/back_translation/dataset.py
from transformers.modeling_bert import BertModel import torch.nn as nn class TransformerEncoder(nn.Module): """Transformer Encoder class. """ def __init__(self, config, tokenizer): super(TransformerEncoder, self).__init__() # Initializes transformer architecture with BERT structure ...
craftassist-master
python/base_agent/ttad/back_translation/transformer.py
from transformers import AutoConfig, GPT2Tokenizer, BertTokenizer from os.path import isdir from dataset import * from transformer import * from torch.utils.data import DataLoader from datetime import date import argparse import os import sys from time import time from huggingface_modeling_gpt2 import * import logging ...
craftassist-master
python/base_agent/ttad/back_translation/train.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License...
craftassist-master
python/base_agent/ttad/back_translation/huggingface_modeling_gpt2.py
import argparse import ast import copy import json import os import random from recombine_data_utils import * from typing import * def create_train_valid_split(chunk_index: int, k: int, data_dir: str, output_dir: str): """Create partitions for k fold Cross Validation Given a chunk index for the valid set, cr...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/recombine_data.py
# flake8: noqa import json import math import pickle import torch from transformers import AutoModel, AutoTokenizer, BertConfig from utils_caip import * from utils_parsing import * from train_model import * from pprint import pprint model = "python/craftassist/models/semantic_parser/ttad_bert_updated/caip_test_mode...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/test_model_script.py
import argparse import functools import json import logging import logging.handlers import os import pickle from time import time from os.path import isfile from os.path import join as pjoin from tqdm import tqdm from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from transformers import AutoMo...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/train_model.py
import os import sys sys.path.append(os.path.dirname(__file__))
craftassist-master
python/base_agent/ttad/ttad_transformer_model/__init__.py
import ast import copy from enum import Enum from typing import * class TurkToolProcessor: def __init__(self, train_annotated_phrases: List[str], node_types: List[str]): self.train_annotated_phrases = train_annotated_phrases self.node_types = node_types def filter_tool1_lines(self, tool1_line...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/recombine_data_utils.py
import json import numpy as np import random import re import ast from os.path import isfile, isdir from os.path import join as pjoin import torch from torch.utils.data import Dataset ######### # Node typing: checking the type of a specific sub-tree (dict value) ######### def is_span(val): try: a, (b, c)...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/utils_caip.py
import argparse import os import random import math from typing import * def partition_dataset(k: int, data_path: str, output_dir: str): """ Split dataset into k partitions. """ # Read in annotated dataset full_dataset = open(data_path + "annotated_data_text_spans.txt").readlines() print("Leng...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/gen_cross_valid_chunks.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam, Adagrad from transformers.modeling_bert import BertModel, BertOnlyMLMHead from utils_caip import * # -------------------------- # Transformer-based decoder module for sequence ans span prediction, computes the loss # --...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/utils_parsing.py
import json import math import pickle import torch from transformers import AutoModel, AutoTokenizer, BertConfig from utils_parsing import * from utils_caip import * from train_model import * class TTADBertModel(object): def __init__(self, model_dir, data_dir, model_name="caip_test_model"): model_name ...
craftassist-master
python/base_agent/ttad/ttad_transformer_model/query_model.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import os from emnlp_model import * from typing import Sequence, Dict THIS_DIR = os.path.dirname(__file__) class ActionDictBuilder(object): def __init__( self, model_path=THIS_DIR + "/../../models/semantic_parser/ttad/ttad.pth", ...
craftassist-master
python/base_agent/ttad/ttad_model/ttad_model_wrapper.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import argparse import logging import logging.handlers import os import pickle TTAD_MODEL_DIR = os.path.dirname(os.path.realpath(__file__)) TTAD_DATA_DIR = os.path.join(TTAD_MODEL_DIR, "../data/ttad_model/") from time import time import torch.optim as optim ...
craftassist-master
python/base_agent/ttad/ttad_model/train_model.py
import os import sys sys.path.append(os.path.dirname(__file__))
craftassist-master
python/base_agent/ttad/ttad_model/__init__.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import json import sys import spacy from spacy.lang.en import English tokenizer = English().Defaults.create_tokenizer() def tokenize(st): return " ".join([str(x) for x in tokenizer(st)]) data_in_text_file = sys.argv[1] data_out_json_file = sys.argv[2] ...
craftassist-master
python/base_agent/ttad/ttad_model/make_dataset.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import json import sys from pprint import pprint from emnlp_model import * data_file = sys.argv[1] grammar_file = sys.argv[2] print("loading", data_file) data_dct = json.load(open(data_file)) print("loaded data") a_tree = ActionTree() for spl, spl_dct in dat...
craftassist-master
python/base_agent/ttad/ttad_model/make_action_grammar.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import copy import math import torch import torch.nn as nn ##### Utility modules # Produce n identical layers. def clones(module, n): return nn.ModuleList([copy.deepcopy(module) for _ in range(n)]) def xavier_init(module, mul=1.0): for p in module.pa...
craftassist-master
python/base_agent/ttad/ttad_model/emnlp_model/model_utils.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import math import torch import torch.nn as nn class HighwayNetwork(nn.Module): def __init__(self, in_dim, out_dim): super(HighwayNetwork, self).__init__() self.gate_proj = nn.Linear(in_dim, out_dim) self.lin_proj = nn.Linear(in_di...
craftassist-master
python/base_agent/ttad/ttad_model/emnlp_model/sentence_encoder.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ # define the grammar from collections import OrderedDict ##### ## define node types class SpanSingleLeaf: def __init__(self, node_id, name): self.node_type = "span-single" self.name = name self.node_id = node_id def is_span(val):...
craftassist-master
python/base_agent/ttad/ttad_model/emnlp_model/action_tree.py
from .action_tree import * from .data import * from .sentence_encoder import * from .prediction_model import * from .my_optim import *
craftassist-master
python/base_agent/ttad/ttad_model/emnlp_model/__init__.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import json import math import pickle import torch import torch.nn as nn from .action_tree import * from .model_utils import * from .my_optim import * from .sentence_encoder import * ##### Define tree modules # Each node module computes a contextual node rep...
craftassist-master
python/base_agent/ttad/ttad_model/emnlp_model/prediction_model.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import json import numpy as np from random import choice, random, randint, seed, shuffle import torch from .action_tree import * def tree_to_action_type(tr): a_type = tr["action_type"] if a_type == "Build" and "reference_object" in tr: retur...
craftassist-master
python/base_agent/ttad/ttad_model/emnlp_model/data.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import logging from collections import OrderedDict from time import time import torch import torch.nn as nn import copy from torch.nn.modules.loss import _Loss from .data import * class LabelSmoothingBCE(nn.Module): def __init__(self, smoothing=0.0): ...
craftassist-master
python/base_agent/ttad/ttad_model/emnlp_model/my_optim.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ from copy import deepcopy # from pprint import pprint import csv import json from spacy.lang.en import English tokenizer = English().Defaults.create_tokenizer() def word_tokenize(st): return [(x.text, x.idx) for x in tokenizer(st)] rephrases = [] for ...
craftassist-master
python/base_agent/ttad/ttad_model/processing_scripts/read_rephrased.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import json from pprint import pprint from random import choice from models import * def read_generations(f_name): res = [] f = open(f_name) for line in f: if line[0] == "{": try: a_tree = ActionTree() ...
craftassist-master
python/base_agent/ttad/ttad_model/processing_scripts/read_data.py
""" Copyright (c) Facebook, Inc. and its affiliates. """ import json import matplotlib.pyplot import numpy as np from scipy.ndimage import imread import visdom import pickle # vis = visdom.Visdom(server ='http://localhost') home_dir = '/private/home/aszlam' f = open(home_dir + '/minecraft_specs/block_images/css_chu...
craftassist-master
minecraft_specs/block_images/read_images.py