-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython-as-web-service-shi-2013-12-02.html
494 lines (394 loc) · 20.5 KB
/
python-as-web-service-shi-2013-12-02.html
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<!DOCTYPE HTML>
<html>
<meta charset="utf-8" />
<head>
<title>Python As Web Services</title>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
<style>
body, p, td, pre {
font-size: 14pt; }
body {
background-color:lightyellow;
counter-reset: section subsection figure;}
h1 {
text-align:center }
h2 {
counter-increment: section; }
h3 {
counter-increment: subsection; }
h4 {
counter-increment: figure; }
h2:before {
content:counter(section) ". "; }
h3:before {
content:counter(section) "." counter(subsection) " "; }
h4:before{
content:"Fig. " counter(section) "." counter(figure) " - ";}
.reset {
counter-reset:subsection figure;}
.nav-bar{
list-style-type:none;
margin:0;
padding:0; }
img {
margin-left: 10pt;
border: thin solid gray; }
.sample {
background-color: black;
font-size: 12pt;
color:white;
padding: 4pt;
margin-left: 10pt;
margin-right: 30pt;
display: block;
white-space: pre-line;}
.code {
padding: 4pt;
font-size: 12pt;
background-color: whitesmoke;
border: thin dotted gray;
margin-left: 10pt;
margin-right: 30pt;
display: block;
white-space: pre;}
.author {
font-size: 16pt;
text-align:center;}
</style></head>
<body>
<a name="_top_" />
<nav class="nav-bar">
<a href="#install-nltk">install nltk</a>
|
<a href="#naive-bayes">naive bayes</a>
|
<a href="#java-interface">java interface</a>
|
<a href="#python-implement">python implement</a>
|
<a href="#service-wrapping">Service Wrapping</a>
</nav>
<h1>NLTK Python as Web Services</h1>
<p class="author">
Version <var>0.01</var>, <ruby>史 春奇 <rt> Chunqi Shi</rt></ruby>, Dec. 2013</p>
<a name="install-nltk" />
<h2>Install NLTK <a href="#_top_" style="text-decoration: none;">^</a></h2>
The <a href="http://nltk.org/">NLTK</a> provides Python tool kits for Natrual Language Processing. How to wrap such python tools into Web service? This will be interesting.
To <a href="http://nltk.org/install.html">install NLTK</a> on MacBook, we need to know the version of Python. After that, we download, setup and install NLTK package. Before using NLTK, we need to test and <a href="http://nltk.org/data.html">install NLTK Data</a>.
<samp class="sample">shis-MacBook-Air:~ shi$ python --version <span style="color:blue">↵</span>
Python 2.7.5
shis-MacBook-Air:~ shi$ wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py <span style="color:blue">↵ (download <a href="https://pythonhosted.org/setuptools/easy_install.html" target="_blank">easy_install</a>)</span>
--2013-12-02 16:24:31-- https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
......
2013-12-02 16:24:31 (118 MB/s) - ‘ez_setup.py’ saved [12155/12155]
shis-MacBook-Air:~ shi$ python ez_setup.py --user <span style="color:blue">↵(install <a href="https://pythonhosted.org/setuptools/easy_install.html" target="_blank">easy_install</a>)</span>
Downloading https://pypi.python.org/packages/source/s/setuptools/setuptools-1.4.2.tar.gz
......
Processing dependencies for setuptools==1.4.2
Finished processing dependencies for setuptools==1.4.2
shis-MacBook-Air:~ shi$ shis-MacBook-Air:~ shi$ sudo /Users/shi/Library/Python/2.7/bin/easy_install pip<span style="color:blue">↵ (install <a href="http://en.wikipedia.org/wiki/Pip_%28package_manager%29" target="_blank">pip</a>)</span>
Password:
Searching for pip
......
Processing dependencies for pip
Finished processing dependencies for pip
shis-MacBook-Air:~ shi$ sudo /Users/shi/Library/Python/2.7/bin/pip install -U numpy<span style="color:blue">↵ (install <a href="http://www.numpy.org" target="_blank">numpy</a>) </span>
......
Successfully installed numpy
Cleaning up...
shis-MacBook-Air:~ shi$ sudo /Users/shi/Library/Python/2.7/bin/pip install -U pyyaml nltk<span style="color:blue">↵ (install <a href="https://pypi.python.org/pypi/PyYAML" target="_blank">nltk</a>)</span>
Downloading/unpacking pyyaml
......
Successfully installed pyyaml nltk
Cleaning up...
shis-MacBook-Air:~ shi$ python <span style="color:blue">↵</span>
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
>>> import nltk <span style="color:blue">↵ (test nltk)</span>
>>> nltk.download() <span style="color:blue">↵ (download nltk data)</span>
showing info http://nltk.github.com/nltk_data/
True
>>> from nltk.corpus import brown <span style="color:blue">↵</span>
>>> brown.words() <span style="color:blue">↵ (test nltk data)</span>
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
>>>
</samp>
<figure>
<img src="python-as-web-service-shi-2013-12-02.img/img_nltk_download.png" alt="The NLTK Downloader" width="" height="">
<figcaption><h4> A view of NLTK downloader.</h4></figcaption></figure>
<p>
Here, we have installed the NLTK and Data package.
</p>
<a name="naive-bayes" />
<h2>NLTK's Naive Bayes Classifier<a href="#_top_" style="text-decoration: none;">^</a></h2>
<p>NLTK has Naive Bayes classifiers, <a href="http://nltk.org/book/ch06.html" target="_blank">Chapter 6</a> describes details about calculating features, training, and evaluating. The training and testing function will be wrapped into Web service. Thus, we need Python programs for training and testing, and need Java programs for SOAP service. </p>
<h3 class="reset">NLTK Naive Bayes</h3>
<p/>
<code class="code prettyprint linenums"># Example 6.7 (<a href="http://nltk.org/book/pylisting/code_consecutive_pos_tagger.py" target="_blank">code_consecutive_pos_tagger.py</a>)
# Natural Language Toolkit: code_consecutive_pos_tagger
def pos_features(sentence, i, history): # [_consec-pos-tag-features]
features = {"suffix(1)": sentence[i][-1:],
"suffix(2)": sentence[i][-2:],
"suffix(3)": sentence[i][-3:]}
if i == 0:
features["prev-word"] = "<START>"
features["prev-tag"] = "<START>"
else:
features["prev-word"] = sentence[i-1]
features["prev-tag"] = history[i-1]
return features
class ConsecutivePosTagger(nltk.TaggerI): # [_consec-pos-tagger]
def __init__(self, train_sents):
train_set = []
for tagged_sent in train_sents:
untagged_sent = nltk.tag.untag(tagged_sent)
history = []
for i, (word, tag) in enumerate(tagged_sent):
featureset = pos_features(untagged_sent, i, history)
train_set.append( (featureset, tag) )
history.append(tag)
self.classifier = nltk.NaiveBayesClassifier.train(train_set)
def tag(self, sentence):
history = []
for i, word in enumerate(sentence):
featureset = pos_features(sentence, i, history)
tag = self.classifier.classify(featureset)
history.append(tag)
return zip(sentence, history)
</code>
<!--
@brief: step by step wrapping based on template project.
-->
<a name="java-interface" />
<h2>Java Interface<a href="#_top_" style="text-decoration: none;">^</a></h2>
<h3 class="reset">Git Project</h3>
<p> We use <a href="http://git-scm.com/" target="_blank">Git</a> to manage the source code. After <a href="http://git-scm.com/downloads" target="_blank"> installation of Git </a>, you can <a href="https://help.github.com/articles/set-up-git" target="_blank" >set up Git</a>. Here we use <a href="https://github.com" target="_blank" >Github</a> to host the source code. If you want to use <a href="https://help.github.com/articles/https-cloning-errors" target="_blank"> https protocol </a> to access GitHub, you need to make sure git version >= 1.7.10. Then you could clone the repository <a href="https://github.com/chunqishi/lapps/tree/master/edu.brandeis.cs.template-web-service" target="_blank">lapps/edu.brandeis.cs.template-web-service/</a>
</p>
<samp class="sample">[shicq@chilote lapps]$ git --version <span style="color:blue">↵</span>
git version 1.8.2.1
[shicq@chilote lapps]$ git clone https://github.com/chunqishi/lapps.git <span style="color:blue">↵</span>
......
[shicq@chilote chunqishi]$ cd lapps/edu.brandeis.cs.template-web-service/ <span style="color:blue">↵</span>
[shicq@chilote edu.brandeis.cs.template-web-service]$
[shicq@chilote edu.brandeis.cs.template-web-service]$ find . <span style="color:blue">↵ Display the directory tree</span>
.
./pom.xml
./src
./src/main
./src/main/resource
./src/main/webapp
./src/main/webapp/WEB-INF
./src/main/webapp/WEB-INF/server-config.wsdd
./src/main/webapp/WEB-INF/serviceimpl
./src/main/webapp/WEB-INF/serviceimpl/template.xml
./src/main/webapp/WEB-INF/web.xml
./src/main/java
./src/main/java/edu
./src/main/java/edu/brandeis
./src/main/java/edu/brandeis/cs
./src/test
./src/test/java
./src/test/java/edu
./src/test/java/edu/brandeis
./src/test/java/edu/brandeis/cs
[shicq@chilote edu.brandeis.cs.template-web-service]$ mvn validate <span style="color:blue">↵ Maven validate</span>
[INFO] Scanning for projects...
[shicq@chilote edu.brandeis.cs.template-web-service]$
</samp>
<p>Then, We will define the Java Interface according to <a href="http://nltk.org/book/" target="_blank"> NLTK</a> Chapter 6 <a href="http://nltk.org/book/ch06.html" target="_blank">Learning to Classify Text</a>. </p> According to this chapter, Supervised Learning contains (a) <b>Training</b> (b) <b>Prediction</b>. Thus, there are at least two interface functions are needed.
<figure>
<img src="http://nltk.org/images/supervised-classification.png" alt="Supervised Classification. ">
<figcaption><h4><a href="http://nltk.org/book/ch06.html" target="_blank">Supervised Classification</a>. </h4></figcaption></figure>
<p> Here, we define a Java Interface <b>IClassify.java</b>. Meanwhile, we also define an exception process function, ClassifyException.
</p>
<code class="code prettyprint linenums">package edu.brandeis.cs.nltk;
import jp.go.nict.langrid.commons.rpc.intf.Service;
/**
* @brief According to <a href="http://nltk.org/book/ch06.html" target="_blank">NLTK Chapter 6</a>
* Two main interface <b>train</b> and <b>predict</b> are defined. Since features are always extracted from input.
* Thus, feature extractor is needed for further implementation.
* @author [email protected]
*
*/
@Service(namespace="servicegrid:servicetype:brandeis:NLTKClassifier")
public interface IClassify {
/**
* @brief train a classifier based on features.
* @refer <a href="http://nltk.org/book/ch06.html" target="_blank">Supervised Classification</a>
* @return classifierID
* @throws ClassifyException
*/
public String train(String featuresID) throws ClassifyException;
/**
* @brief predict classification label according to input using a trained model classifierID
* @param input users's one input.
* @param classifierID users set classifier.
* @return classification label.
* @throws ClassifyException
*/
public String predict(String classifierID, String input) throws ClassifyException;
/**
*
* @return existing feature sets.
* @throws ClassifyException
*/
public String [] listFeatureSets() throws ClassifyException;
}
</code>
<p> After this, we define two classifier for <em>Part-of-Speech Tagging</em>: <b>DecisionTreeClassifier</b> and <b>NaiveBayesClassifier</b>.
According Section <b>Part-of-Speech Tagging</b> of <a href="http://nltk.org/book/ch06.html" target="_blank">NLTK Chapter 6</a>, “we can train a classifier to work out which suffixes are most informative."
Thus, our Java Interface will be implemented based on python programming. We define 2 Java Classes: DecisionTreeClassifier.java and NaiveBayesClassifier.java.
Before we implement them, we would like to define a common Python runner class: <b>PythonRunner.java</b>. Then we can define an abstract Python classifier class: <b>AbstractPythonClassifier.java</b>.
</p>
<a name="python-implement" />
<h2>Python Implement<a href="#_top_" style="text-decoration: none;">^</a></h2>
<h3 class="reset">Python Common</h3>
<p> We provide a common library for easy usage.
<a href="https://github.com/chunqishi/lapps/blob/master/edu.brandeis.cs.nltk-web-service/src/main/resources/pythons/intfc_common_io.py" target="_blank">intfc_common_io.py</a>
and feature extract <a href="https://github.com/chunqishi/lapps/blob/master/edu.brandeis.cs.nltk-web-service/src/main/resources/pythons/intfc_nltk_features.py" target="_blank">intfc_nltk_features.py</a>.
After this, we realize the train <a href="https://github.com/chunqishi/lapps/blob/master/edu.brandeis.cs.nltk-web-service/src/main/resources/pythons/cf_naive_bayes_pos_tagger_train.py" target="_blank">cf_naive_bayes_pos_tagger_train.py</a> and <a href="https://github.com/chunqishi/lapps/blob/master/edu.brandeis.cs.nltk-web-service/src/main/resources/pythons/cf_naive_bayes_pos_tagger_predict.py" target="_blank">cf_naive_bayes_pos_tagger_predict.py</a>.
</p>
<code class="code prettyprint linenums">'''
/**
* @brief <b>cf_naive_bayes_pos_tagger_train.py</b> train a classifier based on features.
* @refer <a href="http://nltk.org/book/ch06.html" target="_blank">Supervised Classification</a>
* @return classifierID
* @throws ClassifyException
*/
public String train(String featuresID) throws ClassifyException;
'''
import sys,os,time,nltk, cPickle as pickle
from nltk.corpus import *
from intfc_common_io import log,home,load_features, save_classifiers
def train_naive_bayes(path, fname):
name='naive_bayes' + '_._' + fname
featuresets = load_features(path,fname)
log("load featuresets")
train_set = featuresets[1:200]
classifier = nltk.NaiveBayesClassifier.train(train_set)
log("train classifier")
save_classifiers(classifier, path, name)
log("dump classifier")
def main():
featuresID = sys.argv[1]
train_naive_bayes(home(), featuresID)
print featuresID
if __name__ == "__main__":
main()
</code>
<p>
</p>
<code class="code prettyprint linenums">'''
/**
* @brief <b>cf_naive_bayes_pos_tagger_predict.py</b> predict classification label according to input using a trained model classifierID
* @param input users's one input.
* @param classifierID users set classifier.
* @return classification label.
* @throws ClassifyException
*/
public String predict(String input, String classifierID) throws ClassifyException;
'''
import sys,os,ConfigParser,io,time,nltk, cPickle as pickle
from nltk.corpus import *
from intfc_common_io import log,home,load_commons, load_classifiers
from intfc_nltk_features import pos_features
def main():
classifierID = 'naive_bayes_._'+sys.argv[1]
input = sys.argv[2]
path = home()
classifier = load_classifiers(path, classifierID)
common_suffixes = load_commons(path, 'common_suffixes')
print classifier.classify(pos_features(common_suffixes, input))
if __name__ == "__main__":
main()
</code>
<a name="service-wrapping" />
<h2>Web Service Wrapping<a href="#_top_" style="text-decoration: none;">^</a></h2>
<p> We can config the Web service XML.
</p>
<textarea rows="12" cols="100" class="code prettyprint linenums" style="border:none;">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="target" class="jp.go.nict.langrid.servicecontainer.handler.TargetServiceFactory" >
<property name="service">
<bean class="edu.brandeis.cs.nltk.classifier.NaiveBayesClassifier" />
</property>
</bean>
</beans>
</textarea>
<p>
Then, we can deploy and run <em>mvn package</em> to package the war: <b>nltk-web-service.war</b>.
</p>
<samp class="sample">
[shicq@chilote edu.brandeis.cs.nltk-web-service]$ mvn clean;mvn package;
......
[INFO] Copying webapp resources [/home/j/llc/shicq/Project/chunqishi/lapps/edu.brandeis.cs.nltk-web-service/src/main/webapp]
[INFO] Webapp assembled in [34280 msecs]
[INFO] Building war: /home/j/llc/shicq/Project/chunqishi/lapps/edu.brandeis.cs.nltk-web-service/target/nltk-web-service.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:27.234s
[INFO] Finished at: Fri Dec 06 20:06:49 EST 2013
[INFO] Final Memory: 13M/238M
</samp>
<p>
We can deploy this war package into <a href="http://tomcat.apache.org/" target="_blank">Tomcat</a>. Copy the nltk-web-service.war into $TOMCAT_HOME/webapps, and start the tomcat server.
</p>
<samp class="sample">
[shicq@chilote apache-tomcat-6.0.37]$ bin/shutdown.sh
Using CATALINA_BASE: /home/j/llc/shicq/Softwares/apache-tomcat-6.0.37
Using CATALINA_HOME: /home/j/llc/shicq/Softwares/apache-tomcat-6.0.37
......
[shicq@chilote apache-tomcat-6.0.37]$ mv /home/j/llc/shicq/Project/chunqishi/lapps/edu.brandeis.cs.nltk-web-service/target/nltk-web-service.war webapps/
[shicq@chilote apache-tomcat-6.0.37]$ bin/startup.sh
Using CATALINA_BASE: /home/j/llc/shicq/Softwares/apache-tomcat-6.0.37
Using CATALINA_HOME: /home/j/llc/shicq/Softwares/apache-tomcat-6.0.37
</samp>
<p>
Now, we could visit <a href="http://chilote.cs.brandeis.edu:8080/" target="_blank">http://localhost:8080/</a>, and find out that tomcat is running.
Then, we could open <a href="http://chilote.cs.brandeis.edu:8080/nltk-web-service/jsServices" target="_blank">http://localhost:8080/nltk-web-service/jsServices</a> to invoke the JSON-RPC Web service.
</p>
<figure>
<img src="python-as-web-service-shi-2013-12-02.img/img_jsonrpc_services.png" alt="JSON RPC Services" width="" height="">
<figcaption><h4><a href="http://chilote.cs.brandeis.edu:8080/nltk-web-service/jsServices" target="_blank">JSON RPC Services.</a></h4></figcaption></figure>
<figure>
<img src="python-as-web-service-shi-2013-12-02.img/img_naivebayes_listfeaturesets.png" alt="Naive Bayes Services" width="" height="">
<figcaption><h4><a href="http://chilote.cs.brandeis.edu:8080/nltk-web-service/jsServices" target="_blank">Availabe Feature Sets.</a></h4></figcaption></figure>
<p> After, we list all the feature sets, we can train a classifier using the available feature set (e.g. <b>"features_brown_news"</b>).
Since it is too complicated to design scalable feature extractors. Currently, we just provide users default available feature sets.
</p>
<figure>
<img src="python-as-web-service-shi-2013-12-02.img/img_naivebayes_train.png" alt="Naive Bayes Services" width="" height="">
<figcaption><h4><a href="http://chilote.cs.brandeis.edu:8080/nltk-web-service/jsServices" target="_blank">Training Naive Bayes Classifier.</a></h4></figcaption></figure>
<p>After the training, We can test this naive bayes classifier <b>"features_brown_news"</b>. We input a name <b>"dogs"</b>. It will output the POST Tagger <b>"NNS"</b>.
</p>
<figure>
<img src="python-as-web-service-shi-2013-12-02.img/img_naivebayes_predict.png" alt="Naive Bayes Services" width="" height="">
<figcaption><h4><a href="http://chilote.cs.brandeis.edu:8080/nltk-web-service/jsServices" target="_blank">Testing Naive Bayes Classifier.</a></h4></figcaption></figure>
<p> Finally, all the codes are available from Github <a href="https://github.com/chunqishi/lapps/tree/master/edu.brandeis.cs.nltk-web-service" target="_blank">edu.brandeis.cs.nltk-web-service</a>.
You can git clone for details.
</p>
<!--
<figure>
<img src="img_pulpit.jpg" alt="The Pulpit Rock" width="304" height="228">
<figcaption><h4> A view of the pulpit rock in Norway.</h4></figcaption></figure>
<h3/>
<h3/>
<h4/>
<h2></h2>
<h3 class="reset"/>
<h3/>
<h4 class="reset" />
<h4/>
-->
<footer><hr/>
<p>
Progress:
<progress value="60" max="100"></progress></p>
<p>
Contacts:
<nonsense>shi</nonsense>cq@<nonsense>cs.</nonsense>brandeis.<nonsense></nonsense>edu,
<nonsense>mar</nonsense>c@<nonsense>cs.</nonsense>brandeis.<nonsense></nonsense>edu </p></footer>
</body></html>