-
Notifications
You must be signed in to change notification settings - Fork 3
/
mongo.py
176 lines (157 loc) · 6.38 KB
/
mongo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import glob
import os
import re
import numpy as np
from pymongo import MongoClient
from pymongo import UpdateOne
from sklearn.metrics import pairwise_distances
from ranking import *
def dump_sentences():
client = MongoClient('localhost', 27017)
db = client['nlprokz']
hinglish = db.hinglish
count = 0
# for root, dirs, files in os.walk('Corpus/Hindi_English/'):
for root, dirs, files in os.walk('Corpus/small/'):
for basename in files:
filename = os.path.join(root, basename)
print(filename)
bulk_grams = []
flag = False
for line in open(filename):
if not flag:
flag = True
continue
grams = re.split(r'\s',line.strip().replace("\\"," "))
id = grams[0]
sentence = grams[1:]
words = sentence[::2]
pos_tags = sentence[1::2]
if "eng" in filename:
lang = "eng"
else:
lang = "hin"
bulk_grams.append({"identifier":id,"lang":lang,"words":words,"pos_tags":pos_tags})
count += len(bulk_grams)
print 'Inserted '+str(count)
hinglish.insert_many(bulk_grams)
hinglish.remove({"identifier":"ID"})
def dump_matrix(lang_origin,lang_target):
client = MongoClient('localhost', 27017)
db = client['nlprokz']
words = sorted(db.hinglish.find({"lang":lang_target}).distinct("words"))
count = 0
count_update = 0
for i in db.hinglish.find({"lang":lang_origin}):
hindi_sentence = db.hinglish.find_one({"identifier":i['identifier'],"lang":lang_target})
bulk_vec = []
for j in i["words"]:
vec_count = db.bilingualvec.count({"word":j.lower()})
if vec_count > 0:
doc = db.bilingualvec.find_one({"word":j.lower()})
vec = doc["vec"]
for k in xrange(len(words)):
if words[k] in hindi_sentence["words"]:
vec[k] += 1
count_update += 1
#print "INSERTS:"+str(count_update)
db.bilingualvec.update_one({"word":j.lower()},{"$set":{"vec":vec,"lang_origin":lang_origin,"lang_target":lang_target}})
else:
vec = []
for k in words:
if k in hindi_sentence["words"]:
vec.append(1)
else:
vec.append(0)
count += 1
db.bilingualvec.insert({"word":j.lower(),"vec":vec,"lang_origin":lang_origin,"lang_target":lang_target})
print "NEW INSERTS:"+str(count)
def translate_word(word,lang_target):
client = MongoClient("localhost", 27017)
db = client["nlprokz"]
target_words = []
for i in db.bilingualvec.find({"lang_origin":lang_target}):
target_words.append(i['vec'])
target_words = np.array(target_words)
norm_vector = 1.0*np.sum(target_words,axis=0)
elem = db.bilingualvec.find_one({"word":word})
elem_vec = np.array(elem["vec"])/norm_vector
if elem_vec is None:
print("Word " + word + " not found!")
return
max_index = elem_vec.argsort()[-10:][::-1]
words = sorted(db.hinglish.find({"lang":lang_target}).distinct("words"))
print(max_index)
for i in max_index:
print(words[i] + " " + str(i) + " " + str(elem_vec[i]))
def find_closest(lang_origin,lang_target):
client = MongoClient("localhost", 27017)
db = client["nlprokz"]
target_words = []
target_words_strings = []
for i in db.bilingualvec.find({"lang_origin":lang_target}):
target_words.append(i['vec'])
target_words_strings.append(i['word'])
words = sorted(db.hinglish.find({"lang":lang_target}).distinct("words"))
norm_vector = 1.0*np.sum(target_words,axis=0)
target_words = target_words/(norm_vector)
target_words = target_words/(norm_vector)
target_words = np.transpose(np.array(target_words))
target_words = target_words/ np.linalg.norm(target_words, axis=0)
count = 0
for i in db.bilingualvec.find({"lang_origin":lang_origin}):
origin_word = 1.0*np.array([i['vec']])
origin_word = origin_word/np.sum(origin_word)
origin_word = origin_word/norm_vector
origin_word = origin_word/np.linalg.norm([origin_word])
# dist = []
# for word_vec in target_words:
# word_vec = np.transpose(word_vec)
# dist.append(euclidean(origin_word, word_vec))
# max_similarity = np.argmax(dist[0])
# print "STRING:"+i['word']+":"+target_words_strings[max_similarity]
# count += 1
# if count > 10:
# break
dot_product = np.dot(origin_word,target_words)
max_index = dot_product.argsort()[-5:][::-1]
for j in max_index[0][-5:]:
print "STRING:"+i['word']+":"+target_words_strings[j]+":"+str(dot_product[0][j])
# max_similarity = np.argmax(dot_product[0])
# print "STRING:"+i['word']+":"+target_words_strings[max_similarity]+":"+str(dot_product[0][max_similarity])
count += 1
if count > 100:
break
def get_vector(word, lang_origin, lang_target):
client = MongoClient("localhost", 27017)
db = client["nlprokz"]
word_entry = db.bilingualvec.find_one({"lang_origin":lang_origin, "word":word, "lang_target":lang_target})
if word_entry is None:
return None
print(word)
vec = 1.0*np.array(word_entry['vec'])
return vec
def get_sentence_vector(sentence, lang_origin, lang_target):
lang_origin = "eng"
lang_target = "hin"
sentence = ['Temples', 'in', 'India', 'are', 'very', 'beautiful', '.']
sent_vector = None
for word in sentence:
word_vector = get_vector(word.lower(), lang_origin, lang_target)
if word_vector is not None:
if sent_vector is None:
sent_vector = word_vector
else:
sent_vector += word_vector
return sent_vector
if __name__ == '__main__':
# dump_sentences()
# dump_matrix("eng","hin")
# dump_matrix("hin","hin")
# find_closest("eng","hin")
# translate_word("hill","hin")
lang_origin = "eng"
lang_target = "hin"
sentence = ['Train', 'runs', 'fast', '.']
sent_vector = get_sentence_vector(sentence, lang_origin, lang_target)
print(sent_vector)