ginzaserver 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,237 @@
1
+ Metadata-Version: 2.4
2
+ Name: ginzaserver
3
+ Version: 0.1.0
4
+ Summary: HTTP Server for GiNZA - Japanese NLP Library
5
+ Home-page: https://github.com/oyahiroki/ginzaserver
6
+ Author: Hiroki Oya
7
+ Author-email: Hiroki Oya <oyahiroki@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ Project-URL: Homepage, https://github.com/oyahiroki/ginzaserver
10
+ Project-URL: Repository, https://github.com/oyahiroki/ginzaserver
11
+ Keywords: ginza,spacy,japanese,nlp,http-server
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: ginza>=5.2.0
16
+ Requires-Dist: ja-ginza
17
+ Provides-Extra: electra
18
+ Requires-Dist: ja-ginza-electra; extra == "electra"
19
+ Provides-Extra: dev
20
+ Requires-Dist: build; extra == "dev"
21
+ Requires-Dist: twine; extra == "dev"
22
+ Dynamic: author
23
+ Dynamic: home-page
24
+ Dynamic: license-file
25
+ Dynamic: requires-python
26
+
27
+ # ginzaserver
28
+
29
+ HTTP Server for GiNZA - Japanese NLP Library
30
+
31
+ A high-performance, multi-threaded HTTP server that provides REST API access to [GiNZA](https://megagonlabs.github.io/ginza/), a Japanese natural language processing library built on spaCy.
32
+
33
+ ## Features
34
+
35
+ - 🚀 **Multi-threaded server** using `ThreadingMixIn` for concurrent request handling
36
+ - 🎯 **Dual model support**: Choose between `ja_ginza` (fast) or `ja_ginza_electra` (accurate)
37
+ - 🔥 **GPU acceleration** support for enhanced performance
38
+ - 📊 **Performance optimized** with list comprehensions and efficient memory management
39
+ - 🌐 **REST API** with both GET and POST endpoints
40
+ - 📝 **JSON response format** with detailed token analysis
41
+
42
+ ## Installation
43
+
44
+ ### Prerequisites
45
+
46
+ Python 3.8 or higher is required.
47
+
48
+ ### Install GiNZA Models
49
+
50
+ Choose one or both models based on your needs:
51
+
52
+ ```bash
53
+ # Fast model (recommended for production)
54
+ pip install -U ginza ja_ginza
55
+
56
+ # Accurate model (higher memory usage, ~16GB RAM recommended)
57
+ pip install -U ginza ja_ginza_electra
58
+ ```
59
+
60
+ ### Install ginzaserver
61
+
62
+ Install directly from GitHub:
63
+
64
+ ```bash
65
+ pip install git+https://github.com/oyahiroki/ginzaserver
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ### Running the Server
71
+
72
+ ```bash
73
+ ginzaserver <port> <option>
74
+ ```
75
+
76
+ **Parameters:**
77
+ - `port`: Port number to listen on (e.g., 8888)
78
+ - `option`: Model selection
79
+ - `0`: Use `ja_ginza` (faster, 10-20ms per request)
80
+ - `1`: Use `ja_ginza_electra` (more accurate, 40-50ms per request)
81
+
82
+ **Example:**
83
+
84
+ ```bash
85
+ ginzaserver 8888 0
86
+ ```
87
+
88
+ ### API Endpoints
89
+
90
+ #### POST Request
91
+
92
+ Send JSON data with a `text` field:
93
+
94
+ ```bash
95
+ curl -X POST -H "Content-Type: application/json" \
96
+ -d '{"text":"今日はいい天気です"}' \
97
+ http://localhost:8888/
98
+ ```
99
+
100
+ #### GET Request
101
+
102
+ Pass text as a URL-encoded query parameter:
103
+
104
+ ```bash
105
+ curl "http://localhost:8888/?text=%E4%BB%8A%E6%97%A5%E3%81%AF%E3%81%84%E3%81%84%E5%A4%A9%E6%B0%97%E3%81%A7%E3%81%99"
106
+ ```
107
+
108
+ ### Response Format
109
+
110
+ The server returns JSON with the following structure:
111
+
112
+ ```json
113
+ {
114
+ "type": "doc",
115
+ "sents": [
116
+ {
117
+ "tokens": [
118
+ {
119
+ "i": 0,
120
+ "orth": "今日",
121
+ "tag": "名詞-普通名詞-副詞可能",
122
+ "pos": "NOUN",
123
+ "lemma": "今日",
124
+ "head.i": 3,
125
+ "dep": "obl"
126
+ },
127
+ ...
128
+ ]
129
+ }
130
+ ]
131
+ }
132
+ ```
133
+
134
+ **Token Fields:**
135
+ - `i`: Token index in the document
136
+ - `orth`: Original word form
137
+ - `tag`: Detailed part-of-speech tag
138
+ - `pos`: Universal part-of-speech tag
139
+ - `lemma`: Base form of the word
140
+ - `head.i`: Index of the syntactic head
141
+ - `dep`: Dependency relation
142
+
143
+ ## Client Example
144
+
145
+ A sample client is included in `examples/ginzaclient.py`:
146
+
147
+ ```python
148
+ import urllib.request
149
+ import json
150
+
151
+ url = 'http://localhost:8888'
152
+ method = 'POST'
153
+ headers = {'Content-Type': 'application/json'}
154
+
155
+ obj = {'text': '今日はいい天気です'}
156
+ requestbody = json.dumps(obj).encode('utf-8')
157
+
158
+ request = urllib.request.Request(url, data=requestbody, method=method, headers=headers)
159
+ with urllib.request.urlopen(request) as response:
160
+ response_body = response.read().decode('utf-8')
161
+ response = json.loads(response_body)
162
+ print(json.dumps(response, indent=2, ensure_ascii=False))
163
+ ```
164
+
165
+ ## Running as Python Script
166
+
167
+ You can also run the server directly as a Python script:
168
+
169
+ ```bash
170
+ python ginzaserver/ginzaserver.py 8888 0
171
+ ```
172
+
173
+ ## Performance Optimizations
174
+
175
+ Recent improvements include:
176
+
177
+ - ✅ List comprehensions for faster token processing
178
+ - ✅ Removed unnecessary `del` statements
179
+ - ✅ Direct JSON encoding without intermediate variables
180
+ - ✅ GPU acceleration support (automatically enabled if available)
181
+ - ✅ Removed unused imports
182
+
183
+ ## GPU Support
184
+
185
+ The server automatically detects and enables GPU acceleration if available:
186
+
187
+ ```python
188
+ if spacy.prefer_gpu():
189
+ spacy.require_gpu()
190
+ ```
191
+
192
+ For CUDA support, install the appropriate spaCy version:
193
+
194
+ ```bash
195
+ # For CUDA 11.5
196
+ pip install -U spacy[cuda115]
197
+ ```
198
+
199
+ ## Uninstallation
200
+
201
+ ```bash
202
+ pip uninstall ginzaserver
203
+ ```
204
+
205
+ ## Troubleshooting
206
+
207
+ ### Memory Issues
208
+
209
+ If the server is killed due to out-of-memory errors, check system logs:
210
+
211
+ ```bash
212
+ # Linux
213
+ dmesg -T | grep -E -i -B100 'killed process'
214
+
215
+ # Check available memory
216
+ free -h
217
+ ```
218
+
219
+ Consider using the `ja_ginza` model (option 0) instead of `ja_ginza_electra` if memory is limited.
220
+
221
+ ### WSL/Container Localhost Access
222
+
223
+ When running in WSL or containers, you may need to bind to `0.0.0.0` instead of `127.0.0.1` to accept external connections. Modify the `ip` variable in `ginzaserver.py` if needed.
224
+
225
+ ## License
226
+
227
+ Apache License 2.0
228
+
229
+ ## Author
230
+
231
+ Hiroki Oya (oyahiroki@gmail.com)
232
+
233
+ ## Links
234
+
235
+ - [GiNZA Official Documentation](https://megagonlabs.github.io/ginza/)
236
+ - [GitHub Repository](https://github.com/oyahiroki/ginzaserver)
237
+ - [spaCy Documentation](https://spacy.io/)
@@ -0,0 +1,211 @@
1
+ # ginzaserver
2
+
3
+ HTTP Server for GiNZA - Japanese NLP Library
4
+
5
+ A high-performance, multi-threaded HTTP server that provides REST API access to [GiNZA](https://megagonlabs.github.io/ginza/), a Japanese natural language processing library built on spaCy.
6
+
7
+ ## Features
8
+
9
+ - 🚀 **Multi-threaded server** using `ThreadingMixIn` for concurrent request handling
10
+ - 🎯 **Dual model support**: Choose between `ja_ginza` (fast) or `ja_ginza_electra` (accurate)
11
+ - 🔥 **GPU acceleration** support for enhanced performance
12
+ - 📊 **Performance optimized** with list comprehensions and efficient memory management
13
+ - 🌐 **REST API** with both GET and POST endpoints
14
+ - 📝 **JSON response format** with detailed token analysis
15
+
16
+ ## Installation
17
+
18
+ ### Prerequisites
19
+
20
+ Python 3.8 or higher is required.
21
+
22
+ ### Install GiNZA Models
23
+
24
+ Choose one or both models based on your needs:
25
+
26
+ ```bash
27
+ # Fast model (recommended for production)
28
+ pip install -U ginza ja_ginza
29
+
30
+ # Accurate model (higher memory usage, ~16GB RAM recommended)
31
+ pip install -U ginza ja_ginza_electra
32
+ ```
33
+
34
+ ### Install ginzaserver
35
+
36
+ Install directly from GitHub:
37
+
38
+ ```bash
39
+ pip install git+https://github.com/oyahiroki/ginzaserver
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ### Running the Server
45
+
46
+ ```bash
47
+ ginzaserver <port> <option>
48
+ ```
49
+
50
+ **Parameters:**
51
+ - `port`: Port number to listen on (e.g., 8888)
52
+ - `option`: Model selection
53
+ - `0`: Use `ja_ginza` (faster, 10-20ms per request)
54
+ - `1`: Use `ja_ginza_electra` (more accurate, 40-50ms per request)
55
+
56
+ **Example:**
57
+
58
+ ```bash
59
+ ginzaserver 8888 0
60
+ ```
61
+
62
+ ### API Endpoints
63
+
64
+ #### POST Request
65
+
66
+ Send JSON data with a `text` field:
67
+
68
+ ```bash
69
+ curl -X POST -H "Content-Type: application/json" \
70
+ -d '{"text":"今日はいい天気です"}' \
71
+ http://localhost:8888/
72
+ ```
73
+
74
+ #### GET Request
75
+
76
+ Pass text as a URL-encoded query parameter:
77
+
78
+ ```bash
79
+ curl "http://localhost:8888/?text=%E4%BB%8A%E6%97%A5%E3%81%AF%E3%81%84%E3%81%84%E5%A4%A9%E6%B0%97%E3%81%A7%E3%81%99"
80
+ ```
81
+
82
+ ### Response Format
83
+
84
+ The server returns JSON with the following structure:
85
+
86
+ ```json
87
+ {
88
+ "type": "doc",
89
+ "sents": [
90
+ {
91
+ "tokens": [
92
+ {
93
+ "i": 0,
94
+ "orth": "今日",
95
+ "tag": "名詞-普通名詞-副詞可能",
96
+ "pos": "NOUN",
97
+ "lemma": "今日",
98
+ "head.i": 3,
99
+ "dep": "obl"
100
+ },
101
+ ...
102
+ ]
103
+ }
104
+ ]
105
+ }
106
+ ```
107
+
108
+ **Token Fields:**
109
+ - `i`: Token index in the document
110
+ - `orth`: Original word form
111
+ - `tag`: Detailed part-of-speech tag
112
+ - `pos`: Universal part-of-speech tag
113
+ - `lemma`: Base form of the word
114
+ - `head.i`: Index of the syntactic head
115
+ - `dep`: Dependency relation
116
+
117
+ ## Client Example
118
+
119
+ A sample client is included in `examples/ginzaclient.py`:
120
+
121
+ ```python
122
+ import urllib.request
123
+ import json
124
+
125
+ url = 'http://localhost:8888'
126
+ method = 'POST'
127
+ headers = {'Content-Type': 'application/json'}
128
+
129
+ obj = {'text': '今日はいい天気です'}
130
+ requestbody = json.dumps(obj).encode('utf-8')
131
+
132
+ request = urllib.request.Request(url, data=requestbody, method=method, headers=headers)
133
+ with urllib.request.urlopen(request) as response:
134
+ response_body = response.read().decode('utf-8')
135
+ response = json.loads(response_body)
136
+ print(json.dumps(response, indent=2, ensure_ascii=False))
137
+ ```
138
+
139
+ ## Running as Python Script
140
+
141
+ You can also run the server directly as a Python script:
142
+
143
+ ```bash
144
+ python ginzaserver/ginzaserver.py 8888 0
145
+ ```
146
+
147
+ ## Performance Optimizations
148
+
149
+ Recent improvements include:
150
+
151
+ - ✅ List comprehensions for faster token processing
152
+ - ✅ Removed unnecessary `del` statements
153
+ - ✅ Direct JSON encoding without intermediate variables
154
+ - ✅ GPU acceleration support (automatically enabled if available)
155
+ - ✅ Removed unused imports
156
+
157
+ ## GPU Support
158
+
159
+ The server automatically detects and enables GPU acceleration if available:
160
+
161
+ ```python
162
+ if spacy.prefer_gpu():
163
+ spacy.require_gpu()
164
+ ```
165
+
166
+ For CUDA support, install the appropriate spaCy version:
167
+
168
+ ```bash
169
+ # For CUDA 11.5
170
+ pip install -U spacy[cuda115]
171
+ ```
172
+
173
+ ## Uninstallation
174
+
175
+ ```bash
176
+ pip uninstall ginzaserver
177
+ ```
178
+
179
+ ## Troubleshooting
180
+
181
+ ### Memory Issues
182
+
183
+ If the server is killed due to out-of-memory errors, check system logs:
184
+
185
+ ```bash
186
+ # Linux
187
+ dmesg -T | grep -E -i -B100 'killed process'
188
+
189
+ # Check available memory
190
+ free -h
191
+ ```
192
+
193
+ Consider using the `ja_ginza` model (option 0) instead of `ja_ginza_electra` if memory is limited.
194
+
195
+ ### WSL/Container Localhost Access
196
+
197
+ When running in WSL or containers, you may need to bind to `0.0.0.0` instead of `127.0.0.1` to accept external connections. Modify the `ip` variable in `ginzaserver.py` if needed.
198
+
199
+ ## License
200
+
201
+ Apache License 2.0
202
+
203
+ ## Author
204
+
205
+ Hiroki Oya (oyahiroki@gmail.com)
206
+
207
+ ## Links
208
+
209
+ - [GiNZA Official Documentation](https://megagonlabs.github.io/ginza/)
210
+ - [GitHub Repository](https://github.com/oyahiroki/ginzaserver)
211
+ - [spaCy Documentation](https://spacy.io/)
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,178 @@
1
+ # coding: utf-8
2
+
3
+ from http.server import HTTPServer
4
+ from http.server import BaseHTTPRequestHandler
5
+ from urllib.parse import urlparse
6
+ import urllib.parse
7
+
8
+ import spacy
9
+ import json
10
+ import traceback
11
+
12
+ from socketserver import ThreadingMixIn
13
+ import threading
14
+
15
+ import sys
16
+ import time
17
+
18
+ import datetime
19
+
20
+ import signal
21
+
22
+ def sig_handler(signum, frame) -> None:
23
+ sys.exit(1)
24
+
25
+ class GinzaHttpRequestHandler(BaseHTTPRequestHandler):
26
+
27
+ count = 0
28
+
29
+ def __init__(self, request, client_address, server):
30
+ # print("init request handler")
31
+ # self.nlp = spacy.load("ja_ginza")
32
+ BaseHTTPRequestHandler.__init__(self,request,client_address,server)
33
+
34
+ def log_message(self, format, *args):
35
+ pass
36
+
37
+ def myProcess(self, text):
38
+ GinzaHttpRequestHandler.count += 1
39
+ try:
40
+ time1 = time.time()
41
+ doc = self.nlp(text)
42
+
43
+ # リスト内包表記を使用してパフォーマンス向上
44
+ sents = [
45
+ {
46
+ "tokens": [
47
+ {
48
+ "i": token.i,
49
+ "orth": token.orth_,
50
+ "tag": token.tag_,
51
+ "pos": token.pos_,
52
+ "lemma": token.lemma_,
53
+ "head.i": token.head.i,
54
+ "dep": token.dep_
55
+ }
56
+ for token in sent
57
+ ]
58
+ }
59
+ for sent in doc.sents
60
+ ]
61
+
62
+ res = {
63
+ "type": "doc",
64
+ "sents": sents
65
+ }
66
+
67
+ self.send_response(200)
68
+ self.send_header("Content-type","application/json; charset=utf-8")
69
+ self.end_headers()
70
+ # 中間変数を削減してJSON直接エンコード
71
+ self.wfile.write(json.dumps(res).encode('utf-8'))
72
+ self.close_connection = True
73
+ time2 = time.time()
74
+ print( datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") + "," + "{:9}".format(GinzaHttpRequestHandler.count) + ", time=" + "{:6.2f}".format( (time2 - time1) * 1000 ) + ", text.length=" + str(len(text)) + ", text[0:8]=" + text[0:8])
75
+ return
76
+ except:
77
+ print(traceback.format_exc())
78
+ self.send_response(500)
79
+
80
+ def do_POST(self):
81
+ try:
82
+ # print(self.headers)
83
+ content_length = int(self.headers.get('content-length'))
84
+ requestbody = json.loads(self.rfile.read(content_length).decode('utf-8'))
85
+ text = requestbody.get('text')
86
+ self.myProcess(text)
87
+ # print('text: ' + text )
88
+ except Exception as e:
89
+ print(e)
90
+ self.send_response(500)
91
+ self.send_header('Content-type','application/json')
92
+ self.end_headers()
93
+ response = {}
94
+ responsebody = json.dumps(response)
95
+ self.wfile.write(responsebody.encode('utf-8'))
96
+
97
+
98
+ def do_GET(self):
99
+ query = urlparse(self.path).query
100
+ # print("query=" + query)
101
+
102
+ qs_d = urllib.parse.parse_qs(query)
103
+ # print(qs_d)
104
+ # print('has attribute text:' + str(hasattr(qs_d,"text")))
105
+ # print("text" in qs_d)
106
+ # check parameter
107
+ if ("text" in qs_d) == False:
108
+ self.send_response(404)
109
+ self.end_headers()
110
+ return
111
+
112
+ text = qs_d["text"][0]
113
+ # decode requested value
114
+ text = urllib.parse.unquote(text)
115
+ self.myProcess(text)
116
+
117
+ class GinzaHttpServer(ThreadingMixIn, HTTPServer):
118
+ def __init__(self, address, handlerClass=GinzaHttpRequestHandler, option=0):
119
+ print("init GinzaHttpServer")
120
+ # http://127.0.0.1:8888/?text=%E3%81%93%E3%82%8C%E3%81%AF%E3%83%86%E3%82%B9%E3%83%88%E3%81%A7%E3%81%99%E3%80%82
121
+ print("http://" + address[0] + ":" + str(address[1]) + "/?text=これはテストです。")
122
+ print("http://" + address[0] + ":" + str(address[1]) + "/?text=%E3%81%93%E3%82%8C%E3%81%AF%E3%83%86%E3%82%B9%E3%83%88%E3%81%A7%E3%81%99%E3%80%82")
123
+ print("curl -X POST -H \"Content-Type: application/json\" -d \"{\\\"text\\\":\\\"これはテストです。\\\"}\" http://" + address[0] + ":" + str(address[1]) + "/")
124
+
125
+ # 解析精度重視モデル (メモリ容量16GB以上を推奨)
126
+ # pip install -U ginza ja_ginza_electra
127
+ # 実行速度重視モデル
128
+ # pip install -U ginza ja_ginza
129
+ # handlerClass.nlp = spacy.load("ja_ginza") # 従来型モデル
130
+ # handlerClass.nlp = spacy.load("ja_ginza_electra") # ja_ginza_electra
131
+
132
+ # $ nvcc -V
133
+ # $ pip install -U spacy[cuda115]
134
+
135
+
136
+ # GPU サポートの有効化
137
+ if spacy.prefer_gpu():
138
+ spacy.require_gpu()
139
+ print("GPU enabled")
140
+
141
+ if (option == 1):
142
+ handlerClass.nlp = spacy.load("ja_ginza_electra") # ja_ginza_electra (40-50ms)
143
+ print("Running ja_ginza_electra")
144
+ else:
145
+ handlerClass.nlp = spacy.load("ja_ginza") # 従来型モデル (10-20ms)
146
+ print("Running ja_ginza")
147
+
148
+ super().__init__(address, handlerClass)
149
+
150
+ def main():
151
+ signal.signal(signal.SIGTERM, sig_handler)
152
+ ip = '127.0.0.1'
153
+ port = 8888
154
+ option = 0
155
+
156
+ args = sys.argv[1:]
157
+ if (len(args)!=2):
158
+ print("help: ginzaserver port_number option(0: use ja_ginza, 1: use ja_ginza_electra)")
159
+ print("example: ginzaserver 8888 0")
160
+ return
161
+ else:
162
+ port = int(args[0])
163
+ option = int(args[1])
164
+ if(option != 0 and option != 1):
165
+ print("option(0: use ja_ginza, 1: use ja_ginza_electra)");
166
+ return
167
+ # MEMO: WSL, Container からの localhost リクエストを受け付けるには工夫が必要
168
+ server = GinzaHttpServer((ip,port),GinzaHttpRequestHandler,option)
169
+ try:
170
+ server.serve_forever()
171
+ except KeyboardInterrupt:
172
+ pass
173
+ finally:
174
+ server.server_close()
175
+
176
+
177
+ if __name__ == '__main__':
178
+ main()
@@ -0,0 +1,237 @@
1
+ Metadata-Version: 2.4
2
+ Name: ginzaserver
3
+ Version: 0.1.0
4
+ Summary: HTTP Server for GiNZA - Japanese NLP Library
5
+ Home-page: https://github.com/oyahiroki/ginzaserver
6
+ Author: Hiroki Oya
7
+ Author-email: Hiroki Oya <oyahiroki@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ Project-URL: Homepage, https://github.com/oyahiroki/ginzaserver
10
+ Project-URL: Repository, https://github.com/oyahiroki/ginzaserver
11
+ Keywords: ginza,spacy,japanese,nlp,http-server
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: ginza>=5.2.0
16
+ Requires-Dist: ja-ginza
17
+ Provides-Extra: electra
18
+ Requires-Dist: ja-ginza-electra; extra == "electra"
19
+ Provides-Extra: dev
20
+ Requires-Dist: build; extra == "dev"
21
+ Requires-Dist: twine; extra == "dev"
22
+ Dynamic: author
23
+ Dynamic: home-page
24
+ Dynamic: license-file
25
+ Dynamic: requires-python
26
+
27
+ # ginzaserver
28
+
29
+ HTTP Server for GiNZA - Japanese NLP Library
30
+
31
+ A high-performance, multi-threaded HTTP server that provides REST API access to [GiNZA](https://megagonlabs.github.io/ginza/), a Japanese natural language processing library built on spaCy.
32
+
33
+ ## Features
34
+
35
+ - 🚀 **Multi-threaded server** using `ThreadingMixIn` for concurrent request handling
36
+ - 🎯 **Dual model support**: Choose between `ja_ginza` (fast) or `ja_ginza_electra` (accurate)
37
+ - 🔥 **GPU acceleration** support for enhanced performance
38
+ - 📊 **Performance optimized** with list comprehensions and efficient memory management
39
+ - 🌐 **REST API** with both GET and POST endpoints
40
+ - 📝 **JSON response format** with detailed token analysis
41
+
42
+ ## Installation
43
+
44
+ ### Prerequisites
45
+
46
+ Python 3.8 or higher is required.
47
+
48
+ ### Install GiNZA Models
49
+
50
+ Choose one or both models based on your needs:
51
+
52
+ ```bash
53
+ # Fast model (recommended for production)
54
+ pip install -U ginza ja_ginza
55
+
56
+ # Accurate model (higher memory usage, ~16GB RAM recommended)
57
+ pip install -U ginza ja_ginza_electra
58
+ ```
59
+
60
+ ### Install ginzaserver
61
+
62
+ Install directly from GitHub:
63
+
64
+ ```bash
65
+ pip install git+https://github.com/oyahiroki/ginzaserver
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ### Running the Server
71
+
72
+ ```bash
73
+ ginzaserver <port> <option>
74
+ ```
75
+
76
+ **Parameters:**
77
+ - `port`: Port number to listen on (e.g., 8888)
78
+ - `option`: Model selection
79
+ - `0`: Use `ja_ginza` (faster, 10-20ms per request)
80
+ - `1`: Use `ja_ginza_electra` (more accurate, 40-50ms per request)
81
+
82
+ **Example:**
83
+
84
+ ```bash
85
+ ginzaserver 8888 0
86
+ ```
87
+
88
+ ### API Endpoints
89
+
90
+ #### POST Request
91
+
92
+ Send JSON data with a `text` field:
93
+
94
+ ```bash
95
+ curl -X POST -H "Content-Type: application/json" \
96
+ -d '{"text":"今日はいい天気です"}' \
97
+ http://localhost:8888/
98
+ ```
99
+
100
+ #### GET Request
101
+
102
+ Pass text as a URL-encoded query parameter:
103
+
104
+ ```bash
105
+ curl "http://localhost:8888/?text=%E4%BB%8A%E6%97%A5%E3%81%AF%E3%81%84%E3%81%84%E5%A4%A9%E6%B0%97%E3%81%A7%E3%81%99"
106
+ ```
107
+
108
+ ### Response Format
109
+
110
+ The server returns JSON with the following structure:
111
+
112
+ ```json
113
+ {
114
+ "type": "doc",
115
+ "sents": [
116
+ {
117
+ "tokens": [
118
+ {
119
+ "i": 0,
120
+ "orth": "今日",
121
+ "tag": "名詞-普通名詞-副詞可能",
122
+ "pos": "NOUN",
123
+ "lemma": "今日",
124
+ "head.i": 3,
125
+ "dep": "obl"
126
+ },
127
+ ...
128
+ ]
129
+ }
130
+ ]
131
+ }
132
+ ```
133
+
134
+ **Token Fields:**
135
+ - `i`: Token index in the document
136
+ - `orth`: Original word form
137
+ - `tag`: Detailed part-of-speech tag
138
+ - `pos`: Universal part-of-speech tag
139
+ - `lemma`: Base form of the word
140
+ - `head.i`: Index of the syntactic head
141
+ - `dep`: Dependency relation
142
+
143
+ ## Client Example
144
+
145
+ A sample client is included in `examples/ginzaclient.py`:
146
+
147
+ ```python
148
+ import urllib.request
149
+ import json
150
+
151
+ url = 'http://localhost:8888'
152
+ method = 'POST'
153
+ headers = {'Content-Type': 'application/json'}
154
+
155
+ obj = {'text': '今日はいい天気です'}
156
+ requestbody = json.dumps(obj).encode('utf-8')
157
+
158
+ request = urllib.request.Request(url, data=requestbody, method=method, headers=headers)
159
+ with urllib.request.urlopen(request) as response:
160
+ response_body = response.read().decode('utf-8')
161
+ response = json.loads(response_body)
162
+ print(json.dumps(response, indent=2, ensure_ascii=False))
163
+ ```
164
+
165
+ ## Running as Python Script
166
+
167
+ You can also run the server directly as a Python script:
168
+
169
+ ```bash
170
+ python ginzaserver/ginzaserver.py 8888 0
171
+ ```
172
+
173
+ ## Performance Optimizations
174
+
175
+ Recent improvements include:
176
+
177
+ - ✅ List comprehensions for faster token processing
178
+ - ✅ Removed unnecessary `del` statements
179
+ - ✅ Direct JSON encoding without intermediate variables
180
+ - ✅ GPU acceleration support (automatically enabled if available)
181
+ - ✅ Removed unused imports
182
+
183
+ ## GPU Support
184
+
185
+ The server automatically detects and enables GPU acceleration if available:
186
+
187
+ ```python
188
+ if spacy.prefer_gpu():
189
+ spacy.require_gpu()
190
+ ```
191
+
192
+ For CUDA support, install the appropriate spaCy version:
193
+
194
+ ```bash
195
+ # For CUDA 11.5
196
+ pip install -U spacy[cuda115]
197
+ ```
198
+
199
+ ## Uninstallation
200
+
201
+ ```bash
202
+ pip uninstall ginzaserver
203
+ ```
204
+
205
+ ## Troubleshooting
206
+
207
+ ### Memory Issues
208
+
209
+ If the server is killed due to out-of-memory errors, check system logs:
210
+
211
+ ```bash
212
+ # Linux
213
+ dmesg -T | grep -E -i -B100 'killed process'
214
+
215
+ # Check available memory
216
+ free -h
217
+ ```
218
+
219
+ Consider using the `ja_ginza` model (option 0) instead of `ja_ginza_electra` if memory is limited.
220
+
221
+ ### WSL/Container Localhost Access
222
+
223
+ When running in WSL or containers, you may need to bind to `0.0.0.0` instead of `127.0.0.1` to accept external connections. Modify the `ip` variable in `ginzaserver.py` if needed.
224
+
225
+ ## License
226
+
227
+ Apache License 2.0
228
+
229
+ ## Author
230
+
231
+ Hiroki Oya (oyahiroki@gmail.com)
232
+
233
+ ## Links
234
+
235
+ - [GiNZA Official Documentation](https://megagonlabs.github.io/ginza/)
236
+ - [GitHub Repository](https://github.com/oyahiroki/ginzaserver)
237
+ - [spaCy Documentation](https://spacy.io/)
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ ginzaserver/__init__.py
6
+ ginzaserver/ginzaserver.py
7
+ ginzaserver.egg-info/PKG-INFO
8
+ ginzaserver.egg-info/SOURCES.txt
9
+ ginzaserver.egg-info/dependency_links.txt
10
+ ginzaserver.egg-info/entry_points.txt
11
+ ginzaserver.egg-info/requires.txt
12
+ ginzaserver.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ginzaserver = ginzaserver.ginzaserver:main
@@ -0,0 +1,9 @@
1
+ ginza>=5.2.0
2
+ ja-ginza
3
+
4
+ [dev]
5
+ build
6
+ twine
7
+
8
+ [electra]
9
+ ja-ginza-electra
@@ -0,0 +1 @@
1
+ ginzaserver
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ginzaserver"
7
+ version = "0.1.0"
8
+ description = "HTTP Server for GiNZA - Japanese NLP Library"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "Apache-2.0"
12
+
13
+ authors = [
14
+ { name = "Hiroki Oya", email = "oyahiroki@gmail.com" }
15
+ ]
16
+
17
+ keywords = [
18
+ "ginza",
19
+ "spacy",
20
+ "japanese",
21
+ "nlp",
22
+ "http-server"
23
+ ]
24
+
25
+ dependencies = [
26
+ "ginza >= 5.2.0",
27
+ "ja-ginza"
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ electra = [
32
+ "ja-ginza-electra"
33
+ ]
34
+
35
+ dev = [
36
+ "build",
37
+ "twine"
38
+ ]
39
+
40
+ [project.scripts]
41
+ ginzaserver = "ginzaserver.ginzaserver:main"
42
+
43
+ [project.urls]
44
+ Homepage = "https://github.com/oyahiroki/ginzaserver"
45
+ Repository = "https://github.com/oyahiroki/ginzaserver"
46
+
47
+ [tool.setuptools.packages.find]
48
+ where = ["."]
49
+ include = ["ginzaserver*"]
50
+ exclude = ["tests*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,25 @@
1
+ import setuptools
2
+
3
+ with open("README.md", "r") as fh:
4
+ long_description = fh.read()
5
+
6
+ setuptools.setup(
7
+ name="ginzaserver",
8
+ version="1.0.0.0",
9
+ author="Hiroki Oya",
10
+ author_email="oyahiroki@gmail.com",
11
+ description="HTTP Server for GiNZA - Japanese NLP Library",
12
+ long_description=long_description,
13
+ long_description_content_type="text/markdown",
14
+ url="https://github.com/oyahiroki/ginzaserver",
15
+ packages=setuptools.find_packages(),
16
+ license='Apache License 2.0',
17
+ classifiers=[
18
+ "Programming Language :: Python :: 3",
19
+ "Operating System :: OS Independent",
20
+ ],
21
+ entry_points = {
22
+ 'console_scripts': ['ginzaserver = ginzaserver.ginzaserver:main']
23
+ },
24
+ python_requires='>=3.8',
25
+ )