python_code stringlengths 0 187k | repo_name stringlengths 8 46 | file_path stringlengths 6 135 |
|---|---|---|
import re
import io
from typing import Tuple
from pathlib import Path
import boto3
import botocore
s3_client = boto3.client("s3")
class RetryableDownloadFailure(Exception):
def __init__(self, err: Exception):
self.err = err
def try_get_content(url: str) -> bytes:
bucket,key = _parse_url(url)
try... | cc_net-main | cc_net/s3util.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import func_argparse
import cc_net.mine
def main():
func_argparse.parse_and_call(cc_net.mine.get_main_parser())
if __name__ == "__... | cc_net-main | cc_net/__main__.py |
from datetime import datetime, timezone
from typing import Optional
from cc_net import jsonql
class Ai2Formatter(jsonql.Transformer):
def __init__(self):
super().__init__()
def do(self, doc: dict) -> Optional[dict]:
d = {}
d["source"] = "common-crawl"
d["id"] = doc["url"]
... | cc_net-main | cc_net/ai2_format.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import collections
from pathlib import Path
from typing import Dict, Optional
import fasttext # type: igno... | cc_net-main | cc_net/split_by_lang.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import contextlib
import functools
import gzip
import logging
import multiprocessing
from collections import defaultdict
from pathlib import... | cc_net-main | cc_net/tools/dl_cc_100.py |
cc_net-main | cc_net/tools/__init__.py | |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
This code is used to train a fastText classifier to label document with DMOZ categories.
The data, distributed under the cc-by 3.0 lice... | cc_net-main | cc_net/tools/make_dmoz_corpus.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
"""
Tools to search sentences in CC similar to sentences in another corpus.
"""
import functools
import logging
import math
import subproce... | cc_net-main | cc_net/tools/expand_corpus.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import json
from pathlib import Path
from typing import Iterable, Sequence
from cc_net import dedup, jsonql
from cc_net.dedup import str_ha... | cc_net-main | tests/test_dedup.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import cc_net.text_normalizer as txt
def test_unicode_punct():
weird = ",。、„”“«»1」「《》´∶:?!();–—.~’…━〈〉【】%"
replaced = ',.,""""""""... | cc_net-main | tests/test_normalizer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from pathlib import Path
from cc_net import process_wet_file
def test_parsing():
sample = Path(__file__).parent / "data" / "sample.wa... | cc_net-main | tests/test_parse_wet_file.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
import pytest
from cc_net.flat_hash_set import HASH_TYPE, FlatHashSet, NaiveHashSet
def as_dict(flat_hash_set) -> dict... | cc_net-main | tests/test_flat_hash_set.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import pytest
def _request_is_disabled(self, *args, **kwargs):
raise Exception(
f"Your code tried to call 'request' with: {arg... | cc_net-main | tests/conftest.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
#
| cc_net-main | tests/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import time
from cc_net import jsonql, regroup
def check_regroup(tmp_path, regroup_fn, check_blocks_boundaries=False):
n_shards = 4
... | cc_net-main | tests/test_regroup.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import io
from pathlib import Path
from typing import Sequence
import numpy as np
import pytest
from cc_net import jsonql
def bar(small_... | cc_net-main | tests/test_jsonql.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import json
from pathlib import Path
import pytest
import cc_net
import cc_net.minify as minify
from cc_net import jsonql, process_wet_fil... | cc_net-main | tests/test_minify.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import inspect
import pickle
from pathlib import Path
import pytest
from cc_net import dedup, jsonql, perplexity, split_by_lang, tokenizer... | cc_net-main | tests/test_transformer.py |
"""setup.py file for packaging amti."""
from setuptools import setup
with open('readme.md', 'r') as readme_file:
readme = readme_file.read()
setup(
name='amti',
version='0.0.2',
description="A Mechanical Turk Interface",
long_description=readme,
url='http://github.com/allenai/amti',
aut... | amti-master | setup.py |
"""A Mechanical Turk Interface"""
from amti import (
actions,
clis,
settings,
utils)
| amti-master | amti/__init__.py |
"""Constants and default settings that ship with ``amti``"""
# AWS client configuration
MAX_ATTEMPTS = 25
"""The number of retries to perform for requests."""
# Mechanical Turk environment values
ENVS = {
'live': {
'region_name': 'us-east-1',
'endpoint_url': 'https://mturk-requester.us-east-1.... | amti-master | amti/settings.py |
"""
amti.utils.logging
==================
Utilities for logging.
"""
import logging
import subprocess
import sys
LOG_FORMAT = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
def config_logging(log_level, file_path=None):
"""Configure python logging.
Parameters
----------
log_level : int
t... | amti-master | amti/utils/log.py |
"""Utilities for processing XML."""
from xml.dom import minidom
def get_node_text(node):
"""Return the text from a node that has only text as content.
Calling this function on a node with multiple children or a non-text
node child raises a ``ValueError``.
Parameters
----------
node : xml.do... | amti-master | amti/utils/xml.py |
"""Utilities for ``amti``"""
from amti.utils import (
log,
mturk,
serialization,
validation,
workers,
xml)
| amti-master | amti/utils/__init__.py |
""" Module for worker management functions """
import boto3
import click
import csv
from typing import List
def chunk_list(items: List, n: int = 100) -> List:
"""Create generatator that yields n sized chunks of input list."""
for i in range(0, len(items), n):
yield items[i:i + n]
def read_workerids_fr... | amti-master | amti/utils/workers.py |
"""Utilities for interacting with MTurk."""
import logging
import os
import boto3
from botocore.config import Config
from typing import Optional
from amti import settings
logger = logging.getLogger(__name__)
def get_mturk_client(env):
"""Return a client for Mechanical Turk.
Return a client for Mechanica... | amti-master | amti/utils/mturk.py |
"""Utilities for data serialization"""
import datetime
def json_helper(obj):
"""Help ``json.dump`` serialize objects to JSON.
This function is written to be passed into ``json.dump`` as the
argument to the ``default`` parameter, so that we can serialize a
broader range of data types. Currently, this... | amti-master | amti/utils/serialization.py |
"""Utilities for validating data"""
def validate_dict(dict_like, schema):
"""Return a list of validation error strings.
Compare ``dict_like`` to ``schema``, returning a list of strings
describing all the validation errors. In particular, validate that
``dict_like`` contains every key specified in ``s... | amti-master | amti/utils/validation.py |
"""Functions for saving HITs to storage"""
import json
import logging
import os
import shutil
import tempfile
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
def save_batch(
client,
batch_dir):
"""Save results from turkers working a batch to disk.
In ... | amti-master | amti/actions/save.py |
"""Functions for deleting HITs from MTurk"""
import json
import logging
import os
from amti import settings
logger = logging.getLogger(__name__)
def delete_hit(
client,
hit_id):
"""Delete the HIT corresponding to ``hit_id`` from MTurk.
Parameters
----------
client : MTurk.Client
... | amti-master | amti/actions/delete.py |
"""Functions for creating HITs"""
import json
import logging
import os
import shutil
import tempfile
import uuid
import jinja2
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
def initialize_batch_directory(
definition_dir,
data_path,
save_dir):
""... | amti-master | amti/actions/create.py |
"""Actions for managing HITs and their results"""
from amti.actions import (
create,
delete,
expire,
extraction,
review,
save,
status)
| amti-master | amti/actions/__init__.py |
"""Functions for reviewing HITs"""
import json
import logging
import os
from xml.dom import minidom
import click
from amti import settings
logger = logging.getLogger(__name__)
def review_hit(
client,
hit_id,
approve_all):
"""Manually review the results from a HIT.
Parameters
... | amti-master | amti/actions/review.py |
"""Functions for expiring all (unanswered) HITs"""
import json
import logging
import os
import datetime
from amti import settings
logger = logging.getLogger(__name__)
def expire_batch(
client,
batch_dir):
"""Expire all the (unanswered) HITs in the batch.
Parameters
----------
clie... | amti-master | amti/actions/expire.py |
"""Functions for retrieving status information about HITs"""
import collections
import json
import logging
import os
from amti import settings
logger = logging.getLogger(__name__)
def status_batch(
client,
batch_dir):
"""Retrieve the status for a batch of HITs.
Parameters
----------
... | amti-master | amti/actions/status.py |
"""A function for extracting batch data into a tabular format."""
import csv
import html
import json
import logging
import os
from xml.dom import minidom
import click
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
TABULAR_SUPPORTED_FILE_FORMATS = [
'csv',
'json',
... | amti-master | amti/actions/extraction/tabular.py |
"""A function for extracting data from a batch as XML"""
import json
import logging
import os
import shutil
import tempfile
from xml.dom import minidom
from amti import settings
logger = logging.getLogger(__name__)
def xml(
batch_dir,
output_dir):
"""Extract the XML from assignments in a batch... | amti-master | amti/actions/extraction/xml.py |
"""Actions for extracting data from batches"""
from amti.actions.extraction import (
tabular,
xml)
| amti-master | amti/actions/extraction/__init__.py |
"""Command line interfaces for saving HITs"""
import logging
import click
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
'batch_dir',
... | amti-master | amti/clis/save.py |
"""Command line interfaces for deleting HITs"""
import logging
import click
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
'batch_dir',
... | amti-master | amti/clis/delete.py |
"""CLI for running a web server to preview HITs"""
import html
from http import server
import json
import logging
import os
import re
from xml.etree import ElementTree
import click
import jinja2
from amti import settings
logger = logging.getLogger(__name__)
class Server(server.HTTPServer):
"""A server for pr... | amti-master | amti/clis/preview.py |
"""Command line interfaces for creating HITs"""
import logging
import click
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
'definition_d... | amti-master | amti/clis/create.py |
"""Command line interfaces for unblocking Workers"""
import logging
import click
import csv
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
... | amti-master | amti/clis/unblock.py |
"""CLIs for managing HITs and their results"""
from amti.clis import (
associate,
block,
create,
delete,
disassociate,
expire,
extract,
extraction,
notify,
review,
save,
status,
unblock,
preview
)
| amti-master | amti/clis/__init__.py |
"""Command line interfaces for blocking Workers"""
import logging
import click
import csv
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
... | amti-master | amti/clis/notify.py |
"""Command line interfaces for reviewing HITs"""
import logging
import boto3
import click
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
... | amti-master | amti/clis/review.py |
"""Command line interfaces for expiring the HITs"""
import logging
import click
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
'batch_di... | amti-master | amti/clis/expire.py |
"""Command line interfaces for blocking Workers"""
import logging
import click
import csv
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
... | amti-master | amti/clis/block.py |
"""Command line interface for disassociating quals with Workers"""
import logging
import click
import csv
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@cli... | amti-master | amti/clis/disassociate.py |
"""Command line interfaces for extracting data from a batch"""
import logging
import click
# import extraction directly to avoid a circular import
from amti.clis import extraction
logger = logging.getLogger(__name__)
@click.group(
context_settings={
'help_option_names': ['--help', '-h']
})
def ex... | amti-master | amti/clis/extract.py |
"""Command line interface for associating quals with Workers"""
import logging
import click
import csv
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.... | amti-master | amti/clis/associate.py |
"""Command line interfaces for viewing the statuses of HITs"""
import logging
import click
from amti import actions
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
... | amti-master | amti/clis/status.py |
"""Command line interface for extracting tabular data from a batch"""
import logging
import click
from amti import actions
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
'batch_dir',
type=click.Path(exists=... | amti-master | amti/clis/extraction/tabular.py |
"""Command line interface for extracting XML from a batch"""
import logging
import click
from amti import actions
logger = logging.getLogger(__name__)
@click.command(
context_settings={
'help_option_names': ['--help', '-h']
})
@click.argument(
'batch_dir',
type=click.Path(exists=True, fil... | amti-master | amti/clis/extraction/xml.py |
"""Commands for extracting batch data into various formats"""
from amti.clis.extraction import (
tabular,
xml)
| amti-master | amti/clis/extraction/__init__.py |
from setuptools import setup
version = {}
with open('beakerstore/version.py') as v:
exec(v.read(), version)
# TODO: license
setup(
name='beakerstore',
version=version['__version__'],
description='Local store for Beaker datasets and files.',
packages=['beakerstore'],
url='https://github.com/al... | beakerstore-master | setup.py |
import atexit
import logging
import os
import platform
import requests
import tempfile
import time
from enum import Enum
from pathlib import Path
from random import shuffle
from typing import Optional, Set, Union
from . import __version__
# Logging stuff
logging.basicConfig(format='%(levelname)s %(name)s %(asctime)... | beakerstore-master | beakerstore/beakerstore.py |
__version__ = '1.1.0'
| beakerstore-master | beakerstore/version.py |
from .version import __version__
from .beakerstore import BeakerOptions, path
| beakerstore-master | beakerstore/__init__.py |
import pytest
# Most of this a variation of the example for skipping slow tests in pytest documentation
# here: https://docs.pytest.org/en/latest/example/simple.html
def pytest_addoption(parser):
parser.addoption(
'--run-internal', action='store_true', default=False, help='run internal Beaker tests'
... | beakerstore-master | beakerstore/tests/conftest.py |
beakerstore-master | beakerstore/tests/__init__.py | |
import pytest
import os
import unittest
from pathlib import Path
from .. import path, BeakerOptions
from ..beakerstore import Cache, DatasetNotFoundError
@pytest.fixture(scope='class')
def cache_test_dir(request, tmpdir_factory):
request.cls.tmpdir = tmpdir_factory.mktemp('cache_test_dir')
class TestBeakersto... | beakerstore-master | beakerstore/tests/beakerstore_test.py |
"""
a script to train a word2vec model
"""
import argparse
from aristomini.common.wordtwovec import tokenizer
from gensim.models import Word2Vec
parser = argparse.ArgumentParser(description="train a word2vec model")
parser.add_argument("sentences_filename",
metavar="sentences-filename",
... | aristo-mini-master | scripts/train_word2vec_model.py |
#!/usr/bin/env python
from __future__ import print_function
import json
import re
import sys
try:
# for Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# fallback to Python 2
from urllib2 import urlopen
# Reads text input on STDIN, splits it into sentences, gathers groups of
# sen... | aristo-mini-master | scripts/insert_text_to_elasticsearch.py |
aristo-mini-master | aristomini/__init__.py | |
"""
This is a skeleton for building your own solver.
You just need to find and fix the two TODOs in this file.
"""
from typing import List
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
# TODO: replace with your solv... | aristo-mini-master | aristomini/solvers/mysolver.py |
"""text search solver"""
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Q, Search
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
class TextSearchSolver(SolverBase):
"""
runs a query ag... | aristo-mini-master | aristomini/solvers/textsearch.py |
"""random guesser solver"""
import random
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
class RandomGuesserSolver(SolverBase):
"""guesses at random"""
def solver_info(self) -> str:
return "random_gu... | aristo-mini-master | aristomini/solvers/randomguesser.py |
aristo-mini-master | aristomini/solvers/__init__.py | |
"""pmi solver"""
from collections import defaultdict
import math
from typing import NamedTuple, Iterable, List, Dict, Set, Sequence
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
from aristomini.common.nlp import all_... | aristo-mini-master | aristomini/solvers/acme.py |
"""pmi solver"""
from collections import defaultdict
import math
from typing import NamedTuple, Iterable, List, Dict
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
from aristomini.common.nlp import all_grams, distinct... | aristo-mini-master | aristomini/solvers/pmi.py |
"""word vector similarity solver"""
import argparse
from aristomini.common.solver import SolverBase
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, ChoiceConfidence
from aristomini.common.wordtwovec import WordTwoVec
parser = argparse.ArgumentParser()
parser.add_argument("model_fil... | aristo-mini-master | aristomini/solvers/wordvectorsimilarity.py |
"""
a wrapper class for the gensim Word2Vec model that has extra features we need, as well as some
helper functions for tokenizing and stemming and things like that.
"""
from functools import lru_cache
import math
from typing import Iterable, List
from gensim.parsing.preprocessing import STOPWORDS
from gensim.parsing... | aristo-mini-master | aristomini/common/wordtwovec.py |
"""base class that solvers should inherit from"""
from typing import Any
from aristomini.common.models import MultipleChoiceQuestion, MultipleChoiceAnswer, \
SolverAnswer, parse_question
# built in `json` module doesn't serialize namedtuples correctly; `simplejson` does.
import simplejson as json
from flask impo... | aristo-mini-master | aristomini/common/solver.py |
"""
typed models for our data. these are the exact analogues of the case classes used by the scala
code (which is why the fields have unfortunate, non-pythonic names)
"""
from typing import NamedTuple, List, Any, Dict, NamedTuple
import simplejson as json
# pylint: disable=invalid-name
class Choice(NamedTuple):
... | aristo-mini-master | aristomini/common/models.py |
aristo-mini-master | aristomini/common/__init__.py | |
"""
nlp utils
"""
from functools import lru_cache
import re
from typing import List, NamedTuple, Iterable
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
STOPWORDS = set(stopwords.words('english'))
_stemmer = SnowballStemmer('english')
def get_... | aristo-mini-master | aristomini/common/nlp.py |
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers import LSTM
from keras.optimizers import RMSprop
from keras.utils.data_utils import get_file
import numpy as np
import random
import string
import sys
import re
path = 'aristo-mini-corpus-v1.txt'
good_chars = set(string.pr... | aristo-mini-master | aristomini/common/rnn.py |
"""server to run the evaluation ui"""
from typing import Any
import argparse
import pathlib
import os
import json
import jinja2
# built in `json` module doesn't serialize namedtuples correctly; `simplejson` does.
import simplejson as json
from flask import Flask, request, send_from_directory
import requests
from ari... | aristo-mini-master | aristomini/evalui/evalui.py |
import argparse
from glob import glob
import shutil, sys, os, random, re
def randomize(keys, to_dir, source_txt_files, source_ann_files):
random.seed()
prefixes = [i for i in range(len(keys))]
random.shuffle(prefixes)
for key, prefix in zip(keys, prefixes):
shutil.copy2(source_txt_files[key],
... | brat-master | copy_randomize_files.py |
#!/usr/bin/env python
# Minimal standalone brat server based on SimpleHTTPRequestHandler.
# Run as apache, e.g. as
#
# APACHE_USER=`./apache-user.sh`
# sudo -u $APACHE_USER python standalone.py
import sys
import os
from posixpath import normpath
from urllib import unquote
from cgi import FieldStorage
from ... | brat-master | standalone.py |
# -*- Mode: Python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# This configuration file specifies the global setup of the brat
# server. It is recommended that you use the installation script
# instead of editing this file directly. To do this, run the following
# command in the brat directory:
#
# .... | brat-master | config_template.py |
from setuptools import setup
setup(name='ai2-brat',
version='0.1',
description='brat related utilities',
url='http://github.com/allenai/brat',
packages=['ai2_brat'],
install_requires=[],
zip_safe=False)
| brat-master | setup.py |
#!/usr/bin/env python
'''
Run brat using the built-in Python CGI server for testing purposes.
Author: Pontus Stenetorp <pontus stenetorp se>
Version: 2012-07-01
'''
from BaseHTTPServer import HTTPServer, test as simple_http_server_test
from CGIHTTPServer import CGIHTTPRequestHandler
# Note: It is a terribl... | brat-master | testserver.py |
#!/usr/bin/env python
# Script to convert a CoNLL-flavored BIO-formatted entity-tagged file
# into BioNLP ST-flavored standoff with reference to the original
# text.
import sys
import re
import os
import codecs
try:
import psyco
psyco.full()
except:
pass
# what to do if an error in the tag sequence (e.g... | brat-master | tools/conll2standoff.py |
#!/usr/bin/env python
'''
Make a data back-up into the work directory.
This script is a quick hack until we come up with something better.
Author: Pontus Stenetorp <pontus stenetorp se>
Version: 2011-05-11
'''
from datetime import datetime
from os import mkdir, remove
from os.path import dirname, exists, bas... | brat-master | tools/backup.py |
#!/usr/bin/env python
# -*- Mode: Python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# vim:set ft=python ts=4 sw=4 sts=4 autoindent:
from __future__ import with_statement
'''
Merge BioNLP Shared Task annotation format into a single annotation file.
find data -name '*.a1' -o -name '*.a2' -o -name '*.rel'... | brat-master | tools/merge.py |
#!/usr/bin/env python
# Script to revise the whitespace content of a PMC NXML file for text
# content extraction.
from __future__ import with_statement
import sys
import os
import re
import codecs
# TODO: switch to lxml
try:
import xml.etree.ElementTree as ET
except ImportError:
import cElementTree as ET
... | brat-master | tools/respace.py |
#!/usr/bin/env python
import sys
import re
try:
import cElementTree as ET
except:
import xml.etree.cElementTree as ET
# tags of elements to exclude from standoff output
EXCLUDED_TAGS = [
"PAPER",
"s",
]
EXCLUDED_TAG = { t:True for t in EXCLUDED_TAGS }
# string to use to indicate elided text in output... | brat-master | tools/discsegtostandoff.py |
#!/usr/bin/env python
# Script to convert a CoNLL 2002-flavored BIO-formatted entity-tagged
# file into BioNLP ST-flavored standoff and a reconstruction of the
# original text.
from __future__ import with_statement
import sys
import re
import os
import codecs
INPUT_ENCODING = "Latin-1"
OUTPUT_ENCODING = "UTF-8"
ou... | brat-master | tools/conll02tostandoff.py |
#!/usr/bin/env python
# Script to convert a column-based BIO-formatted entity-tagged file
# into standoff with reference to the original text.
from __future__ import with_statement
import sys
import re
import os
import codecs
class taggedEntity:
def __init__(self, startOff, endOff, eType, idNum, fullText):
... | brat-master | tools/BIOtoStandoff.py |
#!/usr/bin/env python
import sys
import re
import os
options = None
DEFAULT_INPUT = 'entities-anatomy.csv'
# Document ID format in BioContext data
BIOCONTEXT_ID_RE = re.compile(r'^([0-9]+|PMC[0-9]+\.[0-9]+\.[0-9])+$')
def argparser():
import argparse
ap=argparse.ArgumentParser(description='Convert Bio... | brat-master | tools/biocontext2standoff.py |
#!/usr/bin/env python
'''
An example of a tagging service using NER suite.
'''
from argparse import ArgumentParser
from os.path import join as path_join
from os.path import dirname
try:
from json import dumps
except ImportError:
# likely old Python; try to fall back on ujson in brat distrib
from sys imp... | brat-master | tools/nersuitetaggerservice.py |
#!/usr/bin/env python
'''
An example of a tagging service using metamap.
'''
from argparse import ArgumentParser
from os.path import join as path_join
from os.path import dirname
try:
from json import dumps
except ImportError:
# likely old Python; try to fall back on ujson in brat distrib
from sys impor... | brat-master | tools/metamaptaggerservice.py |
#!/usr/bin/env python
# Check that text-bound annotations in .ann file align with the
# corresponding .txt file.
import sys
import re
import codecs
from collections import namedtuple
from os.path import basename
Textbound = namedtuple('Textbound', 'id type start end text')
TEXTBOUND_RE = re.compile(r'^([A-Z]\d+)\t... | brat-master | tools/checkann.py |
#!/usr/bin/env python
# Script to convert MetaMap "fielded" ("-N" argument) output into
# standoff with reference to the original text.
import sys
import re
import os
import codecs
# Regex for the "signature" of a metamap "fielded" output line
FIELDED_OUTPUT_RE = re.compile(r'^\d+\|')
class taggedEntity:
def __... | brat-master | tools/MetaMaptoStandoff.py |
#!/usr/bin/env python
'''
An example of a tagging service.
Author: Pontus Stenetorp <pontus stenetorp se>
Version: 2012-03-05
'''
from argparse import ArgumentParser
from cgi import FieldStorage
try:
from json import dumps
except ImportError:
# likely old Python; try to fall back on ujson in brat ... | brat-master | tools/randomtaggerservice.py |
#!/usr/bin/env python
# Convert CoNLL 2009 format file into brat-flavored standoff and a
# reconstruction of the original text.
from __future__ import with_statement
import sys
import re
import os
import codecs
# maximum number of sentences to include in single output document
# (if None, doesn't split into documen... | brat-master | tools/conll09tostandoff.py |
#!/usr/bin/env python
'''
Dictionary-based NER tagging server using PubDictionaries.
This code is based on that of randomtagger.py
Author: Han-Cheol Cho
(Author of the original script: Pontus Stenetorp)
Version: 2014-04-05
'''
from argparse import ArgumentParser
from cgi import FieldStorage
try:
from json i... | brat-master | tools/pubdic_tagger.py |
#!/usr/bin/env python
'''
Parse an annotation log and extract annotation statistics.
Author: Pontus Stenetorp <pontus stenetorp se>
Version: 2011-11-25
'''
from argparse import ArgumentParser
### Constants
ARGPARSER = ArgumentParser()#XXX:
ARGPARSER.add_argument('ann_log', nargs='+')
###
from collections im... | brat-master | tools/anneval.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.