Commit 5c7d5c33 by guanxing

guan-mermaid-modification

parent 53c41166
import numpy as np
import math
import json
from mermaid import preprocessing as pp
from mermaid import sessions
from mermaid import models
import json
import os
from tqdm import tqdm_notebook
import gensim
from mermaid.embeddings import Embedding
from mermaid import preprocessing as pp
from mermaid.preprocessing import WordIndex
from mermaid import plotting
from mermaid import models
import numpy as np
import mermaid
from mermaid.factory import Factory
from mermaid import sessions
import keras
sentence_set = []
with open('/home/NewPartion/e2e-coref/dev.english.jsonlines','r') as file:
for f in file.readlines():
f = json.loads(f)
sentence_set.append(f['sentences'])
print(len(sentence_set))
antecedent_scores = np.load('/home/NewPartion/e2e-coref/antecedents.npz', encoding='bytes')['arr_0']
mention_starts = np.load('/home/NewPartion/e2e-coref/mention_starts.npz', encoding='bytes')['arr_0']
mention_ends = np.load('/home/NewPartion/e2e-coref/mention_ends.npz', encoding='bytes')['arr_0']
new_sentence_set = []
for item in sentence_set:
new_item = []
for a in item:
for b in a:
new_item.append(b)
new_sentence_set.append(new_item)
print(len(new_sentence_set[0]))
i=0
count=0
for index in range(len(mention_starts[i])):
first_mention = new_sentence_set[i][mention_starts[i][index]:mention_ends[i][index]]
for index2 in range(index + 1, len(mention_ends[i])):
if mention_starts[i][index2] < mention_ends[i][index]:
continue
second_mention = new_sentence_set[i][mention_starts[i][index2]:mention_ends[i][index2]]
split_index = math.ceil((mention_starts[i][index2] - mention_ends[i][index]) / 2)
splitted_sentence1 = ' '.join(new_sentence_set[i][:split_index])
splitted_sentence2 = ' '.join(new_sentence_set[i][split_index:])
count+=1
if count == 10000:
break
print(antecedent_scores[i].shape)
print(len(mention_ends[i]))
print(len(mention_starts[i]))
print(count)
class LoadedWordVecEmbedding(Embedding):
def __init__(self, word_vector_file_path, dim):
super().__init__()
self._w2v = gensim.models.KeyedVectors.load_word2vec_format(word_vector_file_path)
self._word_index = WordIndex({
token: self._w2v.vocab[token].index + 2 for token in self._w2v.vocab
})
self._dim = dim
def make_layer(self):
embedding_matrix = np.zeros((self.vocab_size, self._dim))
for key, index in self._word_index.items():
embedding_matrix[index] = self._w2v[key]
return keras.layers.Embedding(
self.vocab_size,
self._dim,
weights=[embedding_matrix],
trainable=self._trainable
)
@property
def vocab_size(self):
return len(self._word_index) + 2
@property
def word_index(self):
return self._word_index
@property
def index_word(self):
return self._word_index.rev()
def __getitem__(self, item):
return self._w2v[item]
sess = sessions.DQTrainingSession()
sess.setup.embedding('pre-trained')
sess.setup.embedding('loadedwordvecembedding-legruwxj6pwz')
sess.setup.model('convknrm-z3kmin68al3z')
sess.setup.preprocessor('word.30','word.30')
sess.compile()
to_predict_sentence = {'d':splitted_sentence1,'q':splitted_sentence2}
predict_stream = pp.Stream([pp.Entry(**to_predict_sentence)])
sess.build_stream_tokens(predict_stream)
sess.build_stream_sequences(predict_stream)
sess.model.predict(sess.X(predict_stream))
\ No newline at end of file
import operator
import random
import math
import json
import threading
import numpy as np
import tensorflow as tf
import util
import coref_ops
import conll
import metrics
from tensorflow import Session as sess
from coref_model import CorefModel
class CorefMermaidModel(CorefModel):
def matrix_combination(self, matrix1, matrix2, ratio):
"""
Calculate the matrix from matrix1 and matrix2 combination with ratio . matrix1 and matrix2 should have same shape.
:param matrix1:
:param matrix2:
:param ratio: combination ratio of matrix1 : matrix2
:return: combined matrix
"""
assert matrix1.shape == matrix2.shape
ratio=5
print("Using combination ratio: {}".format(ratio))
#combined_matrix = (matrix1 * ratio/(1+ratio) ) + (matrix2 * 1/(1+ratio) )
#combined_matrix = matrix1 + matrix2 * ratio
combined_matrix = matrix2
return np.array(combined_matrix)
def sub_certain_value_from_matrix(self, matrix, value):
print('Subing value {}'.format(value))
new_matrix = matrix
for i, item1 in enumerate(matrix):
for j, item2 in enumerate(item1):
if j > 0:
item2 = item2 - value
new_matrix[i, j] = item2
return np.array(new_matrix)
def evaluate(self, session, sub_value, official_stdout=False):
self.load_eval_data()
def _k_to_tag(k):
if k == -3:
return "oracle"
elif k == -2:
return "actual"
elif k == -1:
return "exact"
elif k == 0:
return "threshold"
else:
return "{}%".format(k)
mention_evaluators = {k: util.RetrievalEvaluator() for k in [-3, -2, -1, 0, 10, 15, 20, 25, 30, 40, 50]}
coref_predictions = {}
coref_evaluator = metrics.CorefEvaluator()
antecedent_scores_set = []
mention_starts_set = []
mention_ends_set = []
#file1 = file('correcting_matrix_loss0.514.npz','rb')
#file1 = file('origin_correcting_matrix.npz','rb')
#file1 = file('corrected_matrix.npz','rb')
#file1 = file('corrected_matrix_halfbyhalf_loss0.514.npz','rb')
#file1 = file('corrected_matrix_halfbyhalf_epoch0180wan.npz','rb')
#file1 = file('no_streched_matrix_epoch0180wan','rb')
#file1 = file('filtered_by_confidence_correcting_matrix_0epoch180wan.npz', 'rb')
#file1 = file('no_strech_filtered_matrix_-0.2_0epoch180wan.npz','rb')
#file1 = file('l2regulazation_matrix_0epoch180wan.npz','rb')
#file1 = file('filtered_by_confidence0.2_epoch261800wan.npz','rb')
#file1 = file('l2regularzation_correcting_matrix_epoch26_1800wan','rb')
#file1 = file('filtered_by_confidence_correcting_matrix_epoch0_313wan_similar_texts.npz', 'rb')
#file1 = file('test_correcting_matrix_performence_no_strech.npz', 'rb')
#file1 = file('test_correcting_matrix_performence_strech.npz','rb')
#file1 = file('correcting_matrix_long_training_data_model.npz','rb')
#file1 = file('correcting_matrix_long_training_data_model_no_-inf.npz', 'rb')
#file1 = file('perfect_correcting_matrix_long_training_data_model.npz', 'rb')
#file1 = file('1500wan_epoch16_model.npz', 'rb')
#file1 = file('340wan_replace_upper_word_without_the.npz', 'rb')
#file1 = file('340wan_replace_upper_word_without_the_filtered_by_0.3.npz','rb')
file1 = file('sub_1_antecedent_scores', 'rb')
correcting_matrix = np.load(file1)['arr_0']
print('using correcting file: ',file1)
for example_num, (tensorized_example, example) in enumerate(self.eval_data):
_, _, _, _, _, _, gold_starts, gold_ends, _ = tensorized_example
feed_dict = {i: t for i, t in zip(self.input_tensors, tensorized_example)}
candidate_starts, candidate_ends, mention_scores, mention_starts, mention_ends, antecedents, antecedent_scores = session.run(
self.predictions, feed_dict=feed_dict)
# # Generated Random Antecedent-scores
# size = antecedent_scores.shape
# antecedent_scores = np.zeros((size[0],size[1]))
# for index in range(1, size[0]):
# for index2 in range(0, min(index,size[1])-1):
# antecedent_scores[index, index2 + 1] = random.randint(-20, 20)
#
# antecedent_scores_set.append(antecedent_scores)
# mention_starts_set.append(mention_starts)
# mention_ends_set.append(mention_ends)
correcting_matrix_one = correcting_matrix[example_num]
wow = antecedent_scores.shape
antecedent_scores = self.matrix_combination(antecedent_scores, correcting_matrix_one, self.config['combination_ratio'])
#antecedent_scores = correcting_matrix_one
antecedent_scores = self.sub_certain_value_from_matrix(antecedent_scores, sub_value)
assert antecedent_scores.shape == wow
self.evaluate_mentions(candidate_starts, candidate_ends, mention_starts, mention_ends, mention_scores,
gold_starts, gold_ends, example, mention_evaluators)
predicted_antecedents = self.get_predicted_antecedents(antecedents, antecedent_scores)
coref_predictions[example["doc_key"]] = self.evaluate_coref(mention_starts, mention_ends,
predicted_antecedents, example["clusters"],
coref_evaluator)
if example_num % 10 == 0:
print ("Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data)))
#file1 = file('antecedents.npz','wb')
#file2 = file('mention_starts.npz','wb')
#file3 = file('mention_ends.npz','wb')
#np.savez(file1, antecedent_scores_set)
#np.savez(file2, mention_starts_set)
#np.savez(file3, mention_ends_set)
summary_dict = {}
for k, evaluator in sorted(mention_evaluators.items(), key=operator.itemgetter(0)):
tags = ["{} @ {}".format(t, _k_to_tag(k)) for t in ("R", "P", "F")]
results_to_print = []
for t, v in zip(tags, evaluator.metrics()):
results_to_print.append("{:<10}: {:.2f}".format(t, v))
summary_dict[t] = v
print (", ".join(results_to_print))
conll_results = conll.evaluate_conll(self.config["conll_eval_path"], coref_predictions, official_stdout)
average_f1 = sum(results["f"] for results in conll_results.values()) / len(conll_results)
summary_dict["Average F1 (conll)"] = average_f1
print "Average F1 (conll): {:.2f}%".format(average_f1)
p, r, f = coref_evaluator.get_prf()
muc_p, muc_r, muc_f = coref_evaluator.get_muc_prf()
bcubed_p, bcubed_r, bcubed_f = coref_evaluator.get_b_cubed_prf()
ceaf_p, ceaf_r, ceaf_f = coref_evaluator.get_ceaf_prf()
summary_dict["Average F1 (py)"] = f[0]
print "Average F1 (py): {:.2f}%".format(f[0] * 100)
summary_dict["Average precision (py)"] = p[0]
print "Average precision (py): {:.2f}%".format(p[0] * 100)
summary_dict["Average recall (py)"] = r[0]
print "Average recall (py): {:.2f}%".format(r[0] * 100)
print "MUC F1 : {:.2f}%".format(f[1][0] * 100)
print "MUC Precision : {:.2f}%".format(p[1][0] * 100)
print "MUC Recall : {:.2f}%".format(r[1][0] * 100)
print "B_CUBED F1 : {:.2f}%".format(f[1][1] * 100)
print "B_CUBED Precision : {:.2f}%".format(p[1][1] * 100)
print "B_CUBED Recall : {:.2f}%".format(r[1][1] * 100)
print "CEAF F1 : {:.2f}%".format(f[1][2] * 100)
print "CEAF Precision : {:.2f}%".format(p[1][2] * 100)
print "CEAF Recall : {:.2f}%".format(r[1][2] * 100)
return util.make_summary(summary_dict), average_f1, p[0]*100, r[0]*100
import os
import sys
import time
import json
import numpy as np
import cgi
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import ssl
import math
import tensorflow as tf
import coref_model as cm
import util
import coref_mermaid_model as cmm
import nltk
nltk.download("punkt")
from nltk.tokenize import sent_tokenize, word_tokenize
from demo import make_predictions, create_example
sentence = 'Phi4 Ceti is a solitary, orange-hued star in the equatorial constellation Cetus.\
It is faintly visible to the naked eye with an apparent visual magnitude of 5.61.\
Based upon an annual parallax shift of 10.20 mas as seen from Earth, it is located roughly 320 light years from the Sun.\
At that distance, the visual magnitude of the star is diminished by an extinction factor of 0.10 due to interstellar dust.[4]'
sentence = 'Large Electric said the Postal Service connected the Large Electric. Large Electric is great'
#sentence = 'In the summer of 2005 , a picture that people have long been looking forward to started emerging with frequency in various major Hong Kong media .With their unique charm , these well - known cartoon images once again caused Hong Kong to be a focus of worldwide attention .'
#sentence = 'Strains of anarchism have often been divided into the categories of social and individualist anarchism or similar dual classifications,\
# Many types and traditions of anarchism exist , not all of which are mutually exclusive .'
example = create_example(sentence)
name = 'best'
print "Running experiment: {}.".format(name)
config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config)
model = cmm.CorefMermaidModel(config)
print('execueted before session')
saver = tf.train.Saver()
log_dir = config["log_dir"]
with tf.Session() as session:
checkpoint_path = os.path.join(log_dir, "model.max.ckpt")
saver.restore(session, checkpoint_path)
tensorized_example = model.tensorize_example(example, is_training=False)
feed_dict = {i: t for i, t in zip(model.input_tensors, tensorized_example)}
print('prepared to run session!')
_, _, _, mention_starts, mention_ends, antecedents, antecedent_scores, head_scores = session.run(
model.predictions + [model.head_scores], feed_dict=feed_dict)
mention_dict = {}
mention_dict.setdefault('mention_starts', mention_starts)
mention_dict.setdefault('mention_ends',mention_ends)
mention_dict.setdefault('antecedent_scores', antecedent_scores)
file1 = file('antecedent.npz','wb')
file2 = file('mention_starts.npy','ab')
file3 = file('mention_ends.npy','ab')
np.savez(file2, mention_starts)
np.savez(file3, mention_ends)
np.savez(file1, antecedent_scores)
wow = np.arange(10)
np.savez(file1, wow)
#print('mention scores is: ', mention_scores)
predicted_antecedents = model.get_predicted_antecedents(antecedents, antecedent_scores)
print('antecedent_scores is: \n', antecedent_scores)
print('antecedent_scores shape is : \n', len(antecedent_scores), len(antecedent_scores[0]))
print('antecedents is: \n', antecedents)
example["predicted_clusters"], _ = model.get_predicted_clusters(mention_starts, mention_ends, predicted_antecedents)
example["top_spans"] = zip((int(i) for i in mention_starts), (int(i) for i in mention_ends))
example["head_scores"] = head_scores.tolist()
print('predicted_antecedentts: ', predicted_antecedents)
print('mention start is {},\n, mention end is {}, \n, antecedent scores is {}, \n, head scores is {}'.format(
mention_starts, mention_ends, antecedent_scores, head_scores))
print(example)
for cluster in example["predicted_clusters"]:
words = util.flatten(example["sentences"])
print(u"Predicted cluster: {}".format([" ".join(words[m[0]:m[1]+1]) for m in cluster]))
...@@ -3,35 +3,43 @@ ...@@ -3,35 +3,43 @@
import os import os
import re import re
import sys import sys
sys.path.append(os.getcwd()) sys.path.append(os.getcwd())
import time
import random
import shutil import shutil
import numpy as np import coref_mermaid_model as cmm
import tensorflow as tf import tensorflow as tf
import coref_model as cm
import util import util
def copy_checkpoint(source, target): def copy_checkpoint(source, target):
for ext in (".index", ".data-00000-of-00001"): for ext in (".index", ".data-00000-of-00001"):
shutil.copyfile(source + ext, target + ext) shutil.copyfile(source + ext, target + ext)
if __name__ == "__main__": if __name__ == "__main__":
util.set_gpus() util.set_gpus()
if len(sys.argv) > 1: if len(sys.argv) > 1:
name = sys.argv[1] name = sys.argv[1]
print "Running experiment: {} (from command-line argument).".format(name) print
"Running experiment: {} (from command-line argument).".format(name)
else: else:
name = os.environ["EXP"] name = os.environ["EXP"]
print "Running experiment: {} (from environment variable).".format(name) print
"Running experiment: {} (from environment variable).".format(name)
config = util.get_config("experiments.conf")[name] config = util.get_config("experiments.conf")[name]
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name)) config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
config["combination_ratio"] = 1
util.print_config(config) util.print_config(config)
model = cm.CorefModel(config) # model = cm.CorefModel(config)
sub_values = [1.25, 1.5,1.75,2.5,3.5,4,4.5]
for sub_value in sub_values:
tf.reset_default_graph()
model = cmm.CorefMermaidModel(config)
saver = tf.train.Saver() saver = tf.train.Saver()
log_dir = config["log_dir"] log_dir = config["log_dir"]
...@@ -41,10 +49,9 @@ if __name__ == "__main__": ...@@ -41,10 +49,9 @@ if __name__ == "__main__":
checkpoint_pattern = re.compile(".*model.ckpt-([0-9]*)\Z") checkpoint_pattern = re.compile(".*model.ckpt-([0-9]*)\Z")
with tf.Session() as session: with tf.Session() as session:
while True:
ckpt = tf.train.get_checkpoint_state(log_dir) ckpt = tf.train.get_checkpoint_state(log_dir)
if ckpt and ckpt.model_checkpoint_path and ckpt.model_checkpoint_path not in evaluated_checkpoints: if ckpt and ckpt.model_checkpoint_path and ckpt.model_checkpoint_path not in evaluated_checkpoints:
print "Evaluating {}".format(ckpt.model_checkpoint_path) print("Evaluating {}".format(ckpt.model_checkpoint_path))
# Move it to a temporary location to avoid being deleted by the training supervisor. # Move it to a temporary location to avoid being deleted by the training supervisor.
tmp_checkpoint_path = os.path.join(log_dir, "model.tmp.ckpt") tmp_checkpoint_path = os.path.join(log_dir, "model.tmp.ckpt")
...@@ -53,15 +60,17 @@ if __name__ == "__main__": ...@@ -53,15 +60,17 @@ if __name__ == "__main__":
global_step = int(checkpoint_pattern.match(ckpt.model_checkpoint_path).group(1)) global_step = int(checkpoint_pattern.match(ckpt.model_checkpoint_path).group(1))
saver.restore(session, ckpt.model_checkpoint_path) saver.restore(session, ckpt.model_checkpoint_path)
eval_summary, f1 = model.evaluate(session) eval_summary, f1, average_precion, average_recall = model.evaluate(session, sub_value)
if f1 > max_f1: if f1 > max_f1:
max_f1 = f1 max_f1 = f1
copy_checkpoint(tmp_checkpoint_path, os.path.join(log_dir, "model.max.ckpt")) copy_checkpoint(tmp_checkpoint_path, os.path.join(log_dir, "model.max.ckpt"))
print "Current max F1: {:.2f}".format(max_f1) print("Current max F1: {:.2f}".format(max_f1))
writer.add_summary(eval_summary, global_step) writer.add_summary(eval_summary, global_step)
print "Evaluation written to {} at step {}".format(log_dir, global_step)
with open('./precision_recall.txt', 'a') as f:
f.write(str(sub_value)+' '+str(average_precion)+' '+str(average_recall)+'\n')
evaluated_checkpoints.add(ckpt.model_checkpoint_path) evaluated_checkpoints.add(ckpt.model_checkpoint_path)
...@@ -106,6 +106,6 @@ nofeatures = ${best} { ...@@ -106,6 +106,6 @@ nofeatures = ${best} {
# For evaluation. Do not use for training (i.e. only for decoder.py, ensembler.py, visualize.py and demo.py). Rename `best0` directory to `final`. # For evaluation. Do not use for training (i.e. only for decoder.py, ensembler.py, visualize.py and demo.py). Rename `best0` directory to `final`.
final = ${best} { final = ${best} {
embeddings = [${glove_300d}, ${turian_50d}] embeddings = [${glove_300d}, ${turian_50d}]
eval_path = test.english.jsonlines eval_path = eval_file
conll_eval_path = test.english.v4_gold_conll conll_eval_path = test.english.v4_gold_conll
} }
...@@ -20,17 +20,36 @@ class CorefEvaluator(object): ...@@ -20,17 +20,36 @@ class CorefEvaluator(object):
e.update(predicted, gold, mention_to_predicted, mention_to_gold) e.update(predicted, gold, mention_to_predicted, mention_to_gold)
def get_f1(self): def get_f1(self):
return sum(e.get_f1() for e in self.evaluators) / len(self.evaluators) return sum(e.get_f1() for e in self.evaluators) / len(self.evaluators), [e.get_f1() for e in self.evaluators]
def get_recall(self): def get_recall(self):
return sum(e.get_recall() for e in self.evaluators) / len(self.evaluators) return sum(e.get_recall() for e in self.evaluators) / len(self.evaluators), [e.get_recall() for e in self.evaluators]
def get_precision(self): def get_precision(self):
return sum(e.get_precision() for e in self.evaluators) / len(self.evaluators) muc_precision = Evaluator(muc).get_precision()
return sum(e.get_precision() for e in self.evaluators) / len(self.evaluators), [e.get_precision() for e in self.evaluators]
def get_prf(self): def get_prf(self):
return self.get_precision(), self.get_recall(), self.get_f1() return self.get_precision(), self.get_recall(), self.get_f1()
def get_muc_prf(self):
muc_precision = Evaluator(muc).get_precision()
muc_recall = Evaluator(muc).get_recall()
muc_f1 = Evaluator(muc).get_f1()
return muc_precision, muc_recall, muc_f1
def get_b_cubed_prf(self):
muc_precision = Evaluator(b_cubed).get_precision()
muc_recall = Evaluator(b_cubed).get_recall()
muc_f1 = Evaluator(b_cubed).get_f1()
return muc_precision, muc_recall, muc_f1
def get_ceaf_prf(self):
muc_precision = Evaluator(ceafe).get_precision()
muc_recall = Evaluator(ceafe).get_recall()
muc_f1 = Evaluator(ceafe).get_f1()
return muc_precision, muc_recall, muc_f1
class Evaluator(object): class Evaluator(object):
def __init__(self, metric, beta=1): def __init__(self, metric, beta=1):
self.p_num = 0 self.p_num = 0
......
...@@ -11,6 +11,7 @@ import collections ...@@ -11,6 +11,7 @@ import collections
import util import util
import conll import conll
class DocumentState(object): class DocumentState(object):
def __init__(self): def __init__(self):
self.doc_key = None self.doc_key = None
...@@ -59,18 +60,20 @@ class DocumentState(object): ...@@ -59,18 +60,20 @@ class DocumentState(object):
assert len(all_mentions) == len(set(all_mentions)) assert len(all_mentions) == len(set(all_mentions))
return { return {
"doc_key": self.doc_key, "doc_key" : self.doc_key,
"sentences": self.sentences, "sentences": self.sentences,
"speakers": self.speakers, "speakers" : self.speakers,
"clusters": merged_clusters "clusters" : merged_clusters
} }
def normalize_word(word): def normalize_word(word):
if word == "/." or word == "/?": if word == "/." or word == "/?":
return word[1:] return word[1:]
else: else:
return word return word
def handle_line(line, document_state): def handle_line(line, document_state):
begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line) begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line)
if begin_document_match: if begin_document_match:
...@@ -116,15 +119,20 @@ def handle_line(line, document_state): ...@@ -116,15 +119,20 @@ def handle_line(line, document_state):
document_state.clusters[cluster_id].append((start, word_index)) document_state.clusters[cluster_id].append((start, word_index))
return None return None
def minimize_partition(name, language, extension): def minimize_partition(name, language, extension):
input_path = "{}.{}.{}".format(name, language, extension) input_path = "{}.{}.{}".format(name, language, extension)
output_path = "{}.{}.jsonlines".format(name, language) output_path = "{}.{}.jsonlines".format(name, language)
count = 0 count = 0
print "Minimizing {}".format(input_path) print(input_path)
print "minimizing {}".format(input_path)
with open(input_path, "r") as input_file: with open(input_path, "r") as input_file:
with open(output_path, "w") as output_file: with open(output_path, "w") as output_file:
document_state = DocumentState() document_state = DocumentState()
for line in input_file.readlines(): for line in input_file.readlines():
begin_document_match = re.match(conll.BEGIN_DOCUMENT_REGEX, line)
if begin_document_match:
document_state = DocumentState()
document = handle_line(line, document_state) document = handle_line(line, document_state)
if document is not None: if document is not None:
output_file.write(json.dumps(document)) output_file.write(json.dumps(document))
...@@ -133,10 +141,38 @@ def minimize_partition(name, language, extension): ...@@ -133,10 +141,38 @@ def minimize_partition(name, language, extension):
document_state = DocumentState() document_state = DocumentState()
print "Wrote {} documents to {}".format(count, output_path) print "Wrote {} documents to {}".format(count, output_path)
def creating_new_data(name, language, extension):
input_path = "{}.{}.{}".format(name, language, extension)
output_path = "{}.{}.{}.new2".format(name, language, extension)
print("recreating {}".format(input_path))
doc_list = []
with open(input_path, "r") as input_file:
with open(output_path, "w") as output_file:
for line in input_file.readlines():
doc_list.append(line)
trouble_doc_index = 0
for item in doc_list:
if item.startswith('#end document'):
while trouble_doc_index+1<len(doc_list) and doc_list[trouble_doc_index+1] == '\n':
del doc_list[trouble_doc_index+1]
trouble_doc_index += 1
for item in doc_list:
output_file.write(item+'\n')
keyword = ['cctv_0003', '10', '14', 'Xing']
if all(item in line for item in keyword):
output_file.write('#end document' + '\n')
def minimize_language(language): def minimize_language(language):
minimize_partition("dev", language, "v4_auto_conll") minimize_partition("dev", language, "v4_auto_conll")
minimize_partition("train", language, "v4_auto_conll") minimize_partition("train", language, "v4_auto_conll")
minimize_partition("test", language, "v4_gold_conll") minimize_partition("test", language, "v4_gold_conll")
if __name__ == "__main__": if __name__ == "__main__":
#creating_new_data("train", "english", "v4_auto_conll")
minimize_language("english") minimize_language("english")
import json
import flask
from flask import render_template, flash, request, redirect, url_for
import coref_model as cm
class WebServer():
app = flask.Flask(__name__)
@app.route('/coref/', methods=['GET', 'POST'])
def coref_input(self):
try:
data = json.loads(flask.request.get_json())
except:
data = flask.request.get_json()
app = flask.Flask(__name__)
'''
@app.route("/", methods=['POST', 'GET'])
def run_web_server():
return render_template("web_server.html", title='Coreference Resolution Service')
'''
@app.route("/coref", methods=['POST', 'GET'])
def run_web_http_request_service():
data = json.loads(flask.request.get_json())
result = coref_resolve(data)
return flask.jsonify({'result': result})
def coref_resolve(data):
pass
def create_example(text):
raw_sentences = sent_tokenize(text)
sentences = [word_tokenize(s) for s in raw_sentences]
speakers = [["" for _ in sentence] for sentence in sentences]
return {
"doc_key": "nw",
"clusters": [],
"sentences": sentences,
"speakers": speakers,
}
class CorefRequestHandler(BaseHTTPRequestHandler):
model = None
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={"REQUEST_METHOD":"POST",
"CONTENT_TYPE":self.headers["Content-Type"]
})
if "text" in form:
text = form["text"].value.decode("utf-8")
if len(text) <= 10000:
print(u"Document text: {}".format(text))
example = make_predictions(text, self.model)
print_predictions(example)
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(example))
return
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
app.run(host='localhost', port=5700, debug=True, threaded=True)
CorefRequestHandler.model = cm.CorefModel('pre-trained')
import requests
import json
import flask
sentence = 'Hey! Thanks for the ans, but i think i wasnt clear enough about what i need to do.\
I having for example, one computer running the servers script, and another computer runnig client script.\
The client need to send a true var for if he is alive and this need to be an http request, \
so i dont really have a url, just an ip address'
#r = requests.post('localhost:5702/post', data=sentence)
#print(r.text)
app = flask.Flask(__name__)
@app.route('/test/', methods=['GET', 'POST'])
def index():
data = json.loads(flask.request.get_json())
print(data['data'])
print(data)
data = data+' processed!'
return flask.jsonify(data)
app.run('localhost', 8888)
resp = requests.post('localhost:8888', data='this is a test')
#!/bin/bash #!/bin/bash
# Download pretrained embeddings. # Download pretrained embeddings.
curl -O https://lil.cs.washington.edu/coref/turian.50d.txt #curl -O https://lil.cs.washington.edu/coref/turian.50d.txt
curl -O https://nlp.stanford.edu/data/glove.840B.300d.zip #curl -O https://nlp.stanford.edu/data/glove.840B.300d.zip
unzip glove.840B.300d.zip #unzip glove.840B.300d.zip
rm glove.840B.300d.zip #rm glove.840B.300d.zip
# Build custom kernels. # Build custom kernels.
TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())') TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())')
# Linux (pip) # Linux (pip)
#g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0
# Linux (build from source) # Linux (build from source)
g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC #g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC
# Mac # Mac
#g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 -undefined dynamic_lookup #g++ -std=c++11 -shared coref_kernels.cc -o coref_kernels.so -I $TF_INC -fPIC -D_GLIBCXX_USE_CXX11_ABI=0 -undefined dynamic_lookup
...@@ -3,6 +3,6 @@ ...@@ -3,6 +3,6 @@
curl -O https://lil.cs.washington.edu/coref/char_vocab.english.txt curl -O https://lil.cs.washington.edu/coref/char_vocab.english.txt
curl -O https://lil.cs.washington.edu/coref/final.tgz curl -O https://lil.cs.washington.edu/coref/final.tgz
mkdir -p logs #mkdir -p logs
tar -xzvf final.tgz -C logs tar -xzvf final.tgz -C logs
rm final.tgz rm final.tgz
...@@ -7,18 +7,19 @@ dlx() { ...@@ -7,18 +7,19 @@ dlx() {
} }
conll_url=http://conll.cemantix.org/2012/download conll_url=http://conll.cemantix.org/2012/download
dlx $conll_url conll-2012-train.v4.tar.gz #dlx $conll_url conll-2012-train.v4.tar.gz
dlx $conll_url conll-2012-development.v4.tar.gz #dlx $conll_url conll-2012-development.v4.tar.gz
dlx $conll_url/test conll-2012-test-key.tar.gz #dlx $conll_url/test conll-2012-test-key.tar.gz
dlx $conll_url/test conll-2012-test-official.v9.tar.gz #dlx $conll_url/test conll-2012-test-official.v9.tar.gz
dlx $conll_url conll-2012-scripts.v3.tar.gz #dlx $conll_url conll-2012-scripts.v3.tar.gz
dlx http://conll.cemantix.org/download reference-coreference-scorers.v8.01.tar.gz #dlx http://conll.cemantix.org/download reference-coreference-scorers.v8.01.tar.gz
mv reference-coreference-scorers conll-2012/scorer #mv reference-coreference-scorers conll-2012/scorer
ontonotes_path=/projects/WebWare6/ontonotes-release-5.0 #ontonotes_path=/home/NewPartion/conll-formatted-ontonotes-5.0
bash conll-2012/v3/scripts/skeleton2conll.sh -D $ontonotes_path/data/files/data conll-2012 ontonotes_path=/home/NewPartion/ontonotes-release-5.0
#bash conll-2012/v3/scripts/skeleton2conll.sh -D $ontonotes_path/data/files/data conll-2012
function compile_partition() { function compile_partition() {
rm -f $2.$5.$3$4 rm -f $2.$5.$3$4
...@@ -31,7 +32,7 @@ function compile_language() { ...@@ -31,7 +32,7 @@ function compile_language() {
compile_partition test test v4 _gold_conll $1 compile_partition test test v4 _gold_conll $1
} }
compile_language english #compile_language english
python minimize.py python minimize.py
python get_char_vocab.py python get_char_vocab.py
......
...@@ -23,10 +23,11 @@ if __name__ == "__main__": ...@@ -23,10 +23,11 @@ if __name__ == "__main__":
config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name)) config["log_dir"] = util.mkdirs(os.path.join(config["log_root"], name))
util.print_config(config) util.print_config(config)
if "GPU" in os.environ: #if "GPU" in os.environ:
util.set_gpus(int(os.environ["GPU"])) #util.set_gpus(int(os.environ["GPU"]))
else: #else:
util.set_gpus() #util.set_gpus()
util.set_gpus(0)
model = cm.CorefModel(config) model = cm.CorefModel(config)
saver = tf.train.Saver() saver = tf.train.Saver()
......
<!DOCTYPE html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h1>Flaskr</h1>
<div class=metanav>
<form>
</form>
</div>
{% for message in get_flashed_messages() %}
<div class=flash>{{ message }}</div>
{% endfor %}
{% block body %}{% endblock %}
</div>
...@@ -49,6 +49,7 @@ def load_embedding_dict(embedding_path, embedding_size, embedding_format): ...@@ -49,6 +49,7 @@ def load_embedding_dict(embedding_path, embedding_size, embedding_format):
if skip_first and i == 0: if skip_first and i == 0:
continue continue
splits = line.split() splits = line.split()
assert len(splits) == embedding_size + 1 assert len(splits) == embedding_size + 1
word = splits[0] word = splits[0]
embedding = np.array([float(s) for s in splits[1:]]) embedding = np.array([float(s) for s in splits[1:]])
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment