Debian Codegraph @

bindings/java/org/linkgrammar/LGService.java

raw
1 /*************************************************************************/
2 /* */
3 /* Use of the link grammar parsing system is subject to the terms of the */
4 /* license set forth in the LICENSE file included with this software. */
5 /* This license allows free redistribution and use in source and binary */
6 /* forms, with or without modification, subject to certain conditions. */
7 /* */
8 /*************************************************************************/
9
10 package org.linkgrammar;
11
12 import java.io.File;
13 import java.io.InputStreamReader;
14 import java.io.PrintWriter;
15 import java.io.Reader;
16 import java.net.ServerSocket;
17 import java.net.Socket;
18 import java.text.SimpleDateFormat;
19 import java.util.Map;
20 // import java.util.concurrent.Future;
21 import java.util.concurrent.LinkedBlockingQueue;
22 import java.util.concurrent.ThreadPoolExecutor;
23 import java.util.concurrent.TimeUnit;
24
25 /**
26 * A simple server implementation for running Link Grammar as a
27 * standalone server. The server accepts parsing requests and returns
28 * the result as a JSON formatted string (see this
29 * <a href="http://www.json.org">JSON</a> website for more information).
30 * There is no session maintained between client and server, it's a
31 * simple, stateless, single round-trip, request-response protocol.
32 *
33 * Requests consist of a bag of parameters separated by the null '\0'
34 * character. Each request must be terminated with the newline '\n'
35 * character. Each parameter has the form <em>name:value\0</em> where
36 * <em>name</em> and <em>value</em> can contain any character except
37 * '\0' and '\n'. The following parameters are recognized:
38 *
39 * <ul>
40 * <li><b>maxLinkages</b> - maximum number of parses to return in the
41 * result. Note that this does not affect the parser behavior which
42 * computes all parses anyway.</li>
43 * <li><b>maxParseSeconds</b> - abort parsing if it takes longer than this</li>
44 * <li><b>maxCost</b> - don't report linkages with cost greater than this</li>
45 * <li><b>storeConstituentString</b> - whether to return the constituent
46 * string for each Linkage as part of the result.</li>
47 * <li><b>storeDiagramString</b> - return ASCII-art diagram.</li>
48 * <li><b>text</b> - The text to parse. Note that it must be stripped
49 * from newlines.</li>
50 * </ul>
51 *
52 * The server maintains incoming requests in an unbounded queue and
53 * handles them in thread pool whose size can be specified at the
54 * command line. A thread pool of size > 1 will only work if the Link
55 * Grammar version used is thread-safe.
56 *
57 * Execute this class as a main program to view a list of options.
58 *
59 * @author Borislav Iordanov
60 *
61 */
62 public class LGService
63 {
64 private static boolean verbose = false;
65 private static SimpleDateFormat dateFormatter =
66 new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
67
68 // Multi-threading:
69 //
70 // Before thread-exit, the LinkGrammar.close() method should be
71 // called -- it frees the per-thread data structures in the JNI
72 // LinkGrammar code, specifically, the per-thread sentence and
73 // linkage data structures. A mem leak will result if this is not
74 // called before thread exit.
75 //
76 // Upon LinkGrammar class destruction: the LinkGrammar.doFinalize()
77 // method should be called -- it frees the global data structures
78 // (specifically, the dictionary, shared by all threads).
79 //
80 private static ThreadLocal<Boolean> initialized = new ThreadLocal<Boolean>()
81 { protected Boolean initialValue() { return Boolean.FALSE; } };
82
83 /**
84 * <p>Return <code>true</code> if LinkGrammar is initialized for
85 * the current thread and <code>false</code> otherwise.
86 */
87 public static boolean isInitialized()
88 {
89 return initialized.get();
90 }
91
92 /**
93 * <p>
94 * Initialize LinkGrammar for the current thread, if this is not
95 * already done. Note that this method is called by all other
96 * methods in this class that invoke LinkGrammar so there's no
97 * real need to call it yourself. It is safe to call the method
98 * repeatedly. Note that the dictionary language/location must be
99 * set *before* calling init.
100 * </p>
101 */
102 public static void init()
103 {
104 if (!initialized.get())
105 {
106 LinkGrammar.init();
107 initialized.set(Boolean.TRUE);
108 }
109 }
110
111 /**
112 * <p>
113 * Cleanup allocated memory for use of LinkGrammar in the current thread.
114 * </p>
115 */
116 public static void close()
117 {
118 LinkGrammar.close();
119 initialized.set(Boolean.FALSE);
120 }
121 public static void doFinalize()
122 {
123 LinkGrammar.doFinalize();
124 }
125
126 private static void trace(String s)
127 {
128 if (verbose)
129 System.out.println("LG " + dateFormatter.format(new java.util.Date()) + " " + s);
130 }
131
132 /**
133 * <p>
134 * Apply configuration parameters to the parser.
135 * </p>
136 */
137 public static void configure(LGConfig config)
138 {
139 init();
140
141 if (config.getMaxCost() > -1.0)
142 LinkGrammar.setMaxCost(config.getMaxCost());
143 if (config.getMaxParseSeconds() > -1)
144 LinkGrammar.setMaxParseSeconds(config.getMaxParseSeconds());
145
146 // XXX DO NOT DO THIS!!! This will royally screw up results!
147 // Setting the link-grammar max linkages to a low number,
148 // e.g. 4, when there are a dozen or more parses, will cause a
149 // RANDOM 4 sentences to be returned out of the dozen, instead
150 // of the top 4. We almost surely do NOT want that! Or rather,
151 // I'm assuming no one actually wants that; we want the top 4!!
152 // So, setting the link-grammar max linkages iss a huge mistake!
153 // if (config.getMaxLinkages() > -1)
154 // LinkGrammar.setMaxLinkages(config.getMaxLinkages());
155 }
156
157 /**
158 * Assuming <code>LinkGrammar.parse</code> has already been called,
159 * construct a full <code>ParseResult</code> given the passed in
160 * configuration. For example, no more that
161 * <code>config.getMaxLinkages</code> are returned, etc.
162 *
163 * @param config
164 * @return
165 */
166 public static ParseResult getAsParseResult(LGConfig config)
167 {
168 LinkGrammar.makeLinkage(0); // need to call at least once, otherwise it crashes
169 ParseResult parseResult = new ParseResult();
170 parseResult.setParserVersion(LinkGrammar.getVersion());
171 parseResult.setDictVersion(LinkGrammar.getDictVersion());
172 parseResult.numSkippedWords = LinkGrammar.getNumSkippedWords();
173
174 int maxLinkages = Math.min(config.getMaxLinkages(), LinkGrammar.getNumLinkages());
175 for (int li = 0; li < maxLinkages; li++)
176 {
177 LinkGrammar.makeLinkage(li);
178 Linkage linkage = new Linkage();
179 linkage.setDisjunctCost(LinkGrammar.getLinkageDisjunctCost());
180 linkage.setLinkCost(LinkGrammar.getLinkageLinkCost());
181 linkage.setLinkedWordCount(LinkGrammar.getNumWords());
182 linkage.setNumViolations(LinkGrammar.getLinkageNumViolations());
183 String [] disjuncts = new String[LinkGrammar.getNumWords()];
184 String [] words = new String[LinkGrammar.getNumWords()];
185 for (int i = 0; i < words.length; i++)
186 {
187 disjuncts[i] = LinkGrammar.getLinkageDisjunct(i);
188 words[i] = LinkGrammar.getLinkageWord(i);
189 }
190 linkage.setWords(words);
191 linkage.setDisjuncts(disjuncts);
192 int numLinks = LinkGrammar.getNumLinks();
193 for (int i = 0; i < numLinks; i++)
194 {
195 Link link = new Link();
196 link.setLabel(LinkGrammar.getLinkLabel(i));
197 link.setLeft(LinkGrammar.getLinkLWord(i));
198 link.setRight(LinkGrammar.getLinkRWord(i));
199 link.setLeftLabel(LinkGrammar.getLinkLLabel(i));
200 link.setRightLabel(LinkGrammar.getLinkRLabel(i));
201 linkage.getLinks().add(link);
202 }
203 if (config.isStoreConstituentString())
204 linkage.setConstituentString(LinkGrammar.getConstituentString());
205 if (config.isStoreDiagramString())
206 linkage.setDiagramString(LinkGrammar.getLinkString());
207 parseResult.linkages.add(linkage);
208 }
209 return parseResult;
210 }
211
212 /**
213 * Construct a JSON formatted result for a parse which yielded 0 linkages.
214 */
215 public static String getEmptyJSONResult(LGConfig config)
216 {
217 StringBuffer buf = new StringBuffer();
218 buf.append("\"numSkippedWords\":0,");
219 buf.append("\"linkages\":[],");
220 buf.append("\"version\":\"" + LinkGrammar.getVersion() + "\",");
221 buf.append("\"dictVersion\":\"" + LinkGrammar.getDictVersion() + "\"}");
222 return buf.toString();
223 }
224
225 /**
226 * Format the current parsing result as a JSON string. This method
227 * assume that <code>LinkGrammar.parse</code> has been called before.
228 */
229 public static String getAsJSONFormat(LGConfig config)
230 {
231 LinkGrammar.makeLinkage(0); // need to call at least once, otherwise it crashes
232 int numWords = LinkGrammar.getNumWords();
233 int maxLinkages = Math.min(config.getMaxLinkages(), LinkGrammar.getNumLinkages());
234 StringBuffer buf = new StringBuffer();
235 buf.append("{\"numSkippedWords\":" + LinkGrammar.getNumSkippedWords());
236 buf.append(",\"linkages\":[");
237 for (int li = 0; li < maxLinkages; li++)
238 {
239 LinkGrammar.makeLinkage(li);
240 buf.append("{\"words\":[");
241 for (int i = 0; i < numWords; i++)
242 {
243 buf.append(JSONUtils.jsonString(LinkGrammar.getLinkageWord(i)));
244 if (i + 1 < numWords)
245 buf.append(",");
246 }
247 buf.append("], \"disjuncts\":[");
248 for (int i = 0; i < numWords; i++)
249 {
250 buf.append(JSONUtils.jsonString(LinkGrammar.getLinkageDisjunct(i)));
251 if (i + 1 < numWords)
252 buf.append(",");
253 }
254 buf.append("], \"disjunctCost\":");
255 buf.append(Double.toString(LinkGrammar.getLinkageDisjunctCost()));
256 buf.append(", \"linkageCost\":");
257 buf.append(Double.toString(LinkGrammar.getLinkageLinkCost()));
258 buf.append(", \"numViolations\":");
259 buf.append(Integer.toString(LinkGrammar.getLinkageNumViolations()));
260 if (config.isStoreConstituentString())
261 {
262 buf.append(", \"constituentString\":");
263 buf.append(JSONUtils.jsonString(LinkGrammar.getConstituentString()));
264 }
265 if (config.isStoreDiagramString())
266 {
267 buf.append(", \"diagramString\":");
268 buf.append(JSONUtils.jsonString(LinkGrammar.getLinkString()));
269 }
270 buf.append(", \"links\":[");
271 int numLinks = LinkGrammar.getNumLinks();
272 for (int i = 0; i < numLinks; i++)
273 {
274 buf.append("{\"label\":" + JSONUtils.jsonString(LinkGrammar.getLinkLabel(i)) + ",");
275 buf.append("\"left\":" + LinkGrammar.getLinkLWord(i) + ",");
276 buf.append("\"right\":" + LinkGrammar.getLinkRWord(i) + ",");
277 buf.append("\"leftLabel\":" + JSONUtils.jsonString(LinkGrammar.getLinkLLabel(i)) + ",");
278 buf.append("\"rightLabel\":" + JSONUtils.jsonString(LinkGrammar.getLinkRLabel(i)) + "}");
279 if (i + 1 < numLinks)
280 buf.append(",");
281 }
282 buf.append("]");
283 buf.append("}");
284 if (li < maxLinkages - 1)
285 buf.append(",");
286 }
287 buf.append("],\"version\":\"" + LinkGrammar.getVersion() + "\"");
288 buf.append(",\"dictVersion\":\"" + LinkGrammar.getDictVersion() + "\"");
289 buf.append("}");
290 return buf.toString();
291 }
292
293 /**
294 * A stub method for now for implementing a compact binary format
295 * for parse results.
296 *
297 * @param config
298 * @return
299 */
300 public static byte [] getAsBinary(LGConfig config)
301 {
302 int size = 0;
303 byte [] buf = new byte[1024];
304 // TODO ..... grow buf as needed
305 byte [] result = new byte[size];
306 System.arraycopy(buf, 0, result, 0, size);
307 return result;
308 }
309
310 private static void handleClient(Socket clientSocket)
311 {
312 init();
313 Reader in = null;
314 PrintWriter out = null;
315 JSONUtils msgreader = new JSONUtils();
316 try
317 {
318 trace("Connection accepted from : " + clientSocket.getInetAddress());
319 in = new InputStreamReader(clientSocket.getInputStream());
320 Map<String, String> msg = msgreader.readMsg(in);
321 if (verbose)
322 trace("Received msg '" + msg + "' from " + clientSocket.getInetAddress());
323 String json = "{}";
324 if ("version".equals(msg.get("get"))) // special case msg 'get:version'
325 json = "{\"version\":\"" + LinkGrammar.getVersion() + "\"}";
326 else
327 {
328 LGConfig config = new LGConfig();
329 config.setMaxCost(JSONUtils.getDouble("maxCost", msg, config.getMaxCost()));
330 config.setMaxLinkages(JSONUtils.getInt("maxLinkages", msg, config.getMaxLinkages()));
331 config.setMaxParseSeconds(JSONUtils.getInt("maxParseSeconds", msg, config.getMaxParseSeconds()));
332 config.setStoreConstituentString(
333 JSONUtils.getBool("storeConstituentString", msg, config.isStoreConstituentString()));
334 config.setStoreDiagramString(
335 JSONUtils.getBool("storeDiagramString", msg, config.isStoreDiagramString()));
336 configure(config);
337 String text = msg.get("text");
338 if (text != null && text.trim().length() > 0)
339 {
340 LinkGrammar.parse(text);
341 if (LinkGrammar.getNumLinkages() > 0)
342 json = getAsJSONFormat(config);
343 else
344 json = getEmptyJSONResult(config);
345 }
346 else
347 json = getEmptyJSONResult(config);
348 }
349 out = new PrintWriter(clientSocket.getOutputStream(), true);
350 out.print(json.length() + 1);
351 out.print('\n');
352 out.print(json);
353 out.print('\n');
354 out.flush();
355 trace("Response written to " + clientSocket.getInetAddress() + ", closing client connection...");
356 }
357 catch (Throwable t)
358 {
359 t.printStackTrace(System.err);
360 }
361 finally
362 {
363 if (out != null) try { out.close(); } catch (Throwable t) { }
364 if (in != null) try { in.close(); } catch (Throwable t) { }
365 if (clientSocket != null) try { clientSocket.close(); } catch (Throwable t) { }
366 }
367 }
368
369 /**
370 * <p>
371 * Parse a piece of text with the given configuration and return
372 * the <code>ParseResult</code>.
373 * </p>
374 *
375 * @param config The configuration to be used. If this is the first
376 * time the <code>parse</code> method is called within the current
377 * thread, the dictionary location (if not <code>null</code>) of
378 * this parameter will be used to initialize the parser. Otherwise
379 * the dictionary location is ignored.
380 *
381 * @param text The text to parse, normally a single sentence.
382 *
383 * @return The <code>ParseResult</code>. Note that <code>null</code>
384 * is never returned. If parsing failed, there will be 0 linkages in
385 * the result.
386 */
387 public static ParseResult parse(LGConfig config, String text)
388 {
389 init();
390 configure(config);
391 LinkGrammar.parse(text);
392 return getAsParseResult(config);
393 }
394
395 public static void main(String [] argv)
396 {
397 int threads = 1;
398 int port = 0;
399 String dictionaryPath = null;
400 String language = null;
401 try
402 {
403 int argIdx = 0;
404 if (argv[argIdx].equals("-verbose")) { verbose = true; argIdx++; }
405 if (argv[argIdx].equals("-threads")) { threads = Integer.parseInt(argv[++argIdx]); argIdx++; }
406 port = Integer.parseInt(argv[argIdx++]);
407 if (argv.length > argIdx)
408 language = argv[argIdx++];
409 if (argv.length > argIdx)
410 dictionaryPath = argv[argIdx++];
411 }
412 catch (Throwable ex)
413 {
414 if (argv.length > 0)
415 ex.printStackTrace(System.err);
416 System.out.println("Usage: java org.linkgrammar.LGService [-verbose] [-threads n] port [language] [dictPath]");
417 System.out.println("Start a link-grammar parse server on tcp/ip port. The server returns");
418 System.out.println("JSON-formated parse results. Socket input should be a single sentence");
419 System.out.println("to parse, proceeded by the identifier \"text:\".\n");
420 System.out.println(" 'port' The TCP port the service should listen to.");
421 System.out.println(" -verbose Generate verbose output.");
422 System.out.println(" -threads Number of concurrent threads/clients allowed (default 1).");
423 System.out.println(" 'language' Language abbreviation (en, ru, de, lt or fr).");
424 System.out.println(" 'dictPath' Full path to the Link-Grammar dictionaries.");
425 System.exit(-1);
426 }
427
428 if (dictionaryPath != null)
429 {
430 File f = new File(dictionaryPath);
431 if (!f.exists())
432 { System.err.println("Dictionary path " + dictionaryPath + " not found."); System.exit(-1); }
433 else if (!f.isDirectory())
434 { System.err.println("Dictionary path " + dictionaryPath + " not a directory."); System.exit(-1); }
435 }
436
437 System.out.println("Starting Link Grammar Server at port " + port +
438 ", with " + threads + " available processing threads and " +
439 ((dictionaryPath == null) ? " with default dictionary location." :
440 "with dictionary location '" + dictionaryPath + "'."));
441 ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threads,
442 threads,
443 Long.MAX_VALUE,
444 TimeUnit.SECONDS,
445 new LinkedBlockingQueue<Runnable>());
446 try
447 {
448 if (language != null)
449 LinkGrammar.setLanguage(language);
450 if (dictionaryPath != null)
451 LinkGrammar.setDictionariesPath(dictionaryPath);
452 ServerSocket serverSocket = new ServerSocket(port);
453 while (true)
454 {
455 trace("Waiting for client connections...");
456 final Socket clientSocket = serverSocket.accept();
457 threadPool.submit(new Runnable()
458 {
459 public void run()
460 {
461 // We must catch in here, and not outside the
462 // thread pool, because the submit method will
463 // silently swallow the exception. There is a
464 // CERT advisory for this feature/bug:
465 // http://www.securecoding.cert.org/confluence/display/java/TPS03-J.+Ensure+that+tasks+executing+in+a+thread+pool+do+not+fail+silently
466 try
467 {
468 handleClient(clientSocket);
469 }
470 catch (Throwable t)
471 {
472 t.printStackTrace(System.err);
473 System.exit(-1);
474 }
475 }
476 });
477 }
478 }
479 catch (Throwable t)
480 {
481 t.printStackTrace(System.err);
482 System.exit(-1);
483 }
484 }
485 }