bvd757 commited on
Commit
184117d
·
1 Parent(s): df88e6c
Files changed (1) hide show
  1. app.py +75 -92
app.py CHANGED
@@ -1,28 +1,35 @@
1
- import streamlit as st
2
  import language_tool_python
 
 
3
  import subprocess
 
4
  import html
5
- import openai
6
 
7
  is_java_installed = False
8
 
 
9
  def install_java():
10
  global is_java_installed
11
  if is_java_installed: return
12
  try:
 
13
  subprocess.run(["apt-get", "update"], check=True)
14
  subprocess.run(["apt-get", "install", "-y", "openjdk-17-jdk"], check=True)
 
15
  is_java_installed = True
16
  except Exception as e:
17
  st.error(f"Ошибка установки Java: {e}")
18
 
 
19
  @st.cache_resource
20
  def load_assets():
21
  openai.api_key = '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'
22
  install_java()
23
- tool = language_tool_python.LanguageTool('ru-RU', language_tool_download_version="6.1")
 
24
  return tool
25
 
 
26
  def generate_gpt_comment(message, context):
27
  response = openai.ChatCompletion.create(
28
  model="gpt-4o",
@@ -32,6 +39,7 @@ def generate_gpt_comment(message, context):
32
  )
33
  return response.choices[0].message['content']
34
 
 
35
  def check_text(text, tool):
36
  matches = tool.check(text)
37
  errors = []
@@ -44,114 +52,89 @@ def check_text(text, tool):
44
  errors.append(error_info)
45
  return errors
46
 
 
47
  def main():
48
  st.markdown("""
49
  <style>
 
 
 
 
 
 
50
  .error-highlight {
51
  background-color: #ffe066;
52
  border-bottom: 2px dotted #ff9900;
53
- cursor: pointer;
54
- color: black !important;
55
  }
56
- .error-highlight:hover {
57
- background-color: #ffd700;
 
 
 
 
 
 
 
58
  }
59
  </style>
60
  """, unsafe_allow_html=True)
61
 
 
62
  st.title('Проверка орфографии')
63
-
64
- # Сохраняем текст в session_state
65
- text_input = st.text_area("Введите текст для проверки:",
66
- value=st.session_state.get('text_to_check', ''),
67
- height=200)
68
- text = text_input.replace("\n", " ")
69
  tool = load_assets()
70
 
71
  if st.button('Проверить текст'):
72
- st.session_state.text_to_check = text_input
73
  if not text.strip():
74
  st.warning("Введите текст для проверки")
75
  else:
76
  errors = check_text(text, tool)
77
- st.session_state.errors = errors
78
- st.session_state.sorted_errors = sorted(errors, key=lambda x: x['start'])
79
- st.session_state.selected_error = None # Сброс выбранной ошибки
80
-
81
- # Используем сохраненные ошибки при наличии
82
- errors = st.session_state.get('errors', [])
83
- sorted_errors = st.session_state.get('sorted_errors', [])
84
-
85
- if errors:
86
- # Генерация HTML с кликабельными ошибками
87
- highlighted = []
88
- last_pos = 0
89
-
90
- for index, error in enumerate(sorted_errors):
91
- highlighted.append(html.escape(text[last_pos:error['start']]))
92
- highlighted.append(
93
- f'<span class="error-highlight" onclick="handleClick({index})" '
94
- f'title="Кликните для подробностей">'
95
- f'{html.escape(text[error["start"]:error["end"]])}'
96
- f'</span>'
97
- )
98
- last_pos = error['end']
99
-
100
- highlighted.append(html.escape(text[last_pos:]))
101
-
102
- # Создаем кастомный компонент
103
- clicked_index = st.session_state.get("clicked_index", None)
104
-
105
- html_content = f"""
106
- <div style="
107
- background: white;
108
- padding: 20px;
109
- border-radius: 8px;
110
- border: 1px solid #ddd;
111
- white-space: pre-wrap;
112
- font-family: monospace;
113
- color: #000000;
114
- ">
115
- {''.join(highlighted)}
116
- </div>
117
- <script>
118
- function handleClick(index) {{
119
- window.parent.postMessage({{
120
- type: 'streamlit:setComponentValue',
121
- value: index
122
- }}, '*');
123
- }}
124
- </script>
125
- """
126
-
127
- # Рендерим через кастомный компонент
128
- st.components.v1.html(html_content, height=300)
129
-
130
- # Обрабатываем клик
131
- if st.session_state.get("clicked_index") is not None:
132
- selected_index = st.session_state.clicked_index
133
- error = sorted_errors[selected_index]
134
- st.markdown("### Описание ошибки:")
135
- st.markdown(f"**Ошибка {selected_index + 1}**: {error['message']}")
136
- # Сбрасываем состояние после показа
137
- st.session_state.clicked_index = None
138
- else:
139
- st.markdown("### Найденные ошибки:")
140
- st.markdown("🔍 **Кликните на выделенный текст, чтобы увидеть описание ошибки**")
141
-
142
- # Добавляем обработчик сообщений
143
- st.markdown("""
144
- <script>
145
- window.addEventListener("message", (event) => {
146
- if (event.data.type === 'streamlit:setComponentValue') {
147
- window.parent.postMessage({
148
- type: 'streamlit:setComponentValue',
149
- value: event.data.value
150
- }, '*');
151
- }
152
- });
153
- </script>
154
- """, unsafe_allow_html=True)
155
 
156
  if __name__ == "__main__":
157
  main()
 
 
1
  import language_tool_python
2
+ import openai
3
+ import streamlit as st
4
  import subprocess
5
+ from pathlib import Path
6
  import html
 
7
 
8
  is_java_installed = False
9
 
10
+
11
  def install_java():
12
  global is_java_installed
13
  if is_java_installed: return
14
  try:
15
+ # Устанавливаем OpenJDK 17
16
  subprocess.run(["apt-get", "update"], check=True)
17
  subprocess.run(["apt-get", "install", "-y", "openjdk-17-jdk"], check=True)
18
+ #st.success("Java 17 установлена!")
19
  is_java_installed = True
20
  except Exception as e:
21
  st.error(f"Ошибка установки Java: {e}")
22
 
23
+
24
  @st.cache_resource
25
  def load_assets():
26
  openai.api_key = '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'
27
  install_java()
28
+ tool = language_tool_python.LanguageTool('ru-RU',
29
+ language_tool_download_version="6.1")
30
  return tool
31
 
32
+
33
  def generate_gpt_comment(message, context):
34
  response = openai.ChatCompletion.create(
35
  model="gpt-4o",
 
39
  )
40
  return response.choices[0].message['content']
41
 
42
+
43
  def check_text(text, tool):
44
  matches = tool.check(text)
45
  errors = []
 
52
  errors.append(error_info)
53
  return errors
54
 
55
+
56
  def main():
57
  st.markdown("""
58
  <style>
59
+ /* Сохраняем белый текст для темной темы */
60
+ .stApp, .stTextInput, .stTextArea, .stMarkdown {
61
+ color: white;
62
+ }
63
+
64
+ /* Специальный стиль для текста внутри выделенных ошибок */
65
  .error-highlight {
66
  background-color: #ffe066;
67
  border-bottom: 2px dotted #ff9900;
68
+ position: relative;
69
+ color: black !important; /* Принудительно черный текст в выделениях */
70
  }
71
+
72
+ /* Стиль для контейнера с результатом */
73
+ .result-container {
74
+ background: rgba(255, 255, 255, 0.1);
75
+ padding: 20px;
76
+ border-radius: 8px;
77
+ border: 1px solid #444;
78
+ white-space: pre-wrap;
79
+ font-family: monospace;
80
  }
81
  </style>
82
  """, unsafe_allow_html=True)
83
 
84
+
85
  st.title('Проверка орфографии')
86
+ text = st.text_area("Введите текст для проверки:", height=200).replace("\n", " ")
 
 
 
 
 
87
  tool = load_assets()
88
 
89
  if st.button('Проверить текст'):
 
90
  if not text.strip():
91
  st.warning("Введите текст для проверки")
92
  else:
93
  errors = check_text(text, tool)
94
+
95
+ if not errors:
96
+ st.success("Ошибок не найдено! 👍")
97
+ else:
98
+ sorted_errors = sorted(errors, key=lambda x: x['start'])
99
+
100
+ highlighted = []
101
+ last_pos = 0
102
+
103
+ for error in sorted_errors:
104
+ highlighted.append(html.escape(text[last_pos:error['start']]))
105
+
106
+ highlighted.append(
107
+ f'<span style="background-color: #ffe066; border-bottom: 2px dotted #ff9900; '
108
+ f'position: relative;" title="{html.escape(error["message"])}">'
109
+ f'{html.escape(text[error["start"]:error["end"]])}'
110
+ f'</span>'
111
+ )
112
+
113
+ last_pos = error['end']
114
+
115
+ highlighted.append(html.escape(text[last_pos:]))
116
+
117
+ html_content = f"""
118
+ <div style="
119
+ background: white;
120
+ padding: 20px;
121
+ border-radius: 8px;
122
+ border: 1px solid #ddd;
123
+ white-space: pre-wrap;
124
+ font-family: monospace;
125
+ color: #000000;
126
+ ">
127
+ {''.join(highlighted)}
128
+ </div>
129
+ """
130
+
131
+ st.markdown("### Результат проверки:")
132
+ st.markdown(html_content, unsafe_allow_html=True)
133
+
134
+ st.markdown("### Найденные ошибки:")
135
+ for i, error in enumerate(errors, 1):
136
+ st.markdown(f"{i}. **Позиция {error['start']}-{error['end']}**: {error['message']}")
137
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  if __name__ == "__main__":
140
  main()