hHoai commited on
Commit
ba980c3
·
verified ·
1 Parent(s): 52f1f7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -75
app.py CHANGED
@@ -1,80 +1,55 @@
1
  import streamlit as st
2
- from transformers import pipeline, AutoTokenizer
3
- import difflib
4
 
5
- # Cấu hình ứng dụng
6
  MAX_LENGTH = 512
7
- st.set_page_config(
8
- page_title="Demo Correct Spelling Mistakes",
9
- layout="centered",
10
- initial_sidebar_state="auto"
11
- )
12
 
13
- # CSS tuỳ chỉnh cho phần highlight
14
- custom_css = """
15
- <style>
16
- .highlight {
17
- color: red;
18
- font-weight: bold;
19
- }
20
- </style>
21
- """
22
- st.markdown(custom_css, unsafe_allow_html=True)
23
-
24
- st.title("Correct Spelling Mistakes App")
25
-
26
- # Load mô hình và tokenizer
27
- @st.cache_resource
28
- def load_model_and_tokenizer():
29
- model_checkpoint = "hHoai/model_vietnamcorrection" # Thay đổi checkpoint phù hợp
30
- correct_spelling = pipeline("text2text-generation", model=model_checkpoint, tokenizer=model_checkpoint)
31
- tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
32
- return correct_spelling, tokenizer
33
-
34
- correct_spelling, tokenizer = load_model_and_tokenizer()
35
-
36
- # Hàm nối từ thành cụm từ
37
- def join_tokens_as_phrases(tokens):
38
- return " ".join([token.replace("▁", "") if "▁" in token else f"_{token}" for token in tokens]).strip()
39
-
40
- # Nhập liệu từ người dùng
41
- context = st.text_area("Input text", placeholder="Nhập văn bản lỗi chính tả...")
42
-
43
- # Xử lý nút bấm
44
- if st.button("Get Result"):
45
- if context.strip():
46
- try:
47
- # Sử dụng pipeline để sửa lỗi chính tả
48
- result = correct_spelling(context, max_length=MAX_LENGTH)
49
- corrected_text = result[0]['generated_text'] if result else "No output generated."
50
-
51
- # Tokenize sử dụng tokenizer của bạn
52
- original_tokens = tokenizer.tokenize(context)
53
- corrected_tokens = tokenizer.tokenize(corrected_text)
54
-
55
- # Nối các từ thành cụm từ với gạch dưới
56
- original_phrases = join_tokens_as_phrases(original_tokens)
57
- corrected_phrases = join_tokens_as_phrases(corrected_tokens)
58
-
59
- # So sánh các từ và tìm từ thay đổi
60
- def highlight_differences(original, corrected):
61
- highlighted_text = []
62
- matcher = difflib.SequenceMatcher(None, original.split(), corrected.split())
63
- for tag, i1, i2, j1, j2 in matcher.get_opcodes():
64
- if tag == 'replace' or tag == 'insert': # Nếu từ bị thay thế hoặc thêm
65
- highlighted_text.append(
66
- f"<span class='highlight'>{' '.join(corrected.split()[j1:j2])}</span>"
67
- )
68
- else: # Nếu từ không thay đổi
69
- highlighted_text.append(" ".join(corrected.split()[j1:j2]))
70
-
71
- return " ".join(highlighted_text)
72
-
73
- # Hiển thị kết quả
74
- highlighted_text = highlight_differences(original_phrases, corrected_phrases)
75
- st.markdown(f"### Original Text (phrases):\n\n{original_phrases}")
76
- st.markdown(f"### Corrected Text (with highlighted words):\n\n{highlighted_text}", unsafe_allow_html=True)
77
- except Exception as e:
78
- st.error(f"An error occurred: {e}")
79
  else:
80
- st.warning("Please input some text to process!")
 
1
  import streamlit as st
2
+ from transformers import pipeline
 
3
 
 
4
  MAX_LENGTH = 512
 
 
 
 
 
5
 
6
+ # Load the spell corrector model
7
+ corrector = pipeline("text2text-generation", model="VietAI/vit5-base-corrector")
8
+
9
+ def find_mistake_positions(original, corrected):
10
+ """
11
+ Tìm vị trí các từ bị sửa trong câu gốc.
12
+ original: Câu gốc (chuỗi)
13
+ corrected: Câu đã được sửa (chuỗi)
14
+ Trả về danh sách các vị trí từ sai (start_index, end_index)
15
+ """
16
+ positions = []
17
+ orig_tokens = original.split() # Tách từ câu gốc
18
+ corr_tokens = corrected.split() # Tách từ câu sửa
19
+
20
+ orig_idx = 0 # Chỉ số ký tự bắt đầu trong câu gốc
21
+ for orig_word, corr_word in zip(orig_tokens, corr_tokens):
22
+ if orig_word != corr_word: # Nếu từ bị thay đổi
23
+ start_index = original.find(orig_word, orig_idx) + 1 # Tìm vị trí từ trong câu gốc
24
+ end_index = start_index + len(orig_word) - 1 # Tính vị trí kết thúc
25
+ positions.append((start_index, end_index)) # Ghi lại (start, end)
26
+ orig_idx += len(orig_word) + 1 # Cập nhật chỉ số (bao gồm khoảng trắng)
27
+
28
+ return positions
29
+
30
+ # Streamlit app layout
31
+ st.title("Ứng Dụng Sửa Lỗi Chính Tả")
32
+ st.write("Nhập văn bản và nhận kết quả sửa lỗi chính tả!")
33
+
34
+ # Input text box for user to enter a sentence
35
+ input_text = st.text_area("Nhập câu gốc:", "Hôm nay toi di hoc rất vui, gặp gỡ nhiêu ban be mơi.")
36
+
37
+ if st.button("Sửa lỗi"):
38
+ # Perform batch prediction
39
+ predictions = corrector([input_text], max_length=MAX_LENGTH)
40
+
41
+ # Get the corrected text and find mistake positions
42
+ corrected_text = predictions[0]["generated_text"]
43
+ mistake_positions = find_mistake_positions(input_text, corrected_text)
44
+
45
+ # Display the results
46
+ st.subheader("Kết quả sửa lỗi:")
47
+ st.write(f"Câu gốc: {input_text}")
48
+ st.write(f"Câu sửa: {corrected_text}")
49
+
50
+ st.subheader("Vị trí các từ sai (start_index, end_index):")
51
+ if mistake_positions:
52
+ for start, end in mistake_positions:
53
+ st.write(f"Vị trí từ sai: {start} - {end}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  else:
55
+ st.write("Không phát hiện từ sai.")