File size: 3,973 Bytes
923a576 afb193b 923a576 afb193b 923a576 afb193b 923a576 ab3f3b9 afb193b 923a576 afb193b 923a576 afb193b 923a576 afb193b 923a576 3f75e6c 47b96b1 3f75e6c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | import time
import logging
from typing import Dict, Any, Optional
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from app.text_processing import normalize_text, normalize_vietnamese_tones, find_spelling_errors, detect_repeated_words, process_result_json
# Thiết lập logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Biến global để lưu trữ mô hình và tokenizer
model = None
tokenizer = None
def load_model():
"""Tải mô hình sửa lỗi chính tả"""
global model, tokenizer
try:
logger.info("Đang tải mô hình sửa lỗi chính tả")
model_path = "hHoai/spellcheck"
model = AutoModelForSeq2SeqLM.from_pretrained(model_path).to("cuda:0") # Sử dụng GPU nếu có
tokenizer = AutoTokenizer.from_pretrained(model_path)
logger.info("Đã tải mô hình thành công")
except Exception as e:
logger.error(f"Lỗi khi tải mô hình: {str(e)}")
raise RuntimeError(f"Không thể tải mô hình: {str(e)}")
def correct_spelling(text: str, options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Hàm sửa lỗi chính tả"""
global model, tokenizer
# Kiểm tra xem mô hình đã được tải chưa
if model is None or tokenizer is None:
logger.error("Mô hình chưa được tải")
raise RuntimeError("Mô hình chưa được tải")
try:
# Đo thời gian xử lý
start_time = time.time()
# Lấy các tùy chọn từ parameter nếu có
max_length = options.get("max_length", 256) if options else 256
# Chuẩn hóa văn bản đầu vào
normalized_input = normalize_text(text)
normalized_input = normalize_vietnamese_tones(normalized_input)
logger.info(f"Đang xử lý văn bản: {normalized_input[:50]}...")
# Sử dụng mô hình để sửa lỗi chính tả
inputs = tokenizer(normalized_input, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_length=max_length)
corrected_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Tính thời gian xử lý
processing_time = (time.time() - start_time) * 1000 # Đổi sang milliseconds
logger.info(f"Đã xử lý trong {processing_time:.2f}ms")
# Tìm các lỗi chính tả
corrections = find_spelling_errors(normalized_input, corrected_text)
# Phát hiện từ lặp chỉ trong văn bản gốc
warnings = detect_repeated_words(text)
# Ghi log nếu phát hiện lỗi
has_errors = bool(corrections) or bool(warnings)
if has_errors:
if corrections:
logger.info(f"Phát hiện {len(corrections)} lỗi chính tả")
if warnings:
logger.info(f"Phát hiện {len(warnings)} từ lặp")
# Tạo kết quả JSON
result_json = {
"status": "success",
"has_errors": has_errors,
"corrections": corrections,
"warning": warnings if warnings else []
}
# Xử lý và cập nhật corrections dựa trên warnings
processed_result = process_result_json(result_json)
return processed_result
except Exception as e:
logger.error(f"Lỗi khi sửa lỗi chính tả: {str(e)}")
return {
"status": "error",
"has_errors": False,
"corrections": [],
"warning": [],
"error": str(e)
}
def cleanup_model():
"""Giải phóng tài nguyên của mô hình"""
global model, tokenizer
model = None
tokenizer = None
logger.info("Đã giải phóng tài nguyên mô hình") |