Download app/text_processing.py from hHoai/api: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/spaces/hHoai/api/resolve/main/app/text_processing.py
- Command line
-
hf download hf://spaces/hHoai/api/app/text_processing.py
-
curl -L -o text_processing.py https://huggingface.co/spaces/hHoai/api/resolve/main/app/text_processing.py
15.9 kB
| import re | |
| import unicodedata | |
| import difflib | |
| def normalize_vietnamese_tones(text): | |
| """ | |
| Chuẩn hóa vị trí dấu thanh trong tiếng Việt từ kiểu "cũ" sang kiểu "mới". | |
| Kiểu "cũ": òa, óa, ỏa, õa, ọa, òe, óe, ỏe, õe, ọe, ùy, úy, ủy, ũy, ụy | |
| Kiểu "mới": oà, oá, oả, oã, oạ, oè, oé, oẻ, oẽ, oẹ, uỳ, uý, uỷ, uỹ, uỵ | |
| """ | |
| # Ánh xạ chuyển đổi từ dạng "cũ" sang dạng "mới" | |
| replacement_map = { | |
| # oa | |
| 'òa': 'oà', 'óa': 'oá', 'ỏa': 'oả', 'õa': 'oã', 'ọa': 'oạ', | |
| 'Òa': 'Oà', 'Óa': 'Oá', 'Ỏa': 'Oả', 'Õa': 'Oã', 'Ọa': 'Oạ', | |
| # oe | |
| 'òe': 'oè', 'óe': 'oé', 'ỏe': 'oẻ', 'õe': 'oẽ', 'ọe': 'oẹ', | |
| 'Òe': 'Oè', 'Óe': 'Oé', 'Ỏe': 'Oẻ', 'Õe': 'Oẽ', 'Ọe': 'Oẹ', | |
| # uy | |
| 'ùy': 'uỳ', 'úy': 'uý', 'ủy': 'uỷ', 'ũy': 'uỹ', 'ụy': 'uỵ', | |
| 'Ùy': 'Uỳ', 'Úy': 'Uý', 'Ủy': 'Uỷ', 'Ũy': 'Uỹ', 'Ụy': 'Uỵ' | |
| } | |
| # Thực hiện thay thế | |
| normalized_text = text | |
| for old, new in replacement_map.items(): | |
| normalized_text = normalized_text.replace(old, new) | |
| return normalized_text | |
| def normalize_text(text): | |
| # Chuẩn hóa Unicode theo chuẩn NFC | |
| text = unicodedata.normalize("NFC", text) | |
| # Thay thế các ký tự dấu ngoặc kép thông minh thành dấu nháy kép tiêu chuẩn | |
| text = text.replace(""", "\"").replace(""", "\"") | |
| text = text.replace("'", "'").replace("'", "'") | |
| return text | |
| def split_into_sentences(text): | |
| sentences = re.split(r'([.?!:;])\s*', text) | |
| merged_sentences = [] | |
| temp_sentence = "" | |
| for part in sentences: | |
| if part in ".?!:;": | |
| temp_sentence += part | |
| merged_sentences.append(temp_sentence.strip()) | |
| temp_sentence = "" | |
| else: | |
| temp_sentence += part | |
| if temp_sentence: | |
| merged_sentences.append(temp_sentence.strip()) | |
| return merged_sentences | |
| def load_valid_repeated_words(dict_file="app/tu_dien_tu_lap_dung.txt"): | |
| """ | |
| Đọc từ điển các từ lặp hợp lệ từ file | |
| """ | |
| valid_repeats = set() | |
| try: | |
| with open(dict_file, "r", encoding="utf-8") as f: | |
| for line in f: | |
| word = line.strip() | |
| if word: | |
| valid_repeats.add(word.lower()) | |
| return valid_repeats | |
| except Exception as e: | |
| print(f"Lỗi khi đọc từ điển từ lặp: {str(e)}") | |
| return set() | |
| # Tải từ điển từ lặp hợp lệ | |
| _VALID_REPEATED_WORDS = load_valid_repeated_words() | |
| def detect_repeated_words(text): | |
| """ | |
| Phát hiện từ lặp trong văn bản. | |
| Trả về danh sách các từ lặp với vị trí bắt đầu và kết thúc. | |
| Bỏ qua các từ lặp hợp lệ có trong từ điển. | |
| """ | |
| # Chuẩn hóa Unicode | |
| text = unicodedata.normalize('NFC', text) | |
| # Tách văn bản thành các từ riêng biệt | |
| words = [] | |
| # Sử dụng regex để tìm các từ, bỏ qua dấu câu | |
| for match in re.finditer(r'\b(\w+)\b', text): | |
| words.append({ | |
| 'word': match.group().lower(), | |
| 'start': match.start(), | |
| 'end': match.end() | |
| }) | |
| # Tìm các từ lặp liền kề | |
| repeated_info = [] | |
| i = 0 | |
| while i < len(words) - 1: | |
| if words[i]['word'] == words[i + 1]['word'] and len(words[i]['word']) > 1: | |
| # Lấy vị trí bắt đầu của từ thứ nhất và vị trí kết thúc của từ thứ hai | |
| start_pos = words[i]['start'] | |
| end_pos = words[i + 1]['end'] | |
| # Lấy đoạn văn bản gốc (bao gồm cả khoảng trắng giữa các từ) | |
| repeated_phrase = text[start_pos:end_pos] | |
| # Kiểm tra xem từ lặp này có trong từ điển không | |
| if repeated_phrase.lower().strip() not in _VALID_REPEATED_WORDS: | |
| repeated_info.append({ | |
| "word": repeated_phrase, | |
| "start_position": start_pos, | |
| "end_position": end_pos | |
| }) | |
| # Bỏ qua cả hai từ đã xử lý | |
| i += 2 | |
| else: | |
| i += 1 | |
| return repeated_info if repeated_info else None | |
| def get_repeated_regions(text): | |
| """ | |
| Trả về một từ điển các vùng có từ lặp để kiểm tra trùng lặp. | |
| Key là (start_position, end_position), value là từ lặp tương ứng. | |
| """ | |
| repeated_words = detect_repeated_words(text) | |
| if not repeated_words: | |
| return {} | |
| repeated_regions = {} | |
| for repeat in repeated_words: | |
| key = (repeat['start_position'], repeat['end_position']) | |
| repeated_regions[key] = repeat['word'] | |
| return repeated_regions | |
| def tokenize_with_positions(s, normalize_ws=False): | |
| """ | |
| Tách chuỗi s thành các token, bao gồm cả từ và khoảng trắng, | |
| và ghi lại vị trí bắt đầu của từng token. | |
| Nếu normalize_ws=True, với token là khoảng trắng thì chuẩn hóa thành " ". | |
| """ | |
| tokens = [] | |
| for match in re.finditer(r'\S+|\s+', s): | |
| token = match.group(0) | |
| pos = match.start() | |
| # Nếu token là khoảng trắng và cần chuẩn hóa, thay thế bằng 1 khoảng trắng | |
| norm = " " if normalize_ws and token.isspace() else token | |
| tokens.append({'orig': token, 'norm': norm, 'pos': pos}) | |
| return tokens | |
| def find_spelling_errors(s1, s2, warnings=None): | |
| """ | |
| So sánh chuỗi gốc s1 và chuỗi đã sửa s2 để tìm ra các lỗi sai. | |
| Tất cả các vị trí được dựa trên văn bản gốc s1. | |
| Nếu có warnings (danh sách từ lặp), sẽ kiểm tra xem lỗi có liên quan không. | |
| """ | |
| s1_normalized = unicodedata.normalize('NFC', s1) | |
| s2_normalized = unicodedata.normalize('NFC', s2) | |
| # Phát hiện vùng từ lặp trong văn bản gốc để kiểm tra nhưng không thay thế | |
| repeated_regions = get_repeated_regions(s1_normalized) | |
| tokens1 = tokenize_with_positions(s1_normalized, normalize_ws=False) | |
| tokens2 = tokenize_with_positions(s2_normalized, normalize_ws=True) | |
| # Sử dụng phiên bản norm để so sánh | |
| norm_tokens1 = [t['norm'] for t in tokens1] | |
| norm_tokens2 = [t['norm'] for t in tokens2] | |
| matcher = difflib.SequenceMatcher(None, norm_tokens1, norm_tokens2) | |
| corrections = [] | |
| for tag, i1, i2, j1, j2 in matcher.get_opcodes(): | |
| if tag in ('replace', 'delete'): | |
| for idx in range(i1, i2): | |
| token = tokens1[idx] | |
| suggestions = norm_tokens2[j1:j2] if tag == 'replace' else [] | |
| start_pos = token['pos'] | |
| end_pos = start_pos + len(token['orig']) | |
| corrections.append({ | |
| 'word': token['orig'], | |
| 'suggestions': suggestions, | |
| 'start_position': start_pos, | |
| 'end_position': end_pos | |
| }) | |
| elif tag == 'insert': | |
| # Trong trường hợp insert, lấy vị trí từ văn bản gốc | |
| pos = tokens1[i1 - 1]['pos'] + len(tokens1[i1 - 1]['orig']) if i1 > 0 else 0 | |
| suggestions = norm_tokens2[j1:j2] | |
| corrections.append({ | |
| 'word': '', | |
| 'suggestions': suggestions, | |
| 'start_position': pos, | |
| 'end_position': pos | |
| }) | |
| # Gộp các lỗi liền kề trước khi xử lý warnings | |
| processed_corrections = [] | |
| i = 0 | |
| while i < len(corrections): | |
| current = corrections[i] | |
| start_pos = current['start_position'] | |
| end_pos = current['end_position'] | |
| combined_word = current['word'] | |
| current_suggestions = current['suggestions'] | |
| # Xem liệu có thể gộp các lỗi liền nhau không | |
| j = i + 1 | |
| while j < len(corrections) and corrections[j]['start_position'] == end_pos: | |
| end_pos = corrections[j]['end_position'] | |
| combined_word += corrections[j]['word'] | |
| j += 1 | |
| if j > i + 1: # Có gộp lỗi | |
| # Tạo lỗi mới đã gộp | |
| merged_correction = { | |
| 'word': combined_word, | |
| 'suggestions': current_suggestions, | |
| 'start_position': start_pos, | |
| 'end_position': end_pos | |
| } | |
| processed_corrections.append(merged_correction) | |
| i = j | |
| else: | |
| processed_corrections.append(current) | |
| i += 1 | |
| # Kiểm tra trùng lặp trong corrections | |
| improved_corrections = [] | |
| processed_positions = set() # Theo dõi vị trí đã xử lý | |
| # Trước tiên, kiểm tra và áp dụng quy tắc với warnings | |
| if warnings: | |
| for correction in processed_corrections: | |
| skip_correction = False | |
| start_pos = correction['start_position'] | |
| end_pos = correction['end_position'] | |
| # Bỏ qua nếu đã xử lý vị trí này | |
| if any(start_pos >= existing_start and end_pos <= existing_end | |
| for existing_start, existing_end in processed_positions): | |
| continue | |
| for warning in warnings: | |
| # Kiểm tra nếu start_position của correction bé hơn start_position của warning 1 đơn vị | |
| if correction['start_position'] == warning['start_position'] - 1: | |
| # Thay thế bằng thông tin từ warning | |
| improved_corrections.append({ | |
| 'word': warning['word'], | |
| 'suggestions': correction['suggestions'], | |
| 'start_position': warning['start_position'], | |
| 'end_position': warning['end_position'] | |
| }) | |
| # Đánh dấu vị trí đã xử lý | |
| processed_positions.add((warning['start_position'], warning['end_position'])) | |
| skip_correction = True | |
| break | |
| if not skip_correction: | |
| # Kiểm tra xem correction này có thuộc vùng từ lặp không | |
| found_in_repeat_region = False | |
| for (r_start, r_end), r_word in repeated_regions.items(): | |
| # Nếu lỗi này nằm trong một vùng từ lặp | |
| if (start_pos >= r_start and end_pos <= r_end) or (r_start <= start_pos < r_end): | |
| # Bỏ qua nếu đã xử lý vị trí này | |
| if any(r_start >= existing_start and r_end <= existing_end | |
| for existing_start, existing_end in processed_positions): | |
| found_in_repeat_region = True | |
| break | |
| # Lấy từ trong văn bản gốc | |
| word_in_region = s1_normalized[r_start:r_end] | |
| # Thay thế bằng từ lặp đầy đủ | |
| improved_corrections.append({ | |
| 'word': word_in_region, | |
| 'suggestions': correction['suggestions'], | |
| 'start_position': r_start, | |
| 'end_position': r_end | |
| }) | |
| # Đánh dấu vị trí đã xử lý | |
| processed_positions.add((r_start, r_end)) | |
| found_in_repeat_region = True | |
| break | |
| if not found_in_repeat_region: | |
| improved_corrections.append(correction) | |
| # Đánh dấu vị trí đã xử lý | |
| processed_positions.add((start_pos, end_pos)) | |
| else: | |
| improved_corrections = processed_corrections | |
| # Hậu xử lý: nếu 1 từ có nhiều hơn 1 suggestion, ghép chúng lại thành 1 chuỗi duy nhất | |
| for corr in improved_corrections: | |
| if len(corr['suggestions']) > 1: | |
| corr['suggestions'] = [''.join(corr['suggestions'])] | |
| return improved_corrections | |
| def process_result_json(result_json): | |
| """ | |
| Xử lý JSON kết quả, cập nhật corrections dựa trên warnings. | |
| Args: | |
| result_json: Dict chứa kết quả gốc với corrections và warnings | |
| Returns: | |
| Dict đã cập nhật với corrections mới và warnings đã lọc | |
| """ | |
| if not result_json or "corrections" not in result_json or "warning" not in result_json: | |
| return result_json | |
| # Lấy thông tin từ JSON | |
| corrections = result_json.get("corrections", []) | |
| warnings = result_json.get("warning", []) | |
| # Nếu không có dữ liệu đầy đủ, trả về kết quả gốc | |
| if not corrections or not warnings: | |
| return result_json | |
| # Tìm các correction cần cập nhật dựa trên warnings | |
| updated_corrections = [] | |
| processed_idxs = set() # Các chỉ số đã xử lý | |
| processed_warnings = set() # Các warning đã được xử lý | |
| for i, correction in enumerate(corrections): | |
| already_processed = False | |
| for j, warning in enumerate(warnings): | |
| if (correction['start_position'] == warning['start_position'] - 1 or | |
| correction['end_position'] == warning['end_position'] + 1): | |
| # Tách từ lặp để lấy một từ đơn làm suggestion | |
| warning_text = warning['word'] | |
| words_in_repeat = re.findall(r'\b\w+\b', warning_text) | |
| suggestion = words_in_repeat[0] if words_in_repeat else "" | |
| # Thay thế bằng thông tin từ warning và cập nhật suggestions | |
| updated_corrections.append({ | |
| 'word': warning['word'], | |
| 'suggestions': [suggestion], | |
| 'start_position': warning['start_position'], | |
| 'end_position': warning['end_position'] | |
| }) | |
| processed_idxs.add(i) | |
| processed_warnings.add(j) # Đánh dấu warning đã xử lý | |
| already_processed = True | |
| break | |
| if not already_processed and i not in processed_idxs: | |
| updated_corrections.append(correction) | |
| # Cập nhật lại corrections | |
| result_json["corrections"] = updated_corrections | |
| # Lọc warnings: chỉ giữ lại những warning chưa được xử lý và không trùng với corrections | |
| filtered_warnings = [] | |
| for j, warning in enumerate(warnings): | |
| if j in processed_warnings: | |
| continue | |
| warning_pos = (warning['start_position'], warning['end_position']) | |
| has_matching_correction = any( | |
| warning_pos == (correction['start_position'], correction['end_position']) | |
| for correction in updated_corrections | |
| ) | |
| if not has_matching_correction: | |
| filtered_warnings.append(warning) | |
| result_json["warning"] = filtered_warnings | |
| return result_json |