package owl

  1. Overview
  2. Docs
OCaml Scientific and Engineering Computing

Install

Dune Dependency

Authors

Maintainers

Sources

owl-1.2.tbz
sha256=3817a2e4391922c8a2225b4e33ca95da6809246994e6bf291a300c82d8cac6c5
sha512=68a21f540cb4a289419f35cd152d132af36f1000fb41f98bab6e100698820379e36d650c5aa70a0126513451b354f86a28ea4ecf6f1d3b196b5b5e56f0fac9bd

doc/src/owl/owl_nlp_corpus.ml.html

Source file owl_nlp_corpus.ml

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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# 1 "src/owl/nlp/owl_nlp_corpus.ml"
(*
 * OWL - OCaml Scientific Computing
 * Copyright (c) 2016-2022 Liang Wang <liang@ocaml.xyz>
 *)

(** NLP: Corpus module *)

type t =
  { mutable uri : string
  ; (* path of the binary corpus *)
    mutable bin_ofs : int array
  ; (* index of the string corpus *)
    mutable tok_ofs : int array
  ; (* index of the tokenised corpus *)
    mutable bin_fh : in_channel option
  ; (* file descriptor of the binary corpus *)
    mutable tok_fh : in_channel option
  ; (* file descriptor of the tokenised corpus *)
    mutable vocab : Owl_nlp_vocabulary.t option
  ; (* vocabulary of the corpus *)
    mutable minlen : int
  ; (* minimum length of document to save *)
    mutable docid : int array (* document id, can refer to original data *)
  } [@@warning "-69"]

let _close_if_open = function
  | Some h -> close_in h
  | None   -> ()


let _open_if_exists f =
  match Sys.file_exists f with
  | true  -> Some (open_in f)
  | false -> None


let cleanup x =
  _close_if_open x.bin_fh;
  _close_if_open x.tok_fh


let create uri bin_ofs tok_ofs bin_fh tok_fh vocab minlen docid =
  let x = { uri; bin_ofs; tok_ofs; bin_fh; tok_fh; vocab; minlen; docid } in
  Gc.finalise cleanup x;
  x


let get_uri corpus = corpus.uri

let get_bin_uri corpus = corpus.uri ^ ".bin"

let get_bin_fh corpus =
  match corpus.bin_fh with
  | Some x -> x
  | None   ->
    let h = corpus |> get_bin_uri |> open_in in
    corpus.bin_fh <- Some h;
    h


let get_tok_uri corpus = corpus.uri ^ ".tok"

let get_tok_fh corpus =
  match corpus.tok_fh with
  | Some x -> x
  | None   ->
    let h = corpus |> get_tok_uri |> open_in in
    corpus.tok_fh <- Some h;
    h


let get_vocab_uri corpus = corpus.uri ^ ".voc"

let get_vocab corpus =
  match corpus.vocab with
  | Some x -> x
  | None   ->
    let h = corpus |> get_vocab_uri |> Owl_nlp_vocabulary.load in
    corpus.vocab <- Some h;
    h


let get_docid corpus = corpus.docid

let length corpus = Array.length corpus.bin_ofs - 1

(* iterate docs and tokenised docs and etc. *)

let next corpus : string = corpus |> get_bin_fh |> Marshal.from_channel

let next_tok corpus : int array = corpus |> get_tok_fh |> Marshal.from_channel

let iteri f corpus = Owl_io.iteri_lines_of_marshal f (get_bin_uri corpus)

let iteri_tok f corpus = Owl_io.iteri_lines_of_marshal f (get_tok_uri corpus)

let mapi f corpus = Owl_io.mapi_lines_of_marshal f (get_bin_uri corpus)

let mapi_tok f corpus = Owl_io.mapi_lines_of_marshal f (get_tok_uri corpus)

let get corpus i : string =
  let fh = get_bin_fh corpus in
  let old_pos = pos_in fh in
  seek_in fh corpus.bin_ofs.(i);
  let doc = Marshal.from_channel fh in
  seek_in fh old_pos;
  doc


let get_tok corpus i : int array =
  let fh = get_tok_fh corpus in
  let old_pos = pos_in fh in
  seek_in fh corpus.tok_ofs.(i);
  let doc = Marshal.from_channel fh in
  seek_in fh old_pos;
  doc


(* reset all the file pointers at offset 0 *)
let reset_iterators corpus =
  let _reset_offset = function
    | Some h -> seek_in h 0
    | None   -> ()
  in
  _reset_offset corpus.bin_fh;
  _reset_offset corpus.tok_fh


(* return a batch of documents *)
let next_batch ?(size = 100) corpus =
  let batch = Owl_utils.Stack.make () in
  (try
     for _i = 0 to size - 1 do
       corpus |> next |> Owl_utils.Stack.push batch
     done
   with
  | _exn -> ());
  Owl_utils.Stack.to_array batch


(* return a batch of tokenised documents *)
let next_batch_tok ?(size = 100) corpus =
  let batch = Owl_utils.Stack.make () in
  (try
     for _i = 0 to size - 1 do
       corpus |> next_tok |> Owl_utils.Stack.push batch
     done
   with
  | _exn -> ());
  Owl_utils.Stack.to_array batch


let tokenise corpus s =
  let dict = get_vocab corpus in
  Str.split (Str.regexp " ") s
  |> List.filter (Owl_nlp_vocabulary.exits_w dict)
  |> List.map (Owl_nlp_vocabulary.word2index dict)
  |> Array.of_list


(* convert corpus into binary format, build dictionary, tokenise
  lo and hi will be ignored if a vocab is passed in.

  The passed in docid can be used for tracking back to the original corpus, but
  this is not compulsory.
 *)
let build ?docid ?stopwords ?lo ?hi ?vocab ?(minlen = 10) fname =
  (* build and save the vocabulary if necessary *)
  let vocab =
    match vocab with
    | Some vocab -> vocab
    | None       ->
      Owl_log.info "build up vocabulary ...";
      Owl_nlp_vocabulary.build ?lo ?hi ?stopwords fname
  in
  Owl_nlp_vocabulary.save vocab (fname ^ ".voc");
  Owl_nlp_vocabulary.save_txt vocab (fname ^ ".voc.txt");
  (* prepare the output file *)
  let bin_f = fname ^ ".bin" |> open_out in
  let tok_f = fname ^ ".tok" |> open_out in
  let mdl_f = fname ^ ".mdl" |> open_out in
  Fun.protect
    (fun () ->
      set_binary_mode_out bin_f true;
      set_binary_mode_out tok_f true;
      (* initialise the offset array *)
      let b_ofs = Owl_utils.Stack.make () in
      let t_ofs = Owl_utils.Stack.make () in
      Owl_utils.Stack.push b_ofs 0;
      Owl_utils.Stack.push t_ofs 0;
      (* initialise the doc_id stack *)
      let doc_s = Owl_utils.Stack.make () in
      (* binarise and tokenise at the same time *)
      Owl_log.info "convert to binary and tokenise ...";
      Owl_io.iteri_lines_of_file
        (fun i s ->
          let t =
            Str.split Owl_nlp_utils.regexp_split s
            |> List.filter (Owl_nlp_vocabulary.exits_w vocab)
            |> List.map (Owl_nlp_vocabulary.word2index vocab)
            |> Array.of_list
          in
          (* only save those having at least minlen words *)
          if Array.length t >= minlen
          then (
            Marshal.to_channel bin_f s [];
            Marshal.to_channel tok_f t [];
            (* keep tracking of doc id *)
            let id =
              match docid with
              | Some d -> d.(i)
              | None   -> i
            in
            Owl_utils.Stack.push doc_s id;
            (* keep tracking of doc offset *)
            Owl_utils.Stack.push b_ofs (LargeFile.pos_out bin_f |> Int64.to_int);
            Owl_utils.Stack.push t_ofs (LargeFile.pos_out tok_f |> Int64.to_int)))
        fname;
      (* save the corpus file *)
      let b_ofs = Owl_utils.Stack.to_array b_ofs in
      let t_ofs = Owl_utils.Stack.to_array t_ofs in
      let doc_s = Owl_utils.Stack.to_array doc_s in
      let corpus = create fname b_ofs t_ofs None None None minlen doc_s in
      Marshal.to_channel mdl_f corpus [];
      (* return the finished corpus *)
      get_bin_fh corpus |> ignore;
      get_tok_fh corpus |> ignore;
      get_vocab corpus |> ignore;
      corpus)
    ~finally:(fun () ->
      (* done, close the files *)
      close_out bin_f;
      close_out tok_f;
      close_out mdl_f)


(* remove duplicates in a text corpus, the ids of the removed files are returned *)
let unique fi_name fo_name =
  let h = Hashtbl.create 1024 in
  let rm = Owl_utils.Stack.make () in
  let fo = open_out fo_name in
  Fun.protect
    (fun () ->
      Owl_io.iteri_lines_of_file
        (fun i s ->
          match Hashtbl.mem h s with
          | true  -> Owl_utils.Stack.push rm i
          | false ->
            output_string fo s;
            output_char fo '\n';
            Hashtbl.add h s None)
        fi_name;
      Owl_utils.Stack.to_array rm)
    ~finally:(fun () -> close_out fo)


(* a simple function for pre-processing a given string *)
let simple_process s =
  Str.split Owl_nlp_utils.regexp_split s
  |> List.filter (fun x -> String.length x > 1)
  |> String.concat " "
  |> String.lowercase_ascii


(* pre-process a given file with the passed in function
  e.g., you can plug in [simple_process] function to clean up the text.
  Note this function will not change the number of lines in a corpus.
 *)
let preprocess f fi_name fo_name =
  let fo = open_out fo_name in
  Fun.protect
    (fun () ->
      Owl_io.iteri_lines_of_file
        (fun _i s ->
          output_bytes fo (f s);
          output_char fo '\n')
        fi_name)
    ~finally:(fun () -> close_out fo)


(* i/o: save and load corpus *)

(* set some fields to None so it can be safely saved *)
let reduce_model corpus =
  { uri = corpus.uri
  ; bin_ofs = corpus.bin_ofs
  ; tok_ofs = corpus.tok_ofs
  ; bin_fh = None
  ; tok_fh = None
  ; vocab = None
  ; minlen = corpus.minlen
  ; docid = corpus.docid
  }


let save corpus f =
  let x = reduce_model corpus in
  Owl_io.marshal_to_file x f


let load f : t =
  let corpus = Owl_io.marshal_from_file f in
  get_bin_fh corpus |> ignore;
  get_tok_fh corpus |> ignore;
  get_vocab corpus |> ignore;
  corpus


(* convert tokenised corpus back to text file *)
let save_txt corpus f =
  let fh = open_out f in
  Fun.protect
    (fun () ->
      let vocab = get_vocab corpus in
      let i2w_f = Owl_nlp_vocabulary.index2word vocab in
      iteri_tok
        (fun _i t ->
          let s = t |> Array.map i2w_f |> Array.to_list |> String.concat " " in
          output_string fh s;
          output_char fh '\n')
        corpus)
    ~finally:(fun () -> close_out fh)


let to_string corpus =
  Printf.sprintf "corpus info\n"
  ^ Printf.sprintf "  file path  : %s\n" (corpus |> get_uri)
  ^ Printf.sprintf "  # of docs  : %i\n" (corpus |> length)
  ^ Printf.sprintf "  doc minlen : %i" corpus.minlen


let print corpus = corpus |> to_string |> print_endline

(* ends here *)
OCaml

Innovation. Community. Security.