Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathutils.lua
More file actions
Latest commit
275 lines (238 loc) · 6.99 KB
/
Copy pathutils.lua
File metadata and controls
275 lines (238 loc) · 6.99 KB
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
localdl=require'dataload._env'
-- Temporarily changes the current working directory to call fn,
-- returning its result.
functiondl.withcwd(path, fn)
localcurdir=lfs.currentdir()
lfs.chdir(path)
localres=fn()
lfs.chdir(curdir)
returnres
end
-- Downloads srcurl into dstdir.
-- If existfile is provided then
-- download only if that file doesn't exist
functiondl.downloadfile(dstdir, srcurl, existfile)
if (notexistfile) or (notpaths.filep(existfile)) then
paths.mkdir(dstdir)
dl.withcwd(
dstdir,
function()
localprotocol, scpurl, filename=srcurl:match('(.-)://(.*)/(.-)$')
ifprotocol=='scp' then
os.execute(string.format('%s %s %s', 'scp', scpurl..'/' ..filename, filename))
else
os.execute('wget ' ..srcurl)
end
end
)
end
returndstdir
end
-- Decompress a .tar, .tgz or .tar.gz file.
functiondl.untar(srcpath, dstpath)
localdstpath=dstpathor'.'
paths.mkdir(dstpath)
ifsrcpath:match("%.tar$") then
os.execute('tar -xvf ' ..srcpath..' -C ' ..dstpath)
else
os.execute('tar -xvzf ' ..srcpath..' -C ' ..dstpath)
end
end
-- unzip a .zip file
functiondl.unzip(srcpath, dstpath)
localdstpath=dstpathor'.'
paths.mkdir(dstpath)
os.execute('unzip ' ..srcpath..' -d ' ..dstpath)
end
-- gunzip a .gz file
functiondl.gunzip(srcpath, dstpath)
assert(notdstpath, "destination path not supported with gunzip")
os.execute('gunzip ' ..srcpath)
end
-- Decompresses srczip into dstdir.
-- If existfile is provided then
-- decompress only if that file doesn't exist.
-- Supported extensions for srczip are : .zip, .tar, .tgz, .gz, .gzip
functiondl.decompressfile(dstdir, srczip, existfile, verbose, dstfile)
paths.mkdir(dstdir)
if (notexistfile) or (notpaths.filep(existfile)) then
dl.withcwd(dstdir,
function()
ifverbosethen
print("decompressing file: ", srczip)
end
ifstring.find(srczip, ".zip") then
dl.unzip(srczip, dstfile)
elseifstring.find(srczip, ".tar") orstring.find(srczip, ".tgz") then
dl.untar(srczip, dstfile)
elseifstring.find(srczip, ".gz") orstring.find(srczip, ".gzip") then
dl.gunzip(srczip, dstfile)
else
error("Don't know how to decompress file: ", srczip)
end
end
)
end
end
-- loads data as ascii, if that doesn't work, loads as binary.
functiondl.load(path)
localsuccess, data=pcall(function() returntorch.load(path, "ascii") end)
ifnotsuccessthen
data=torch.load(path, "binary")
end
returndata
end
functiondl.rescale(data, min, max, dmin, dmax)
localrange=max-min
localdmin=dminordata:min()
localdmax=dmaxordata:max()
localdrange=dmax-dmin
data:add(-dmin)
data:mul(range)
data:mul(1/drange)
data:add(min)
returndata
end
functiondl.binarize(x, threshold)
x[x:lt(threshold)] =0
x[x:ge(threshold)] =1
returnx
end
-- text utility functions
-- this can be inefficent, I wouldn't use it for datasets larger than PTB
functiondl.buildVocab(tokens, minfreq)
assert(torch.type(tokens) =='table', 'Expecting table')
assert(torch.type(tokens[1]) =='string', 'Expecting table of strings')
minfreq=minfreqor-1
assert(torch.type(minfreq) =='number')
localwordfreq= {}
fori=1,#tokensdo
localword=tokens[i]
wordfreq[word] = (wordfreq[word] or0) +1
end
localvocab, ivocab= {}, {}
localwordseq=0
local_=require'moses'
-- make sure ordering is consistent
localwords=_.sort(_.keys(wordfreq))
localoov=0
fori, wordinipairs(words) do
localfreq=wordfreq[word]
iffreq>=minfreqthen
wordseq=wordseq+1
vocab[word] =wordseq
ivocab[wordseq] =word
else
oov=oov+freq
end
end
ifoov>0then
wordseq=wordseq+1
wordfreq['<OOV>'] =oov
vocab['<OOV>'] =wordseq
ivocab[wordseq] ='<OOV>'
end
returnvocab, ivocab, wordfreq
end
functiondl.text2tensor(tokens, vocab)
localoov=vocab['<OOV>']
localtensor=torch.IntTensor(#tokens):fill(0)
fori, wordinipairs(tokens) do
localwordid=vocab[word]
ifnotwordidthen
assert(oov)
wordid=oov
end
tensor[i] =wordid
end
returntensor
end
functiondl.splitString(str,sep)
localsep, fields=sepor":", {}
localpattern=string.format("([^%s]+)", sep)
str:gsub(pattern, function(c) fields[#fields+1] =cend)
returnfields
end
functiondl.getNumberOfLines(filename)
localctr=0
for_inio.lines(filename) do
ctr=ctr+1
end
returnctr
end
-- misc.
functiondl.hostname()
localf=io.popen ("/bin/hostname")
ifnotfthen
return'localhost'
end
localhostname=f:read("*a") or""
f:close()
hostname=string.gsub(hostname, "\n$", "")
returnhostname
end
-- Generates a globally unique identifier.
-- If a namespace is provided it is concatenated with
-- the time of the call, and the next value from a sequence
-- to get a pseudo-globally-unique name.
-- Otherwise, we concatenate the linux hostname
localcounter=1
functiondl.uniqueid(namespace, separator)
localseparator=separatoror':'
localnamespace=namespaceordl.hostname()
localuid=namespace..separator..os.time()..separator..counter
counter=counter+1
returnuid
end
-- table
--http://lua-users.org/wiki/TableUtils
functiontable.val_to_str ( v )
if"string" ==type( v ) then
v=string.gsub( v, "\n", "\\n" )
ifstring.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
return"'" ..v.."'"
end
return'"' ..string.gsub(v,'"', '\\"' ) ..'"'
else
return"table" ==type( v ) andtable.tostring( v ) ortostring( v )
end
end
functiontable.key_to_str ( k )
if"string" ==type( k ) andstring.match( k, "^[_%a][_%a%d]*$" ) then
returnk
else
return"[" ..table.val_to_str( k ) .."]"
end
end
functiontable.tostring(tbl, newline, sort)
localresult, done= {}, {}
fork, vinipairs( tbl ) do
table.insert( result, table.val_to_str( v ) )
done[ k ] =true
end
locals="="
ifnewlinethen
s=" : "
end
fork, vinpairs( tbl ) do
ifnotdone[ k ] then
localline=table.key_to_str( k ) ..s..table.val_to_str( v )
table.insert(result, line)
end
end
ifsortthen
local_=require'moses'
_.sort(result)
end
localres
ifnewlinethen
res="{\n" ..table.concat( result, "\n" ) .."\n}"
else
res="{" ..table.concat( result, "," ) .."}"
end
returnres
end
functiontable.print(tbl)
assert(torch.type(tbl) =='table', "expecting table")
print(table.tostring(tbl, true, true))
end