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']}...)")