Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
andychisholm committed Mar 11, 2015
1 parent 3133c9b commit d014f56
Show file tree
Hide file tree
Showing 48 changed files with 5,477 additions and 0 deletions.
132 changes: 132 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
data/
output/

##########
# PYTHON #
##########
# Initialized from github
# https://github.com/github/gitignore/blob/master/Python.gitignore

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
ve

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject

# Rope
.ropeproject

# Django stuff:
*.log
*.pot

# Sphinx documentation
docs/_build/

# Package
MANIFEST

#########
# EMACS #
#########
# Initliazed from github
# https://raw2.github.com/github/gitignore/master/Global/Emacs.gitignore

# -*- mode: gitignore; -*-
*~
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*

# Org-mode
.org-id-locations
*_archive

# flymake-mode
*_flymake.*

# eshell files
/eshell/history
/eshell/lastdir

# elpa packages
/elpa/

#######
# VIM #
#######
# Initialized from github
# https://raw2.github.com/github/gitignore/master/Global/vim.gitignore

[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~

#######
# OSX #
#######
# Initialized from github
# https://raw2.github.com/github/gitignore/master/Global/OSX.gitignore

.DS_Store
.AppleDouble
.LSOverride

# Icon must ends with two \r.
Icon

# Thumbnails
._*

# Files that might appear on external disk
.Spotlight-V100
.Trashes

# NFS
.nfs*

# IDE
*.sublime-*
Expand Down
9 changes: 9 additions & 0 deletions LICENCE
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 added nel/__init__.py
Empty file.
76 changes: 76 additions & 0 deletions nel/__main__.py
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 added nel/corpora/__init__.py
Empty file.
138 changes: 138 additions & 0 deletions nel/corpora/conll.py
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
Loading

0 comments on commit d014f56

Please sign in to comment.