versa / fix_nltk_permissions.py
ftshijt
add a full go-through for nltk permission
7ee1777
raw
history blame
2.91 kB
#!/usr/bin/env python3
"""
Script to pre-download NLTK data to a writable location and patch
discrete_speech_metrics to use this location.
"""
import os
import sys
import nltk
import importlib.util
import subprocess
# Set NLTK data directory to a writable location
nltk_data_dir = "/usr/local/share/nltk_data"
os.makedirs(nltk_data_dir, exist_ok=True)
os.environ["NLTK_DATA"] = nltk_data_dir
print(f"Setting NLTK data directory to: {nltk_data_dir}")
print(f"Directory exists: {os.path.exists(nltk_data_dir)}")
print(f"Directory permissions: {oct(os.stat(nltk_data_dir).st_mode)}")
print(f"User ID: {os.getuid()}, Group ID: {os.getgid()}")
# Make the directory world-writable
try:
os.chmod(nltk_data_dir, 0o777)
print(f"Changed permissions on {nltk_data_dir} to 0o777")
except Exception as e:
print(f"Failed to change permissions: {e}")
# Pre-download necessary NLTK data
for package in ['punkt', 'stopwords', 'wordnet']:
print(f"Downloading NLTK package: {package}")
try:
nltk.download(package, download_dir=nltk_data_dir, quiet=False)
print(f"Successfully downloaded {package}")
except Exception as e:
print(f"Error downloading {package}: {e}")
# Try to modify the discrete_speech_metrics module to use our NLTK data dir
try:
# Find discrete_speech_metrics module
spec = importlib.util.find_spec("discrete_speech_metrics")
if spec is not None:
module_path = os.path.dirname(spec.origin)
print(f"Found discrete_speech_metrics at: {module_path}")
# Files to patch
files_to_patch = [
os.path.join(module_path, "speechbleu.py"),
os.path.join(module_path, "speechbert.py"),
os.path.join(module_path, "__init__.py")
]
for file_path in files_to_patch:
if os.path.exists(file_path):
print(f"Patching file: {file_path}")
# Read file content
with open(file_path, 'r') as file:
content = file.read()
# Replace nltk.download with our custom version
if "nltk.download" in content:
patched_content = content.replace(
'nltk.download(',
f'nltk.download(download_dir="{nltk_data_dir}", '
)
# Write patched content back
with open(file_path, 'w') as file:
file.write(patched_content)
print(f"Successfully patched {file_path}")
else:
print(f"No nltk.download calls found in {file_path}")
else:
print("discrete_speech_metrics module not found")
except Exception as e:
print(f"Error patching discrete_speech_metrics: {e}")
print("NLTK setup complete")