bvd757 commited on
Commit
b57276f
·
1 Parent(s): d7fc09f
Files changed (1) hide show
  1. app.py +33 -29
app.py CHANGED
@@ -90,7 +90,7 @@ def main():
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="window.parent.postMessage({{index: {index}}}, \'*\')" '
94
  f'title="Кликните для подробностей">'
95
  f'{html.escape(text[error["start"]:error["end"]])}'
96
  f'</span>'
@@ -99,6 +99,9 @@ def main():
99
 
100
  highlighted.append(html.escape(text[last_pos:]))
101
 
 
 
 
102
  html_content = f"""
103
  <div style="
104
  background: white;
@@ -111,43 +114,44 @@ def main():
111
  ">
112
  {''.join(highlighted)}
113
  </div>
 
 
 
 
 
 
 
 
114
  """
115
 
116
- st.markdown("### Результат проверки:")
117
- st.markdown(html_content, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- # JavaScript для обработки кликов
120
  st.markdown("""
121
  <script>
122
- window.addEventListener('message', function(event) {
123
- if (event.data.index !== undefined) {
124
- const index = event.data.index;
125
- // Отправляем индекс в Streamlit
126
- const streamlitDoc = window.parent.document;
127
- const iframe = streamlitDoc.querySelector('iframe[data-testid="stIFrame"]');
128
- if (iframe) {
129
- iframe.contentWindow.postMessage({type: 'streamlit:setComponentValue', value: index}, '*');
130
- }
131
  }
132
  });
133
  </script>
134
  """, unsafe_allow_html=True)
135
 
136
- # Создаем компонент для получения индекса ошибки
137
- clicked_error = st.session_state.get('clicked_error', None)
138
-
139
- # Обработка кликов через custom component
140
- if clicked_error is not None:
141
- st.session_state.selected_error = clicked_error
142
-
143
- # Обработка выбранной ошибки
144
- if 'selected_error' in st.session_state and st.session_state.selected_error is not None:
145
- error = sorted_errors[st.session_state.selected_error]
146
- st.markdown("### Описание ошибки:")
147
- st.markdown(f"**Ошибка {st.session_state.selected_error + 1}**: {error['message']}")
148
- else:
149
- st.markdown("### Найденные ошибки:")
150
- st.markdown("🔍 **Кликните на выделенный текст, чтобы увидеть описание ошибки**")
151
-
152
  if __name__ == "__main__":
153
  main()
 
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>'
 
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;
 
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, key="highlighter")
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()