Download app/model_handler.py from hHoai/api: direct link, hf CLI and curl.
- Browser
- Download file 3.97 kB
-
https://huggingface.co/spaces/hHoai/api/resolve/main/app/model_handler.py
- Command line
-
hf download hf://spaces/hHoai/api/app/model_handler.py
-
curl -L -o model_handler.py https://huggingface.co/spaces/hHoai/api/resolve/main/app/model_handler.py
3.97 kB
| 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") |