-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3133c9b
commit d014f56
Showing
48 changed files
with
5,477 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2014. Andrew Chisholm, Ben Hachey, The University of Sydney. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
#!/usr/bin/env python | ||
import argparse | ||
import re | ||
import sys | ||
import textwrap | ||
import logging | ||
|
||
from corpora import prepare | ||
from harness import harness | ||
from features import extract | ||
from learn import train | ||
from model.prepare import wikilinks, wikipedia, kopi, derived, wordvec, dbpedia, yago, freebase | ||
|
||
""" Logging Configuration """ | ||
logFormat = '%(asctime)s|%(levelname)s|%(module)s|%(message)s' | ||
logging.basicConfig(format=logFormat) | ||
log = logging.getLogger() | ||
log.setLevel(logging.DEBUG) | ||
|
||
APPS = [ | ||
prepare.PrepareCorpus, | ||
harness.BatchLink, | ||
harness.ServiceHarness, | ||
extract.ExtractFeature, | ||
train.Train, | ||
|
||
derived.BuildLinkModels, | ||
|
||
wikilinks.BuildWikilinksLexicalisations, | ||
wikilinks.BuildWikilinksEntityContext, | ||
wikilinks.BuildWikilinksMentions, | ||
wikipedia.BuildWikipediaDocrep, | ||
wikipedia.BuildWikipediaRedirects, | ||
wikipedia.BuildWikiHitCounts, | ||
kopi.BuildKopiWikiEntityContext, | ||
|
||
derived.BuildEntitySet, | ||
derived.BuildIdfsForEntityContext, | ||
derived.BuildOccurrenceFromMentions, | ||
derived.BuildOccurrenceFromLinks, | ||
derived.BuildEntityCooccurrenceFromOccurrence, | ||
derived.BuildCandidateModel, | ||
|
||
wordvec.BuildWordVectors, | ||
wordvec.BuildEntityEmbeddings, | ||
|
||
dbpedia.BuildDbpediaLexicalisations, | ||
dbpedia.BuildDbpediaLinks, | ||
dbpedia.BuildDbpediaRedirects, | ||
|
||
yago.BuildYagoMeansNames, | ||
freebase.BuildFreebaseCandidates, | ||
] | ||
|
||
def main(args=sys.argv[1:]): | ||
p = argparse.ArgumentParser(description='Named Entity Linker.') | ||
sp = p.add_subparsers() | ||
for cls in APPS: | ||
name = re.sub('([A-Z])', r'-\1', cls.__name__).lstrip('-').lower() | ||
help = cls.__doc__.split('\n')[0] | ||
desc = textwrap.dedent(cls.__doc__.rstrip()) | ||
csp = sp.add_parser(name, | ||
help=help, | ||
description=desc, | ||
formatter_class=argparse.RawDescriptionHelpFormatter) | ||
cls.add_arguments(csp) | ||
namespace = vars(p.parse_args(args)) | ||
cls = namespace.pop('cls') | ||
try: | ||
obj = cls(**namespace) | ||
except ValueError as e: | ||
p.error(str(e)) | ||
obj() | ||
|
||
if __name__ == '__main__': | ||
main() |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
import re | ||
|
||
from collections import defaultdict | ||
from .prepare import PrepareCorpus | ||
from ..doc import Doc, Candidate, Chain, Mention | ||
from ..model import model | ||
from ..process import tag | ||
from ..process.tokenise import RegexTokeniser | ||
|
||
import logging | ||
log = logging.getLogger() | ||
|
||
DOCSTART_MARKER = '-DOCSTART-' | ||
|
||
@PrepareCorpus.Register | ||
class ConllPrepare(object): | ||
""" Tokenise and tag a conll document """ | ||
def __init__(self, conll_data_path, doc_type): | ||
self.in_path = conll_data_path | ||
self.doc_predicate = { | ||
'all': lambda _: True, | ||
'train': self.is_training_doc, | ||
'dev': self.is_dev_doc, | ||
'test': self.is_test_doc | ||
}[doc_type] | ||
|
||
@staticmethod | ||
def is_training_doc(doc_id): | ||
return 'test' not in doc_id | ||
@staticmethod | ||
def is_test_doc(doc_id): | ||
return 'testb' in doc_id | ||
@staticmethod | ||
def is_dev_doc(doc_id): | ||
return 'testa' in doc_id | ||
|
||
def __call__(self): | ||
""" Prepare documents """ | ||
redirects = model.Redirects() | ||
candidates = model.Candidates() | ||
|
||
log.info('Preparing documents...') | ||
for doc, conll_tags in self.iter_docs(self.in_path, self.doc_predicate): | ||
mentions = [] | ||
for gold_entity, (start, end) in conll_tags: | ||
m = Mention(start, doc.text[start:end]) | ||
m.resolution = redirects.map(gold_entity) | ||
m.surface_form = doc.text[start:end].replace(' ,', ',') | ||
mentions.append(m) | ||
|
||
chains = tag.Tagger.cluster_mentions(mentions) | ||
unique_chains = [] | ||
|
||
for chain in chains: | ||
mbr = defaultdict(list) | ||
for m in chain.mentions: | ||
mbr[m.resolution].append(m) | ||
for r, ms in mbr.iteritems(): | ||
unique_chains.append(Chain(mentions=ms, resolution=Candidate(r))) | ||
|
||
doc.chains = unique_chains | ||
|
||
for chain in doc.chains: | ||
# longest mention string | ||
sf = sorted(chain.mentions, key=lambda m: len(m.surface_form), reverse=True)[0].surface_form | ||
|
||
cs = candidates.search(sf) | ||
if cs: | ||
if chain.resolution.id not in cs: | ||
log.warn('Entity (%s) not in candidate set for (%s) in doc (%s).', chain.resolution.id, sf, doc.id) | ||
#if sf.lower() in chain.resolution.id.lower(): | ||
# import code | ||
# code.interact(local=locals()) | ||
chain.candidates = [Candidate(e) for e in cs] | ||
else: | ||
log.warn('Missing alias (%s): %s' % (doc.id, sf)) | ||
yield doc | ||
|
||
@staticmethod | ||
def iter_docs(path, doc_id_predicate, redirect_model = None, max_docs = None): | ||
""" Read AIDA-CoNLL formatted documents """ | ||
redirect_model = redirect_model or {} | ||
|
||
with open(path, 'rd') as f: | ||
doc_id = None | ||
doc_tokens = None | ||
doc_mentions = None | ||
doc_count = 0 | ||
for line in f: | ||
parts = line.decode('utf-8').split('\t') | ||
if len(parts) > 0: | ||
token = parts[0].strip() | ||
|
||
# if this line contains a mention | ||
if len(parts) >= 4 and parts[1] == 'B': | ||
# filter empty and non-links | ||
if parts[3].strip() != '' and not parts[3].startswith('--'): | ||
entity = parts[3] | ||
entity = redirect_model.get(entity, entity) | ||
begin = sum(len(t)+1 for t in doc_tokens) | ||
|
||
dodgy_tokenisation_bs_offset = 1 if re.search('[A-Za-z],',parts[2]) else 0 | ||
|
||
position = (begin, begin + len(parts[2]) + dodgy_tokenisation_bs_offset) | ||
doc_mentions.append((entity, position)) | ||
|
||
if token.startswith(Conll.DOCSTART_MARKER): | ||
if doc_id != None and doc_id_predicate(doc_id): | ||
doc_count += 1 | ||
yield Doc(' '.join(doc_tokens), doc_id, ConllPrepare.doc_tag_for_id(doc_id)), doc_mentions | ||
|
||
if max_docs != None and doc_count >= max_docs: | ||
doc_id = None | ||
break | ||
|
||
doc_id = token[len(Conll.DOCSTART_MARKER)+2:-1] | ||
doc_tokens = [] | ||
doc_mentions = [] | ||
elif doc_id != None: | ||
doc_tokens.append(token) | ||
|
||
if doc_id != None and doc_id_predicate(doc_id): | ||
yield Doc(' '.join(doc_tokens), doc_id, Conll.doc_tag_for_id(doc_id)), doc_mentions | ||
|
||
@staticmethod | ||
def doc_tag_for_id(doc_id): | ||
if 'testa' in doc_id: | ||
return 'dev' | ||
elif 'testb' in doc_id: | ||
return 'test' | ||
return 'train' | ||
|
||
@classmethod | ||
def add_arguments(cls, p): | ||
p.add_argument('conll_data_path', metavar='CONLL_DATA') | ||
p.add_argument('doc_type', metavar='DOC_TYPE', choices='all,train,dev,test') | ||
p.set_defaults(parsecls=cls) | ||
return p |
Oops, something went wrong.