File size: 7,387 Bytes
77619f4
4dce3bb
184117d
e3c1e1d
2c0b608
a52faf6
0498a33
21ba2b3
0498a33
a52faf6
7bf3b1f
184117d
e3c1e1d
41c1169
7bf3b1f
e3c1e1d
184117d
e3c1e1d
 
184117d
7bf3b1f
e3c1e1d
 
 
184117d
a52faf6
 
9919e6f
407e6f0
cbc6a55
 
a52faf6
 
184117d
0e52473
 
 
 
 
0498a33
 
a52faf6
285e310
2eb0a24
184117d
 
 
 
4a7c0ee
 
 
 
 
184117d
 
2eb0a24
 
 
184117d
 
2eb0a24
184117d
 
 
 
 
 
 
 
 
77619f4
bdef6b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eb0a24
 
 
a52faf6
0498a33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a532349
3588612
aa68abd
a52faf6
 
 
 
 
071bea9
0e52473
184117d
b24410c
184117d
 
74077d8
 
 
 
 
 
 
184117d
 
 
 
74077d8
184117d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159ea49
184117d
 
 
 
74077d8
 
0498a33
184117d
47cd49c
a52faf6
77619f4
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import language_tool_python
import openai
import streamlit as st
import subprocess
from search_errors_logic import check_text
import html
import docx
import mammoth
from io import BytesIO

is_java_installed = False

def install_java():
    global is_java_installed
    if is_java_installed: return
    try:
        # Устанавливаем OpenJDK 17
        subprocess.run(["apt-get", "update"], check=True)
        subprocess.run(["apt-get", "install", "-y", "openjdk-17-jdk"], check=True)
        #st.success("Java 17 установлена!")
        is_java_installed = True
    except Exception as e:
        st.error(f"Ошибка установки Java: {e}")


@st.cache_resource
def load_assets():
    openai.api_key = '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'
    #install_java()
    #tool = language_tool_python.LanguageTool('ru-RU', language_tool_download_version="6.1")
    tool = None
    return tool


def extract_text_from_docx(file):
    text = mammoth.convert_to_markdown(file).value
    for symbol in ".,!?()[]:;":
        text = text.replace(f"\{symbol}", symbol)
    return text


def main():
    st.markdown("""
        <style>
            /* Сохраняем белый текст для темной темы */
            .stApp, .stTextInput, .stTextArea, .stMarkdown {
                color: white;
            }
                
            /* цвет фона */
            .stApp {
                background-color: #0E1117;
            }
            
            /* Специальный стиль для текста внутри выделенных ошибок */
            .error-highlight {
                background-color: #ffe066;
                border-bottom: 2px dotted #ff9900;
                position: relative;
                color: black !important;  /* Принудительно черный текст в выделениях */
            }
            
            /* Стиль для контейнера с результатом */
            .result-container {
                background: rgba(255, 255, 255, 0.1);
                padding: 20px;
                border-radius: 8px;
                border: 1px solid #444;
                white-space: pre-wrap;
                font-family: monospace;
            }
            
            /* Основные стили для белого текста */
            body, .stApp, .stTextInput, .stTextArea, .stMarkdown, 
            .stRadio, .stButton, .stFileUploader, .stAlert,
            .stSuccess, .stWarning, .stError, .stInfo {
                color: white !important;
            }

            /* Текст в полях ввода */
            .stTextInput input, .stTextArea textarea {
                color: white !important;
            }

            /* Текст в radio кнопках */
            .stRadio label {
                color: white !important;
            }

            /* Текст в кнопках */
            .stButton button {
                color: white !important;
            }

            /* Текст в загрузчике файлов */
            .stFileUploader label {
                color: white !important;
            }

            /* Заголовки */
            h1, h2, h3, h4, h5, h6 {
                color: white !important;
            }
        </style>
    """, unsafe_allow_html=True)

    st.title('Проверка орфографии')
    
    # Добавляем переключатель между режимами ввода
    input_mode = st.radio(
        "Выберите способ ввода текста:",
        ("Ввести текст вручную", "Загрузить Word документ"),
        horizontal=True
    )
    
    text = ""
    if input_mode == "Загрузить Word документ":
        uploaded_file = st.file_uploader("Загрузите Word документ", type=['docx'])
        if uploaded_file is not None:
            try:
                text = extract_text_from_docx(uploaded_file)
                st.text_area("Текст из документа:", value=text, height=200, key="docx_text")
            except Exception as e:
                st.error(f"Ошибка при чтении файла: {e}")
    else:
        text = st.text_area("Введите текст для проверки:", height=200, key="manual_text")

    tool = load_assets()

    if st.button('Проверить текст'):
        if not text.strip():
            st.warning("Введите текст для проверки")
        else:
            text, errors = check_text(text, tool, mode="chat_gpt", highlight_mode=True)
            #text = text.replace("\n", " ")
            if not errors:
                st.success("Ошибок не найдено.")
            else:
                sorted_errors = sorted(errors, key=lambda x: x['start'])

                errors_for_higlight = [sorted_errors[0].copy()]
                for error in sorted_errors[1:]:
                    if errors_for_higlight[-1]["end"] >= error["start"]:
                        errors_for_higlight[-1]["end"] = max(errors_for_higlight[-1]["end"], error["end"])
                    else:
                        errors_for_higlight.append(error)
                
                highlighted = []
                last_pos = 0
                
                for error in errors_for_higlight:
                    highlighted.append(html.escape(text[last_pos:error['start']]))
                    
                    highlighted.append(
                        f'<span style="background-color: #ffe066; border-bottom: 2px dotted #ff9900; '
                        f'position: relative;" title="{html.escape(error["message"])}">'
                        f'{html.escape(text[error["start"]:error["end"]])}'
                        f'</span>'
                    )
                    
                    last_pos = error['end']
                
                highlighted.append(html.escape(text[last_pos:]))
                
                html_content = f"""
                <div style="
                    background: white;
                    padding: 20px;
                    border-radius: 8px;
                    border: 1px solid #ddd;
                    white-space: pre-wrap;
                    font-family: monospace;
                    color: #000000; 
                ">
                    {''.join(highlighted)}
                </div>
                """
                
                st.markdown("_**Как это работает:** Если ошибки находятся рядом, они группируются под одним номером. Посмотрите комментарий — там будут все замечания по этому участку текста._")
                st.markdown("### Результат проверки:")
                st.markdown(html_content, unsafe_allow_html=True)
                
                st.markdown("### Найденные ошибки:")
                errors_in_order_for_print = sorted(errors, key=lambda x: x['end'])
                for i, error in enumerate(errors_in_order_for_print, 1):
                    st.markdown(f"{i}. {error['message']}")


if __name__ == "__main__":
    main()