HEX
Server: LiteSpeed
System: Linux houston.panomity.com 6.8.0-100-generic #100-Ubuntu SMP PREEMPT_DYNAMIC Tue Jan 13 16:40:06 UTC 2026 x86_64
User: nudepix (1011)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: //opt/textanalyse/tools/grammar_check_tool.py
# tools/grammar_check_tool.py
# Requires: pip install language-tool-python

import language_tool_python
from typing import List, Dict, Optional

# Initialize the tool once (can be language specific, e.g., 'en-US')
# This might take a moment on first run as it downloads models.
try:
    lang_tool = language_tool_python.LanguageTool('en-US')
    print("LanguageTool initialized successfully.")
except Exception as e:
    print(f"Error initializing LanguageTool: {e}. Grammar check tool will not function.")
    lang_tool = None

def check_grammar(text: str) -> List[Dict[str, Optional[str]]]:
    """
    Checks the text for grammar errors using LanguageTool.

    Args:
        text (str): The text segment to check.

    Returns:
        List[Dict[str, Optional[str]]]: A list of dictionaries, each representing a detected error
                                        with keys like 'message', 'context', 'suggestions', etc.
                                        Returns an empty list if LanguageTool is not available or no errors found.
    """
    if lang_tool is None:
        print("Grammar check skipped: LanguageTool not available.")
        return []
    if not isinstance(text, str) or not text:
        return []

    try:
        matches = lang_tool.check(text)
        # Convert Match objects to a serializable format (list of dicts)
        errors = [] # Initialize errors as an empty list
        for match in matches:
            errors.append({
                'ruleId': match.ruleId,
                'message': match.message,
                'context': match.context,
                'offset': str(match.offset), # Ensure serializable type
                'length': str(match.errorLength), # Ensure serializable type
                'category': match.category,
                'suggestions': str(match.replacements) if match.replacements else None, # Ensure serializable
            })
        return errors
    except Exception as e:
        print(f"Error during grammar check: {e}")
        return []

# Example usage (for testing the tool directly)
# if __name__ == "__main__":
#     test_text = "This are a example sentence with some mistake."
#     found_errors = check_grammar(test_text)
#     print(f"Errors found in '{test_text}':")
#     for error in found_errors:
#         print(f"- {error['message']} (Context:...{error['context']}...)")