temporal-normalization-spacy 2.2.2__tar.gz → 2.4.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.
Files changed (23) hide show
  1. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/MANIFEST.in +1 -1
  2. {temporal_normalization_spacy-2.2.2/temporal_normalization_spacy.egg-info → temporal_normalization_spacy-2.4.0}/PKG-INFO +26 -24
  3. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/README.md +23 -23
  4. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/setup.py +3 -2
  5. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/index.py +9 -1
  6. temporal_normalization_spacy-2.2.2/temporal_normalization/libs/temporal-normalization-2.1.0.jar → temporal_normalization_spacy-2.4.0/temporal_normalization/libs/temporal-normalization-2.2.1.jar +0 -0
  7. temporal_normalization_spacy-2.4.0/temporal_normalization/process/java_process.py +346 -0
  8. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0/temporal_normalization_spacy.egg-info}/PKG-INFO +26 -24
  9. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization_spacy.egg-info/SOURCES.txt +1 -1
  10. temporal_normalization_spacy-2.2.2/temporal_normalization/process/java_process.py +0 -176
  11. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/LICENSE +0 -0
  12. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/setup.cfg +0 -0
  13. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/__init__.py +0 -0
  14. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/commons/__init__.py +0 -0
  15. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/commons/print_utils.py +0 -0
  16. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/commons/temporal_models.py +0 -0
  17. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/commons/temporal_types.py +0 -0
  18. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/factory.py +0 -0
  19. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization/process/__init__.py +0 -0
  20. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization_spacy.egg-info/dependency_links.txt +0 -0
  21. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization_spacy.egg-info/entry_points.txt +0 -0
  22. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization_spacy.egg-info/requires.txt +0 -0
  23. {temporal_normalization_spacy-2.2.2 → temporal_normalization_spacy-2.4.0}/temporal_normalization_spacy.egg-info/top_level.txt +0 -0
@@ -1,5 +1,5 @@
1
1
  include README.md
2
- include temporal_normalization/libs/temporal-normalization-2.1.0.jar
2
+ include temporal_normalization/libs/temporal-normalization-2.2.1.jar
3
3
 
4
4
  recursive-include temporal_normalizer/commons *
5
5
  recursive-include temporal_normalizer/libs *
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: temporal_normalization_spacy
3
- Version: 2.2.2
3
+ Version: 2.4.0
4
4
  Summary: A spaCy plugin for temporal normalization and extraction of historical dates in Romanian narrative texts.
5
5
  Home-page: https://github.com/iliedorobat/timespan-normalization-spacy
6
6
  Author: Ilie Cristian Dorobat
7
+ Author-email: ic.dorobat@gmail.com
7
8
  Keywords: spacy,nlp,temporal normalization,timex,historical dates,romanian
8
9
  Classifier: Programming Language :: Python :: 3
9
10
  Classifier: Programming Language :: Python :: 3.9
@@ -19,6 +20,7 @@ Requires-Dist: spacy<4.0.0,>=3.8.7
19
20
  Requires-Dist: py4j>=0.10.9.9
20
21
  Requires-Dist: langdetect>=1.0.9
21
22
  Dynamic: author
23
+ Dynamic: author-email
22
24
  Dynamic: classifier
23
25
  Dynamic: description
24
26
  Dynamic: description-content-type
@@ -54,7 +56,7 @@ quality and reliability of date-related information extracted from text.
54
56
  <th>Examples of Temporal Expressions*</th>
55
57
  </tr>
56
58
  <tr>
57
- <td>dates</td>
59
+ <td>DATE</td>
58
60
  <td>
59
61
  YMD: 1881-08-31; 1857 mai 10; etc.<br/>
60
62
  DMY: 09.11.1518; 1 noiembrie 1624; etc.<br/>
@@ -62,15 +64,16 @@ quality and reliability of date-related information extracted from text.
62
64
  </td>
63
65
  </tr>
64
66
  <tr>
65
- <td>timespans</td>
66
- <td>
67
- centuries: s:; sc; se.; sec; sec.; secol; secolele; secolul; sex.<br/>
68
- millenniums: mil; mil.; mileniul; mileniului; mileniile
69
- </td>
67
+ <td>YEAR</td>
68
+ <td>1534; (1)931; [1833]; aproximativ 1834; cca. 1420; etc.</td>
69
+ </tr>
70
+ <tr>
71
+ <td>CENTURY</td>
72
+ <td>s: xviii; sec ii p.chr.; secol xix; secolele ii-iii; etc.</td>
70
73
  </tr>
71
74
  <tr>
72
- <td>years</td>
73
- <td>77; 78; 1652; [1873]; aproximativ 1834; cca. 1420; etc.</td>
75
+ <td>MILLENNIUM</td>
76
+ <td>mil iii; mil. 5 a.chr.; mileniul v a.chr.; a mileniului v a.chr.; etc.</td>
74
77
  </tr>
75
78
  </table>
76
79
  * The values are mentioned in the reference language – Romanian language
@@ -78,12 +81,11 @@ quality and reliability of date-related information extracted from text.
78
81
 
79
82
 
80
83
  ## Getting started
81
- To integrate TeNs into spaCy pipelines you need the following:
82
84
 
83
85
  ### Prerequisites
84
86
  - Python 3.9-3.12
85
87
  - JRE 11-17
86
- - spaCy 3.x
88
+ - spaCy >=3.8.7,<4.0.0
87
89
  - py4j 0.10.9.9
88
90
  - langdetect 1.0.9
89
91
 
@@ -109,7 +111,7 @@ import spacy
109
111
  from temporal_normalization.commons.print_utils import console
110
112
 
111
113
  LANG = "ro"
112
- MODEL = "ro_core_news_sm"
114
+ MODEL = "ro_core_news_sm "
113
115
  TEXT_RO = ("Sec al II-lea a.ch. a fost o perioadă de mari schimbări. "
114
116
  "În secolul XX, tehnologia a avansat semnificativ. "
115
117
  "Sec. 21 este adesea asociat cu globalizarea rapidă.")
@@ -233,24 +235,24 @@ Start Edge:
233
235
  Matched value: Sec al II-lea a.ch.
234
236
  Matched Type: century
235
237
  Normalized label: 2nd century BC
236
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
238
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
237
239
 
238
240
  End Edge:
239
241
  Matched value: Sec al II-lea a.ch.
240
242
  Matched Type: century
241
243
  Normalized label: 2nd century BC
242
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
244
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
243
245
 
244
246
  Periods:
245
247
  Matched value: Sec al II-lea a.ch.
246
248
  Matched Type: century
247
249
  Normalized label: 1st millennium BC
248
- DBpedia uri: https://dbpedia.org/page/1st_millennium_BC
250
+ DBpedia uri: https://dbpedia.org/resource/1st_millennium_BC
249
251
 
250
252
  Matched value: Sec al II-lea a.ch.
251
253
  Matched Type: century
252
254
  Normalized label: 2nd century BC
253
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
255
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
254
256
  ```
255
257
 
256
258
  ### Second Sentence
@@ -259,24 +261,24 @@ Start Edge:
259
261
  Matched value: secolul XX
260
262
  Matched Type: century
261
263
  Normalized label: 20th century
262
- DBpedia uri: https://dbpedia.org/page/20th_century
264
+ DBpedia uri: https://dbpedia.org/resource/20th_century
263
265
 
264
266
  End Edge:
265
267
  Matched value: secolul XX
266
268
  Matched Type: century
267
269
  Normalized label: 20th century
268
- DBpedia uri: https://dbpedia.org/page/20th_century
270
+ DBpedia uri: https://dbpedia.org/resource/20th_century
269
271
 
270
272
  Periods:
271
273
  Matched value: secolul XX
272
274
  Matched Type: century
273
275
  Normalized label: 2nd millennium
274
- DBpedia uri: https://dbpedia.org/page/2nd_millennium
276
+ DBpedia uri: https://dbpedia.org/resource/2nd_millennium
275
277
 
276
278
  Matched value: secolul XX
277
279
  Matched Type: century
278
280
  Normalized label: 20th century
279
- DBpedia uri: https://dbpedia.org/page/20th_century
281
+ DBpedia uri: https://dbpedia.org/resource/20th_century
280
282
  ```
281
283
 
282
284
  ### Third Sentence
@@ -285,24 +287,24 @@ Start Edge:
285
287
  Matched value: Sec. 21
286
288
  Matched Type: century
287
289
  Normalized label: 21st century
288
- DBpedia uri: https://dbpedia.org/page/21st_century
290
+ DBpedia uri: https://dbpedia.org/resource/21st_century
289
291
 
290
292
  End Edge:
291
293
  Matched value: Sec. 21
292
294
  Matched Type: century
293
295
  Normalized label: 21st century
294
- DBpedia uri: https://dbpedia.org/page/21st_century
296
+ DBpedia uri: https://dbpedia.org/resource/21st_century
295
297
 
296
298
  Periods:
297
299
  Matched value: Sec. 21
298
300
  Matched Type: century
299
301
  Normalized label: 3rd millennium
300
- DBpedia uri: https://dbpedia.org/page/3rd_millennium
302
+ DBpedia uri: https://dbpedia.org/resource/3rd_millennium
301
303
 
302
304
  Matched value: Sec. 21
303
305
  Matched Type: century
304
306
  Normalized label: 21st century
305
- DBpedia uri: https://dbpedia.org/page/21st_century
307
+ DBpedia uri: https://dbpedia.org/resource/21st_century
306
308
  ```
307
309
 
308
310
 
@@ -23,7 +23,7 @@ quality and reliability of date-related information extracted from text.
23
23
  <th>Examples of Temporal Expressions*</th>
24
24
  </tr>
25
25
  <tr>
26
- <td>dates</td>
26
+ <td>DATE</td>
27
27
  <td>
28
28
  YMD: 1881-08-31; 1857 mai 10; etc.<br/>
29
29
  DMY: 09.11.1518; 1 noiembrie 1624; etc.<br/>
@@ -31,15 +31,16 @@ quality and reliability of date-related information extracted from text.
31
31
  </td>
32
32
  </tr>
33
33
  <tr>
34
- <td>timespans</td>
35
- <td>
36
- centuries: s:; sc; se.; sec; sec.; secol; secolele; secolul; sex.<br/>
37
- millenniums: mil; mil.; mileniul; mileniului; mileniile
38
- </td>
34
+ <td>YEAR</td>
35
+ <td>1534; (1)931; [1833]; aproximativ 1834; cca. 1420; etc.</td>
36
+ </tr>
37
+ <tr>
38
+ <td>CENTURY</td>
39
+ <td>s: xviii; sec ii p.chr.; secol xix; secolele ii-iii; etc.</td>
39
40
  </tr>
40
41
  <tr>
41
- <td>years</td>
42
- <td>77; 78; 1652; [1873]; aproximativ 1834; cca. 1420; etc.</td>
42
+ <td>MILLENNIUM</td>
43
+ <td>mil iii; mil. 5 a.chr.; mileniul v a.chr.; a mileniului v a.chr.; etc.</td>
43
44
  </tr>
44
45
  </table>
45
46
  * The values are mentioned in the reference language – Romanian language
@@ -47,12 +48,11 @@ quality and reliability of date-related information extracted from text.
47
48
 
48
49
 
49
50
  ## Getting started
50
- To integrate TeNs into spaCy pipelines you need the following:
51
51
 
52
52
  ### Prerequisites
53
53
  - Python 3.9-3.12
54
54
  - JRE 11-17
55
- - spaCy 3.x
55
+ - spaCy >=3.8.7,<4.0.0
56
56
  - py4j 0.10.9.9
57
57
  - langdetect 1.0.9
58
58
 
@@ -78,7 +78,7 @@ import spacy
78
78
  from temporal_normalization.commons.print_utils import console
79
79
 
80
80
  LANG = "ro"
81
- MODEL = "ro_core_news_sm"
81
+ MODEL = "ro_core_news_sm "
82
82
  TEXT_RO = ("Sec al II-lea a.ch. a fost o perioadă de mari schimbări. "
83
83
  "În secolul XX, tehnologia a avansat semnificativ. "
84
84
  "Sec. 21 este adesea asociat cu globalizarea rapidă.")
@@ -202,24 +202,24 @@ Start Edge:
202
202
  Matched value: Sec al II-lea a.ch.
203
203
  Matched Type: century
204
204
  Normalized label: 2nd century BC
205
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
205
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
206
206
 
207
207
  End Edge:
208
208
  Matched value: Sec al II-lea a.ch.
209
209
  Matched Type: century
210
210
  Normalized label: 2nd century BC
211
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
211
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
212
212
 
213
213
  Periods:
214
214
  Matched value: Sec al II-lea a.ch.
215
215
  Matched Type: century
216
216
  Normalized label: 1st millennium BC
217
- DBpedia uri: https://dbpedia.org/page/1st_millennium_BC
217
+ DBpedia uri: https://dbpedia.org/resource/1st_millennium_BC
218
218
 
219
219
  Matched value: Sec al II-lea a.ch.
220
220
  Matched Type: century
221
221
  Normalized label: 2nd century BC
222
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
222
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
223
223
  ```
224
224
 
225
225
  ### Second Sentence
@@ -228,24 +228,24 @@ Start Edge:
228
228
  Matched value: secolul XX
229
229
  Matched Type: century
230
230
  Normalized label: 20th century
231
- DBpedia uri: https://dbpedia.org/page/20th_century
231
+ DBpedia uri: https://dbpedia.org/resource/20th_century
232
232
 
233
233
  End Edge:
234
234
  Matched value: secolul XX
235
235
  Matched Type: century
236
236
  Normalized label: 20th century
237
- DBpedia uri: https://dbpedia.org/page/20th_century
237
+ DBpedia uri: https://dbpedia.org/resource/20th_century
238
238
 
239
239
  Periods:
240
240
  Matched value: secolul XX
241
241
  Matched Type: century
242
242
  Normalized label: 2nd millennium
243
- DBpedia uri: https://dbpedia.org/page/2nd_millennium
243
+ DBpedia uri: https://dbpedia.org/resource/2nd_millennium
244
244
 
245
245
  Matched value: secolul XX
246
246
  Matched Type: century
247
247
  Normalized label: 20th century
248
- DBpedia uri: https://dbpedia.org/page/20th_century
248
+ DBpedia uri: https://dbpedia.org/resource/20th_century
249
249
  ```
250
250
 
251
251
  ### Third Sentence
@@ -254,24 +254,24 @@ Start Edge:
254
254
  Matched value: Sec. 21
255
255
  Matched Type: century
256
256
  Normalized label: 21st century
257
- DBpedia uri: https://dbpedia.org/page/21st_century
257
+ DBpedia uri: https://dbpedia.org/resource/21st_century
258
258
 
259
259
  End Edge:
260
260
  Matched value: Sec. 21
261
261
  Matched Type: century
262
262
  Normalized label: 21st century
263
- DBpedia uri: https://dbpedia.org/page/21st_century
263
+ DBpedia uri: https://dbpedia.org/resource/21st_century
264
264
 
265
265
  Periods:
266
266
  Matched value: Sec. 21
267
267
  Matched Type: century
268
268
  Normalized label: 3rd millennium
269
- DBpedia uri: https://dbpedia.org/page/3rd_millennium
269
+ DBpedia uri: https://dbpedia.org/resource/3rd_millennium
270
270
 
271
271
  Matched value: Sec. 21
272
272
  Matched Type: century
273
273
  Normalized label: 21st century
274
- DBpedia uri: https://dbpedia.org/page/21st_century
274
+ DBpedia uri: https://dbpedia.org/resource/21st_century
275
275
  ```
276
276
 
277
277
 
@@ -2,8 +2,9 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="temporal_normalization_spacy",
5
- version="2.2.2",
5
+ version="2.4.0",
6
6
  author="Ilie Cristian Dorobat",
7
+ author_email="ic.dorobat@gmail.com",
7
8
  description="A spaCy plugin for temporal normalization and extraction of "
8
9
  "historical dates in Romanian narrative texts.",
9
10
  keywords="spacy, nlp, temporal normalization, timex, historical dates, romanian",
@@ -18,7 +19,7 @@ setup(
18
19
  ],
19
20
  },
20
21
  package_data={
21
- "temporal_normalization.libs": ["temporal-normalization-2.1.0.jar"],
22
+ "temporal_normalization.libs": ["temporal-normalization-2.2.1.jar"],
22
23
  },
23
24
  install_requires=[
24
25
  "spacy>=3.8.7,<4.0.0",
@@ -43,6 +43,11 @@ class TemporalNormalization:
43
43
  self.nlp = nlp
44
44
  self.count = 0
45
45
 
46
+ # Initialize connection attributes before starting the Java gateway, as initialization may fail
47
+ # (e.g., during Flask's debug reloader), and __del__() may still be called on a partial instance.
48
+ self.java_process = None
49
+ self.gateway = None
50
+
46
51
  root_path = str(Path(__file__).resolve().parent.parent)
47
52
  java_process, gateway = start_conn(root_path)
48
53
  self.java_process: subprocess.Popen = java_process
@@ -97,7 +102,10 @@ class TemporalNormalization:
97
102
  network sockets that might otherwise persist after the Python process ends.
98
103
  """
99
104
 
100
- close_conn(self.java_process, self.gateway)
105
+ if self.java_process is not None or self.gateway is not None:
106
+ close_conn(self.java_process, self.gateway)
107
+ else:
108
+ print(f"⚠️ No Java process or Python connection to close.")
101
109
 
102
110
 
103
111
  def _prepare_str_patterns(expressions: list[TemporalExpression]) -> list[str]:
@@ -0,0 +1,346 @@
1
+ import io
2
+ import random
3
+ import re
4
+ import shutil
5
+ import socket
6
+ import subprocess
7
+ import threading
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from py4j.java_gateway import JavaGateway, GatewayParameters
12
+ from py4j.protocol import Py4JNetworkError
13
+
14
+ from temporal_normalization.commons.print_utils import console
15
+
16
+
17
+ _DEFAULT_GATEWAY_PORT = 25333
18
+
19
+
20
+ def start_conn(root_path: str, max_attempts: int = 10, timeout: float = 10.0) -> tuple[subprocess.Popen, JavaGateway]:
21
+ """
22
+ Starts the Java temporal normalization process and establishes a Py4J gateway connection.
23
+
24
+ Args:
25
+ root_path (str): The root directory of the project.
26
+ max_attempts (int): Maximum number of retry attempts if port binding fails.
27
+ timeout (float): Maximum time to wait for gateway initialization (default: 10 seconds).
28
+
29
+ Returns:
30
+ tuple[subprocess.Popen, JavaGateway]:
31
+ - The subprocess.Popen object representing the running Java process.
32
+ - The JavaGateway object representing the active Py4J connection.
33
+
34
+ Note:
35
+ - Requires Java 11 or higher to be installed and accessible in the system PATH.
36
+ - Requires `temporal-normalization-2.2.1.jar` to be present in the `libs` directory.
37
+ - The caller is responsible for closing the gateway and terminating the Java process
38
+ after usage to avoid orphaned processes.
39
+ - Will automatically retry with cleanup if port binding fails.
40
+ """
41
+
42
+ check_java_version()
43
+
44
+ jar_path = (
45
+ # f"{root_path}/temporal_normalization/libs/temporal-normalization-1.7-patch1.jar"
46
+ f"{root_path}/temporal_normalization/libs/temporal-normalization-2.2.1.jar"
47
+ )
48
+
49
+ if not Path(jar_path):
50
+ raise RuntimeError(f"JAR file not found at {jar_path}")
51
+
52
+ gateway_port = _find_available_port(max_attempts=max_attempts)
53
+ print(f"Starting Java Gateway on port {gateway_port}")
54
+
55
+ gateway_started = threading.Event()
56
+ gateway_error = threading.Event()
57
+
58
+ def stdout_callback(line: str):
59
+ startup_indicators = [
60
+ "gateway server successfully started", # temporal-normalization-2.2.1.jar
61
+ "gateway server started", # temporal-normalization-1.7-patch1.jar
62
+ ]
63
+ if any(indicator in line.lower() for indicator in startup_indicators):
64
+ gateway_started.set()
65
+ print(line.strip())
66
+
67
+ stderr_lines = []
68
+ def stderr_callback(line: str):
69
+ stderr_lines.append(line)
70
+
71
+ if "Failed to bind" in line or "Address already in use" in line:
72
+ gateway_error.set()
73
+
74
+ java_process = subprocess.Popen(
75
+ ["java", "-jar", jar_path, "--python", f"--gateway-port={gateway_port}"],
76
+ stdout=subprocess.PIPE,
77
+ stderr=subprocess.PIPE,
78
+ text=True,
79
+ )
80
+
81
+ threading.Thread(target=drain_stream, args=(java_process.stdout, stdout_callback), daemon=True).start()
82
+ threading.Thread(target=drain_stream, args=(java_process.stderr, stderr_callback), daemon=True).start()
83
+
84
+ start_time = time.monotonic()
85
+
86
+ while not gateway_started.is_set():
87
+ if gateway_error.wait(timeout=0.1):
88
+ error = "\n\t".join(stderr_lines)
89
+
90
+ if java_process.poll() is None:
91
+ java_process.terminate()
92
+ java_process.wait(timeout=5)
93
+
94
+ raise RuntimeError(
95
+ "Java Gateway failed to start.\n"
96
+ f"Java stderr:\n\t{error}"
97
+ )
98
+
99
+ if time.monotonic() - start_time >= timeout:
100
+ error = "\n\t".join(stderr_lines)
101
+
102
+ java_process.terminate()
103
+ java_process.wait()
104
+
105
+ raise RuntimeError(
106
+ f"Java Gateway did not start within {timeout} seconds.\n"
107
+ f"Java stderr:\n\t{error}"
108
+ )
109
+
110
+ time.sleep(0.1)
111
+
112
+ gateway = JavaGateway(
113
+ gateway_parameters=GatewayParameters(
114
+ address="127.0.0.1",
115
+ port=gateway_port,
116
+ auto_convert=True,
117
+ read_timeout=None,
118
+ eager_load=True,
119
+ ),
120
+ callback_server_parameters=None,
121
+ )
122
+
123
+ print("✅ Python connection established.")
124
+
125
+ return java_process, gateway
126
+
127
+
128
+ def close_conn(java_process: subprocess.Popen | None, gateway: JavaGateway | None) -> None:
129
+ """
130
+ Closes the Py4J gateway connection and terminates the associated Java process.
131
+
132
+ This function performs the shutdown sequence by:
133
+ 1. Attempting to gracefully close the Py4J gateway connection.
134
+ - If the Java process has already terminated, the resulting
135
+ Py4JNetworkError is handled without raising an exception.
136
+ 2. Terminating the Java process if it is still running.
137
+ 3. Reporting the shutdown status for each resource.
138
+
139
+ Args:
140
+ java_process (subprocess.Popen | None): The Java process launched
141
+ with subprocess, or None if the process was not successfully
142
+ initialized.
143
+ gateway (JavaGateway | None): The active Py4J gateway connection,
144
+ or None if the gateway was not successfully initialized.
145
+
146
+ Notes:
147
+ - Call this function once all interactions with the Java process
148
+ have been completed.
149
+ - It is safe to call even if either the gateway or Java process
150
+ has already been closed or was not successfully initialized.
151
+ - The Py4J gateway is closed before the Java process is terminated.
152
+ """
153
+
154
+ _close_gateway_conn(gateway)
155
+ _close_java_conn(java_process)
156
+
157
+
158
+ def _close_gateway_conn(gateway: JavaGateway | None) -> None:
159
+ """
160
+ Closes the active Py4J gateway connection, if one exists.
161
+
162
+ Attempts to gracefully shut down the connection between Python and
163
+ the Java process. If the Java process has already terminated, the
164
+ resulting Py4JNetworkError is handled and reported without raising
165
+ an exception.
166
+
167
+ Args:
168
+ gateway (JavaGateway | None): The active Py4J gateway connection,
169
+ or None if the connection was not successfully initialized.
170
+
171
+ Notes:
172
+ - It is safe to call this function when the gateway is None.
173
+ - It is safe to call this function after the Java process has
174
+ already terminated.
175
+ - Unexpected errors during gateway shutdown are caught and
176
+ reported rather than propagated.
177
+ """
178
+
179
+ if gateway is not None:
180
+ try:
181
+ # Proper way to shut down Py4J
182
+ gateway.shutdown()
183
+ print("✅ Python connection closed.")
184
+ except Py4JNetworkError:
185
+ print("⚠️ Java process already shut down.")
186
+ except Exception as e:
187
+ print(f"⚠️ Error shutting down gateway: {e}")
188
+ else:
189
+ print(f"⚠️ No Python connection to close.")
190
+
191
+
192
+ def _close_java_conn(java_process: subprocess.Popen | None) -> None:
193
+ """
194
+ Terminates the Java process, if it is still running.
195
+
196
+ Checks whether the Java process is active before attempting to
197
+ terminate it. If the process has already exited, no termination
198
+ is attempted and a status message is printed.
199
+
200
+ Args:
201
+ java_process (subprocess.Popen | None): The Java process started
202
+ with subprocess, or None if the process was not successfully
203
+ initialized.
204
+
205
+ Notes:
206
+ - It is safe to call this function when java_process is None.
207
+ - It is safe to call this function after the Java process has
208
+ already terminated.
209
+ - If the process is still running, terminate() is called and the
210
+ function waits for the process to exit.
211
+ """
212
+
213
+ if java_process is None:
214
+ print("⚠️ No Java process to close.")
215
+ return
216
+
217
+ if java_process.poll() is None:
218
+ # Terminate Java process
219
+ java_process.terminate()
220
+ java_process.wait()
221
+ print("✅ Java process terminated.")
222
+ else:
223
+ print("⚠️ Java process already terminated.")
224
+
225
+
226
+ def drain_stream(stream: io.TextIOBase, callback=None) -> None:
227
+ """
228
+ Consumes the output from a given stream until a specific marker is found,
229
+ then closes the stream.
230
+
231
+ This function is typically used to monitor the stdout or stderr of a subprocess
232
+ (e.g., a Java process started from Python) and detect when a certain event occurs,
233
+ such as the initialization of a gateway server. Once the marker line is encountered,
234
+ the function prints it (or logs it) and terminates the stream reading.
235
+
236
+ Args:
237
+ stream (io.TextIOBase): A text-based stream object to read from, usually
238
+ subprocess.stdout or subprocess.stderr.
239
+ callback (callable, optional): A function that takes a single string argument (line).
240
+ It will be called for every line read from the stream.
241
+ Useful for detecting specific markers, logging, or
242
+ triggering events when certain output appears.
243
+
244
+ Raises:
245
+ AttributeError: If the provided `stream` does not have `readline` or `close` methods.
246
+ """
247
+
248
+ for line in iter(stream.readline, ""):
249
+ line = line.strip()
250
+ if callback:
251
+ callback(line)
252
+
253
+ stream.close()
254
+
255
+
256
+ def check_java_version() -> None:
257
+ """
258
+ Verifies that Java is installed and meets the minimum required version.
259
+
260
+ This function checks for the presence of the Java executable in the system PATH,
261
+ runs ``java -version``, and ensures that the version is at least 11. If Java is not
262
+ installed or the version is too low, it logs an error using ``console.error``.
263
+
264
+ Raises:
265
+ Logs error messages, but does not raise exceptions directly.
266
+ """
267
+
268
+ min_version = 11
269
+ java_path = shutil.which("java")
270
+
271
+ try:
272
+ if java_path:
273
+ # Run the command to check the Java version
274
+ result = subprocess.run(
275
+ [java_path, "-version"], capture_output=True, text=True
276
+ )
277
+
278
+ # Print the version information (Java version is printed to stderr)
279
+ if result.returncode == 0:
280
+ version_output = result.stderr
281
+ match = re.search(r'version "(\d+\.\d+)', version_output)
282
+
283
+ if match:
284
+ crr_version = float(match.group(1))
285
+ if crr_version < min_version:
286
+ console.error(
287
+ f"Java {crr_version} is installed, but version {min_version} is required." # noqa 501
288
+ )
289
+ else:
290
+ console.error("Could not extract Java version.")
291
+ else:
292
+ console.error("Error occurred while checking the version.")
293
+ else:
294
+ console.error("Java not found.")
295
+ except Exception as e:
296
+ console.error(e.__str__())
297
+
298
+
299
+ def _is_port_available(port: int) -> bool:
300
+ """
301
+ Check if a given port is available for binding.
302
+
303
+ Args:
304
+ port (int): The port number to check.
305
+
306
+ Returns:
307
+ bool: True if the port is available, False otherwise.
308
+ """
309
+ try:
310
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
311
+ s.bind(('127.0.0.1', port))
312
+ return True
313
+ except OSError:
314
+ return False
315
+
316
+
317
+ def _find_available_port(start_port: int = _DEFAULT_GATEWAY_PORT, max_attempts: int = 10) -> int:
318
+ """
319
+ Find an available port starting from the given port number.
320
+
321
+ Args:
322
+ start_port (int): The initial port to try.
323
+ max_attempts (int): Maximum number of ports to check.
324
+
325
+ Returns:
326
+ int: An available port number.
327
+
328
+ Raises:
329
+ RuntimeError: If no available port is found within max_attempts.
330
+ """
331
+ for offset in range(max_attempts):
332
+ port = start_port + offset
333
+ if _is_port_available(port):
334
+ return port
335
+
336
+ # If sequential search fails, try random ports
337
+ for _ in range(max_attempts):
338
+ port = random.randint(_DEFAULT_GATEWAY_PORT, 35333)
339
+ if _is_port_available(port):
340
+ return port
341
+
342
+ raise RuntimeError(f"Could not find an available port after {max_attempts * 2} attempts")
343
+
344
+
345
+ if __name__ == "__main__":
346
+ pass
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: temporal_normalization_spacy
3
- Version: 2.2.2
3
+ Version: 2.4.0
4
4
  Summary: A spaCy plugin for temporal normalization and extraction of historical dates in Romanian narrative texts.
5
5
  Home-page: https://github.com/iliedorobat/timespan-normalization-spacy
6
6
  Author: Ilie Cristian Dorobat
7
+ Author-email: ic.dorobat@gmail.com
7
8
  Keywords: spacy,nlp,temporal normalization,timex,historical dates,romanian
8
9
  Classifier: Programming Language :: Python :: 3
9
10
  Classifier: Programming Language :: Python :: 3.9
@@ -19,6 +20,7 @@ Requires-Dist: spacy<4.0.0,>=3.8.7
19
20
  Requires-Dist: py4j>=0.10.9.9
20
21
  Requires-Dist: langdetect>=1.0.9
21
22
  Dynamic: author
23
+ Dynamic: author-email
22
24
  Dynamic: classifier
23
25
  Dynamic: description
24
26
  Dynamic: description-content-type
@@ -54,7 +56,7 @@ quality and reliability of date-related information extracted from text.
54
56
  <th>Examples of Temporal Expressions*</th>
55
57
  </tr>
56
58
  <tr>
57
- <td>dates</td>
59
+ <td>DATE</td>
58
60
  <td>
59
61
  YMD: 1881-08-31; 1857 mai 10; etc.<br/>
60
62
  DMY: 09.11.1518; 1 noiembrie 1624; etc.<br/>
@@ -62,15 +64,16 @@ quality and reliability of date-related information extracted from text.
62
64
  </td>
63
65
  </tr>
64
66
  <tr>
65
- <td>timespans</td>
66
- <td>
67
- centuries: s:; sc; se.; sec; sec.; secol; secolele; secolul; sex.<br/>
68
- millenniums: mil; mil.; mileniul; mileniului; mileniile
69
- </td>
67
+ <td>YEAR</td>
68
+ <td>1534; (1)931; [1833]; aproximativ 1834; cca. 1420; etc.</td>
69
+ </tr>
70
+ <tr>
71
+ <td>CENTURY</td>
72
+ <td>s: xviii; sec ii p.chr.; secol xix; secolele ii-iii; etc.</td>
70
73
  </tr>
71
74
  <tr>
72
- <td>years</td>
73
- <td>77; 78; 1652; [1873]; aproximativ 1834; cca. 1420; etc.</td>
75
+ <td>MILLENNIUM</td>
76
+ <td>mil iii; mil. 5 a.chr.; mileniul v a.chr.; a mileniului v a.chr.; etc.</td>
74
77
  </tr>
75
78
  </table>
76
79
  * The values are mentioned in the reference language – Romanian language
@@ -78,12 +81,11 @@ quality and reliability of date-related information extracted from text.
78
81
 
79
82
 
80
83
  ## Getting started
81
- To integrate TeNs into spaCy pipelines you need the following:
82
84
 
83
85
  ### Prerequisites
84
86
  - Python 3.9-3.12
85
87
  - JRE 11-17
86
- - spaCy 3.x
88
+ - spaCy >=3.8.7,<4.0.0
87
89
  - py4j 0.10.9.9
88
90
  - langdetect 1.0.9
89
91
 
@@ -109,7 +111,7 @@ import spacy
109
111
  from temporal_normalization.commons.print_utils import console
110
112
 
111
113
  LANG = "ro"
112
- MODEL = "ro_core_news_sm"
114
+ MODEL = "ro_core_news_sm "
113
115
  TEXT_RO = ("Sec al II-lea a.ch. a fost o perioadă de mari schimbări. "
114
116
  "În secolul XX, tehnologia a avansat semnificativ. "
115
117
  "Sec. 21 este adesea asociat cu globalizarea rapidă.")
@@ -233,24 +235,24 @@ Start Edge:
233
235
  Matched value: Sec al II-lea a.ch.
234
236
  Matched Type: century
235
237
  Normalized label: 2nd century BC
236
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
238
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
237
239
 
238
240
  End Edge:
239
241
  Matched value: Sec al II-lea a.ch.
240
242
  Matched Type: century
241
243
  Normalized label: 2nd century BC
242
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
244
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
243
245
 
244
246
  Periods:
245
247
  Matched value: Sec al II-lea a.ch.
246
248
  Matched Type: century
247
249
  Normalized label: 1st millennium BC
248
- DBpedia uri: https://dbpedia.org/page/1st_millennium_BC
250
+ DBpedia uri: https://dbpedia.org/resource/1st_millennium_BC
249
251
 
250
252
  Matched value: Sec al II-lea a.ch.
251
253
  Matched Type: century
252
254
  Normalized label: 2nd century BC
253
- DBpedia uri: https://dbpedia.org/page/2nd_century_BC
255
+ DBpedia uri: https://dbpedia.org/resource/2nd_century_BC
254
256
  ```
255
257
 
256
258
  ### Second Sentence
@@ -259,24 +261,24 @@ Start Edge:
259
261
  Matched value: secolul XX
260
262
  Matched Type: century
261
263
  Normalized label: 20th century
262
- DBpedia uri: https://dbpedia.org/page/20th_century
264
+ DBpedia uri: https://dbpedia.org/resource/20th_century
263
265
 
264
266
  End Edge:
265
267
  Matched value: secolul XX
266
268
  Matched Type: century
267
269
  Normalized label: 20th century
268
- DBpedia uri: https://dbpedia.org/page/20th_century
270
+ DBpedia uri: https://dbpedia.org/resource/20th_century
269
271
 
270
272
  Periods:
271
273
  Matched value: secolul XX
272
274
  Matched Type: century
273
275
  Normalized label: 2nd millennium
274
- DBpedia uri: https://dbpedia.org/page/2nd_millennium
276
+ DBpedia uri: https://dbpedia.org/resource/2nd_millennium
275
277
 
276
278
  Matched value: secolul XX
277
279
  Matched Type: century
278
280
  Normalized label: 20th century
279
- DBpedia uri: https://dbpedia.org/page/20th_century
281
+ DBpedia uri: https://dbpedia.org/resource/20th_century
280
282
  ```
281
283
 
282
284
  ### Third Sentence
@@ -285,24 +287,24 @@ Start Edge:
285
287
  Matched value: Sec. 21
286
288
  Matched Type: century
287
289
  Normalized label: 21st century
288
- DBpedia uri: https://dbpedia.org/page/21st_century
290
+ DBpedia uri: https://dbpedia.org/resource/21st_century
289
291
 
290
292
  End Edge:
291
293
  Matched value: Sec. 21
292
294
  Matched Type: century
293
295
  Normalized label: 21st century
294
- DBpedia uri: https://dbpedia.org/page/21st_century
296
+ DBpedia uri: https://dbpedia.org/resource/21st_century
295
297
 
296
298
  Periods:
297
299
  Matched value: Sec. 21
298
300
  Matched Type: century
299
301
  Normalized label: 3rd millennium
300
- DBpedia uri: https://dbpedia.org/page/3rd_millennium
302
+ DBpedia uri: https://dbpedia.org/resource/3rd_millennium
301
303
 
302
304
  Matched value: Sec. 21
303
305
  Matched Type: century
304
306
  Normalized label: 21st century
305
- DBpedia uri: https://dbpedia.org/page/21st_century
307
+ DBpedia uri: https://dbpedia.org/resource/21st_century
306
308
  ```
307
309
 
308
310
 
@@ -9,7 +9,7 @@ temporal_normalization/commons/__init__.py
9
9
  temporal_normalization/commons/print_utils.py
10
10
  temporal_normalization/commons/temporal_models.py
11
11
  temporal_normalization/commons/temporal_types.py
12
- temporal_normalization/libs/temporal-normalization-2.1.0.jar
12
+ temporal_normalization/libs/temporal-normalization-2.2.1.jar
13
13
  temporal_normalization/process/__init__.py
14
14
  temporal_normalization/process/java_process.py
15
15
  temporal_normalization_spacy.egg-info/PKG-INFO
@@ -1,176 +0,0 @@
1
- import io
2
- import re
3
- import shutil
4
- import subprocess
5
- import threading
6
-
7
- from py4j.java_gateway import JavaGateway, GatewayParameters, CallbackServerParameters
8
- from py4j.protocol import Py4JNetworkError
9
-
10
- from temporal_normalization.commons.print_utils import console
11
-
12
-
13
- gateway_started = threading.Event()
14
-
15
- def start_conn(root_path: str) -> tuple[subprocess.Popen, JavaGateway]:
16
- """
17
- Starts the Java temporal normalization process and establishes a Py4J gateway connection.
18
-
19
- Args:
20
- root_path (str): The root directory of the project.
21
-
22
- Returns:
23
- tuple[subprocess.Popen, JavaGateway]:
24
- - The subprocess.Popen object representing the running Java process.
25
- - The JavaGateway object representing the active Py4J connection.
26
-
27
- Note:
28
- - Requires Java 11 or higher to be installed and accessible in the system PATH.
29
- - Requires `temporal-normalization-2.1.0.jar` to be present in the `libs` directory.
30
- - The caller is responsible for closing the gateway and terminating the Java process
31
- after usage to avoid orphaned processes.
32
- """
33
-
34
- check_java_version()
35
-
36
- jar_path = (
37
- f"{root_path}/temporal_normalization/libs/temporal-normalization-2.1.0.jar"
38
- )
39
-
40
- def stdout_callback(line: str):
41
- if "Gateway Server Started" in line:
42
- gateway_started.set()
43
- print(line.strip())
44
-
45
- java_process = subprocess.Popen(
46
- ["java", "-jar", jar_path, "--python"],
47
- stdout=subprocess.PIPE,
48
- stderr=subprocess.PIPE,
49
- text=True,
50
- )
51
-
52
- threading.Thread(target=drain_stream, args=(java_process.stdout, stdout_callback), daemon=True).start()
53
- threading.Thread(target=drain_stream, args=(java_process.stderr,), daemon=True).start()
54
-
55
- if not gateway_started.wait(timeout=10.0):
56
- java_process.terminate()
57
- raise RuntimeError("Java Gateway did not start within 10 seconds")
58
-
59
- gateway = JavaGateway(
60
- gateway_parameters=GatewayParameters(auto_convert=True, read_timeout=None),
61
- callback_server_parameters=None,
62
- )
63
-
64
- print("Python connection established.")
65
-
66
- return java_process, gateway
67
-
68
-
69
- def close_conn(java_process: subprocess.Popen, gateway: JavaGateway) -> None:
70
- """
71
- Closes the active connection between Python and the Java process started via Py4J.
72
-
73
- This function ensures a proper shutdown sequence:
74
- 1. Attempts to gracefully shut down the Py4J gateway connection.
75
- - If the Java process is already closed, a Py4JNetworkError is caught and logged.
76
- 2. Terminates the underlying Java process.
77
- 3. Prints status messages for debugging/confirmation.
78
-
79
- Args:
80
- java_process (subprocess.Popen): The Java process launched with subprocess.
81
- gateway (JavaGateway): The active Py4J gateway connection.
82
-
83
- Notes:
84
- - Call this function once you have finished all interactions with the Java process.
85
- - It is safe to call even if the Java process has already exited.
86
- """
87
-
88
- try:
89
- # Proper way to shut down Py4J
90
- gateway.shutdown()
91
- print("✅ Python connection closed.")
92
- except Py4JNetworkError:
93
- print("⚠️ Java process already shut down.")
94
- except Exception as e:
95
- print(f"⚠️ Error shutting down gateway: {e}")
96
-
97
- # Terminate Java process
98
- java_process.terminate()
99
- java_process.wait()
100
- print("✅ Java process terminated.")
101
-
102
-
103
- def drain_stream(stream: io.TextIOBase, callback=None) -> None:
104
- """
105
- Consumes the output from a given stream until a specific marker is found,
106
- then closes the stream.
107
-
108
- This function is typically used to monitor the stdout or stderr of a subprocess
109
- (e.g., a Java process started from Python) and detect when a certain event occurs,
110
- such as the initialization of a gateway server. Once the marker line is encountered,
111
- the function prints it (or logs it) and terminates the stream reading.
112
-
113
- Args:
114
- stream (io.TextIOBase): A text-based stream object to read from, usually
115
- subprocess.stdout or subprocess.stderr.
116
- callback (callable, optional): A function that takes a single string argument (line).
117
- It will be called for every line read from the stream.
118
- Useful for detecting specific markers, logging, or
119
- triggering events when certain output appears.
120
-
121
- Raises:
122
- AttributeError: If the provided `stream` does not have `readline` or `close` methods.
123
- """
124
- for line in iter(stream.readline, ""):
125
- line = line.strip()
126
- if callback:
127
- callback(line)
128
-
129
- stream.close()
130
-
131
-
132
- def check_java_version() -> None:
133
- """
134
- Verifies that Java is installed and meets the minimum required version.
135
-
136
- This function checks for the presence of the Java executable in the system PATH,
137
- runs ``java -version``, and ensures that the version is at least 11. If Java is not
138
- installed or the version is too low, it logs an error using ``console.error``.
139
-
140
- Raises:
141
- Logs error messages, but does not raise exceptions directly.
142
- """
143
-
144
- min_version = 11
145
- java_path = shutil.which("java")
146
-
147
- try:
148
- if java_path:
149
- # Run the command to check the Java version
150
- result = subprocess.run(
151
- [java_path, "-version"], capture_output=True, text=True
152
- )
153
-
154
- # Print the version information (Java version is printed to stderr)
155
- if result.returncode == 0:
156
- version_output = result.stderr
157
- match = re.search(r'version "(\d+\.\d+)', version_output)
158
-
159
- if match:
160
- crr_version = float(match.group(1))
161
- if crr_version < min_version:
162
- console.error(
163
- f"Java {crr_version} is installed, but version {min_version} is required." # noqa 501
164
- )
165
- else:
166
- console.error("Could not extract Java version.")
167
- else:
168
- console.error("Error occurred while checking the version.")
169
- else:
170
- console.error("Java not found.")
171
- except Exception as e:
172
- console.error(e.__str__())
173
-
174
-
175
- if __name__ == "__main__":
176
- pass