Diezu commited on
Commit
828db21
·
verified ·
1 Parent(s): c45f7b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -121
app.py CHANGED
@@ -1,123 +1,50 @@
1
  import streamlit as st
2
- from transformers import pipeline
3
- import difflib
4
-
5
- # Thư viện tra cứu nghĩa
6
- # Giả sử bạn có một hàm hoặc cơ sở dữ liệu trả về nghĩa
7
- def get_word_meaning(word):
8
- # Thay bằng hàm thực tế tra cứu nghĩa từ
9
- dictionary = {
10
- "sai": "Không đúng, lệch lạc so với thực tế.",
11
- "đúng": "Phù hợp với sự thật hoặc tiêu chuẩn.",
12
- }
13
- return dictionary.get(word, "Không tìm thấy nghĩa.")
14
-
15
- # Cấu hình ứng dụng
16
- MAX_LENGTH = 512
17
- st.set_page_config(
18
- page_title="Demo Correct Spelling Mistakes",
19
- page_icon="🤖",
20
- layout="centered",
21
- initial_sidebar_state="auto"
22
- )
23
-
24
- # CSS tùy chỉnh
25
- custom_css = """
26
- <style>
27
- body {
28
- background-color: #f4f4f4;
29
- font-family: 'Arial', sans-serif;
30
- }
31
- .main {
32
- background-color: #ffffff;
33
- padding: 20px;
34
- border-radius: 10px;
35
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
36
- max-width: 800px;
37
- margin: 0 auto;
38
- }
39
- h1 {
40
- text-align: center;
41
- color: #4a90e2;
42
- }
43
- textarea {
44
- font-family: 'Courier New', Courier, monospace;
45
- font-size: 14px;
46
- color: #333;
47
- }
48
- .stButton button {
49
- background-color: #4a90e2;
50
- color: white;
51
- border: none;
52
- border-radius: 5px;
53
- padding: 10px 20px;
54
- font-size: 16px;
55
- cursor: pointer;
56
- }
57
- .stButton button:hover {
58
- background-color: #357ABD;
59
- }
60
- .markdown-text-container {
61
- margin-top: 20px;
62
- }
63
- .highlight {
64
- color: #d9534f;
65
- font-weight: bold;
66
- }
67
- .meaning {
68
- color: #5cb85c;
69
- font-style: italic;
70
- }
71
- </style>
72
- """
73
- st.markdown(custom_css, unsafe_allow_html=True)
74
-
75
- st.title("Correct Spelling Mistakes App")
76
-
77
- # Load mô hình
78
- model_checkpoint = "Diezu/bat_pho_bo" # Thay đổi checkpoint phù hợp
79
- correct_spelling = pipeline("text2text-generation", model=model_checkpoint)
80
-
81
- # Nhập liệu từ người dùng
82
- context = st.text_area("Input text", placeholder="Nhập văn bản có lỗi chính tả...")
83
-
84
- # Xử lý nút bấm
85
- if st.button("Get Result"):
86
- if context.strip():
87
- try:
88
- # Sử dụng pipeline để sửa lỗi chính tả
89
- result = correct_spelling(context, max_length=MAX_LENGTH)
90
- corrected_text = result[0]['generated_text'] if result else "No output generated."
91
-
92
- # So sánh và làm nổi bật sự khác biệt
93
- def highlight_differences_with_meaning(original, corrected):
94
- highlighted_text = []
95
- matcher = difflib.SequenceMatcher(None, original, corrected)
96
- for tag, i1, i2, j1, j2 in matcher.get_opcodes():
97
- if tag == 'replace': # Nếu đoạn văn bị thay thế
98
- word = corrected[j1:j2]
99
- meaning = get_word_meaning(word)
100
- highlighted_text.append(
101
- f"<span class='highlight'>{word}</span> <span class='meaning'>({meaning})</span>"
102
- )
103
- elif tag == 'insert': # Nếu đoạn mới được thêm
104
- word = corrected[j1:j2]
105
- meaning = get_word_meaning(word)
106
- highlighted_text.append(
107
- f"<span class='highlight'>{word}</span> <span class='meaning'>({meaning})</span>"
108
- )
109
- elif tag == 'delete': # Nếu đoạn bị xóa
110
- highlighted_text.append(f"<span class='highlight'>{original[i1:i2]}</span>")
111
- else: # Nếu đoạn không thay đổi
112
- highlighted_text.append(corrected[j1:j2])
113
- return "".join(highlighted_text)
114
-
115
- # Làm nổi bật các thay đổi với ngữ nghĩa
116
- highlighted_text = highlight_differences_with_meaning(context, corrected_text)
117
-
118
- # Hiển thị kết quả
119
- st.markdown(f"### Corrected Text (with highlighted changes):\n\n{highlighted_text}", unsafe_allow_html=True)
120
- except Exception as e:
121
- st.error(f"An error occurred: {e}")
122
  else:
123
- st.warning("Please input some text to process!")
 
1
  import streamlit as st
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification # Thay bằng mô hình của bạn
3
+ import torch
4
+
5
+ # Load hình (thay thế bằng mô hình sửa lỗi chính tả của bạn)
6
+ @st.cache_resource
7
+ def load_model():
8
+ tokenizer = AutoTokenizer.from_pretrained("Diezu/bat_pho_bo") # Thay bằng tên hình của bạn
9
+ model = AutoModelForSequenceClassification.from_pretrained("Diezu/bat_pho_bo")
10
+ return tokenizer, model
11
+
12
+ # Hàm phát hiện lỗi chính tả
13
+ def detect_errors(text, tokenizer, model):
14
+ errors = []
15
+ words = text.split()
16
+
17
+ for word in words:
18
+ inputs = tokenizer(word, return_tensors="pt", padding=True, truncation=True)
19
+ with torch.no_grad():
20
+ outputs = model(**inputs)
21
+
22
+ # Xử lý kết quả để phát hiện lỗi (giả sử lớp "1" là từ sai)
23
+ probabilities = torch.softmax(outputs.logits, dim=-1)
24
+ predicted_class = torch.argmax(probabilities, dim=-1).item()
25
+
26
+ if predicted_class == 1: # Nếu từ sai
27
+ errors.append(word)
28
+
29
+ return errors
30
+
31
+ # Streamlit App
32
+ st.title("Công cụ phát hiện lỗi chính tả")
33
+
34
+ # Tải mô hình
35
+ tokenizer, model = load_model()
36
+
37
+ # Nhập văn bản
38
+ input_text = st.text_area("Nhập văn bản của bạn tại đây:", height=200)
39
+
40
+ if st.button("Phát hiện lỗi"):
41
+ if input_text.strip():
42
+ # Phát hiện lỗi
43
+ errors = detect_errors(input_text, tokenizer, model)
44
+ if errors:
45
+ st.subheader("Các từ phát hiện lỗi:")
46
+ st.write(", ".join(f"**{word}**" for word in errors))
47
+ else:
48
+ st.success("Không phát hiện lỗi nào trong văn bản.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  else:
50
+ st.warning("Vui lòng nhập văn bản để kiểm tra.")