jayyd commited on
Commit
c2f24be
·
verified ·
1 Parent(s): aa6b77c

Create nltk_bootstrap.py

Browse files
Files changed (1) hide show
  1. utils/nltk_bootstrap.py +39 -0
utils/nltk_bootstrap.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/utils/nltk_bootstrap.py
2
+ import os
3
+ import pathlib
4
+
5
+ def ensure_punkt():
6
+ """
7
+ Make NLTK look in a writable dir, download 'punkt_tab' (or 'punkt')
8
+ if missing, and inject that dir into nltk.data.path. No-op if already present.
9
+ """
10
+ try:
11
+ import nltk # import here so module is optional at build time
12
+ except Exception:
13
+ return # If NLTK isn't installed, caller should have a fallback
14
+
15
+ # Choose a persistent/writable location
16
+ base = "/data/nltk_data" if os.path.isdir("/data") else os.path.join(os.path.dirname(__file__), "..", "nltk_data")
17
+ nltd = os.path.abspath(base)
18
+ os.makedirs(nltd, exist_ok=True)
19
+
20
+ # Environment + explicit path injection (important in Spaces)
21
+ os.environ["NLTK_DATA"] = nltd
22
+ if nltd not in nltk.data.path:
23
+ nltk.data.path.insert(0, nltd)
24
+
25
+ # Try new resource first, then the legacy one
26
+ for res in ("punkt_tab", "punkt"):
27
+ try:
28
+ nltk.data.find(f"tokenizers/{res}")
29
+ return
30
+ except LookupError:
31
+ try:
32
+ nltk.download(res, download_dir=nltd, quiet=True, raise_on_error=True)
33
+ # After download, ensure it's on the path and return
34
+ if nltd not in nltk.data.path:
35
+ nltk.data.path.insert(0, nltd)
36
+ return
37
+ except Exception:
38
+ # Try the next resource name
39
+ continue