Spaces:
Sleeping
Sleeping
Commit ·
c2a83c1
1
Parent(s): c81fd8c
Removed duplicate logs throughout all files
Browse files- chat_handler.py +0 -154
- documents_prep.py +11 -22
- utils.py +14 -0
chat_handler.py
DELETED
|
@@ -1,154 +0,0 @@
|
|
| 1 |
-
import time
|
| 2 |
-
import logging
|
| 3 |
-
|
| 4 |
-
logger = logging.getLogger(__name__)
|
| 5 |
-
|
| 6 |
-
def log_message(message):
|
| 7 |
-
logger.info(message)
|
| 8 |
-
print(message, flush=True)
|
| 9 |
-
|
| 10 |
-
class ChatHandler:
|
| 11 |
-
def __init__(self, index_retriever):
|
| 12 |
-
self.index_retriever = index_retriever
|
| 13 |
-
self.chat_history = []
|
| 14 |
-
|
| 15 |
-
def format_section_path(self, metadata):
|
| 16 |
-
parts = []
|
| 17 |
-
|
| 18 |
-
section_id = metadata.get('section_id')
|
| 19 |
-
if section_id and section_id != 'Unknown':
|
| 20 |
-
parts.append(section_id)
|
| 21 |
-
|
| 22 |
-
subsection_id = metadata.get('subsection_id')
|
| 23 |
-
if subsection_id and subsection_id != 'Unknown':
|
| 24 |
-
parts.append(subsection_id)
|
| 25 |
-
|
| 26 |
-
sub_subsection_id = metadata.get('sub_subsection_id')
|
| 27 |
-
if sub_subsection_id and sub_subsection_id != 'Unknown':
|
| 28 |
-
parts.append(sub_subsection_id)
|
| 29 |
-
|
| 30 |
-
sub_sub_subsection_id = metadata.get('sub_sub_subsection_id')
|
| 31 |
-
if sub_sub_subsection_id and sub_sub_subsection_id != 'Unknown':
|
| 32 |
-
parts.append(sub_sub_subsection_id)
|
| 33 |
-
|
| 34 |
-
return " → ".join(parts) if parts else "Основной раздел"
|
| 35 |
-
|
| 36 |
-
def generate_sources_html(self, nodes):
|
| 37 |
-
html = "<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; max-height: 400px; overflow-y: auto;'>"
|
| 38 |
-
html += "<h3 style='color: #63b3ed; margin-top: 0;'>Источники:</h3>"
|
| 39 |
-
|
| 40 |
-
for i, node in enumerate(nodes):
|
| 41 |
-
metadata = node.metadata if hasattr(node, 'metadata') else {}
|
| 42 |
-
doc_type = metadata.get('type', 'text')
|
| 43 |
-
doc_id = metadata.get('document_id', 'unknown')
|
| 44 |
-
|
| 45 |
-
html += f"<div style='margin-bottom: 15px; padding: 15px; border: 1px solid #4a5568; border-radius: 8px; background-color: #1a202c;'>"
|
| 46 |
-
|
| 47 |
-
if doc_type == 'text':
|
| 48 |
-
document_name = metadata.get('document_name', doc_id)
|
| 49 |
-
|
| 50 |
-
html += f"<h4 style='margin: 0 0 10px 0; color: #63b3ed;'>📄 {doc_id}</h4>"
|
| 51 |
-
html += f"<div style='color: #a0aec0; font-size: 13px; margin-bottom: 8px;'>{document_name}</div>"
|
| 52 |
-
|
| 53 |
-
elif doc_type == 'table':
|
| 54 |
-
table_num = metadata.get('table_number', 'unknown')
|
| 55 |
-
section = metadata.get('section', '')
|
| 56 |
-
if table_num and table_num != 'unknown':
|
| 57 |
-
if not table_num.startswith('№'):
|
| 58 |
-
table_num = f"№{table_num}"
|
| 59 |
-
html += f"<h4 style='margin: 0 0 10px 0; color: #68d391;'>📊 Таблица {table_num} - {doc_id}</h4>"
|
| 60 |
-
else:
|
| 61 |
-
html += f"<h4 style='margin: 0 0 10px 0; color: #68d391;'>📊 Таблица - {doc_id}</h4>"
|
| 62 |
-
if section:
|
| 63 |
-
html += f"<div style='color: #68d391; font-size: 14px;'>📍 {section}</div>"
|
| 64 |
-
|
| 65 |
-
elif doc_type == 'image':
|
| 66 |
-
image_num = metadata.get('image_number', 'unknown')
|
| 67 |
-
section = metadata.get('section', '')
|
| 68 |
-
if image_num and image_num != 'unknown':
|
| 69 |
-
if not str(image_num).startswith('№'):
|
| 70 |
-
image_num = f"№{image_num}"
|
| 71 |
-
html += f"<h4 style='margin: 0 0 10px 0; color: #fbb6ce;'>🖼️ Изображение {image_num} - {doc_id}</h4>"
|
| 72 |
-
else:
|
| 73 |
-
html += f"<h4 style='margin: 0 0 10px 0; color: #fbb6ce;'>🖼️ Изображение - {doc_id}</h4>"
|
| 74 |
-
if section:
|
| 75 |
-
html += f"<div style='color: #fbb6ce; font-size: 14px;'>📍 {section}</div>"
|
| 76 |
-
|
| 77 |
-
html += "</div>"
|
| 78 |
-
|
| 79 |
-
html += "</div>"
|
| 80 |
-
return html
|
| 81 |
-
|
| 82 |
-
def answer_question(self, question):
|
| 83 |
-
if not self.index_retriever.is_initialized():
|
| 84 |
-
return "<div style='background-color: #e53e3e; color: white; padding: 20px; border-radius: 10px;'>Система не инициализирована</div>", ""
|
| 85 |
-
|
| 86 |
-
try:
|
| 87 |
-
log_message(f"Получен вопрос: {question}")
|
| 88 |
-
current_model = self.index_retriever.get_current_model()
|
| 89 |
-
log_message(f"Используется модель: {current_model}")
|
| 90 |
-
start_time = time.time()
|
| 91 |
-
|
| 92 |
-
retrieved_nodes = self.index_retriever.retrieve_nodes(question)
|
| 93 |
-
|
| 94 |
-
if not retrieved_nodes:
|
| 95 |
-
return "<div style='background-color: #e53e3e; color: white; padding: 20px; border-radius: 10px;'>Не удалось найти релевантные документы</div>", ""
|
| 96 |
-
|
| 97 |
-
log_message(f"Отправляю запрос в LLM с {len(retrieved_nodes)} узлами")
|
| 98 |
-
response = self.index_retriever.query_engine.query(question)
|
| 99 |
-
|
| 100 |
-
end_time = time.time()
|
| 101 |
-
processing_time = end_time - start_time
|
| 102 |
-
|
| 103 |
-
log_message(f"Обработка завершена за {processing_time:.2f} секунд")
|
| 104 |
-
|
| 105 |
-
self.chat_history.append({
|
| 106 |
-
"question": question,
|
| 107 |
-
"answer": response.response,
|
| 108 |
-
"model": current_model,
|
| 109 |
-
"processing_time": processing_time,
|
| 110 |
-
"nodes_count": len(retrieved_nodes)
|
| 111 |
-
})
|
| 112 |
-
|
| 113 |
-
sources_html = self.generate_sources_html(retrieved_nodes)
|
| 114 |
-
|
| 115 |
-
answer_with_time = f"""<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; margin-bottom: 10px;'>
|
| 116 |
-
<h3 style='color: #63b3ed; margin-top: 0;'>Ответ (Модель: {current_model}):</h3>
|
| 117 |
-
<div style='line-height: 1.6; font-size: 16px;'>{response.response}</div>
|
| 118 |
-
<div style='margin-top: 15px; padding-top: 10px; border-top: 1px solid #4a5568; font-size: 14px; color: #a0aec0;'>
|
| 119 |
-
Время обработки: {processing_time:.2f} секунд
|
| 120 |
-
</div>
|
| 121 |
-
</div>"""
|
| 122 |
-
|
| 123 |
-
return answer_with_time, sources_html
|
| 124 |
-
|
| 125 |
-
except Exception as e:
|
| 126 |
-
log_message(f"Ошибка обработки вопроса: {str(e)}")
|
| 127 |
-
error_msg = f"<div style='background-color: #e53e3e; color: white; padding: 20px; border-radius: 10px;'>Ошибка обработки вопроса: {str(e)}</div>"
|
| 128 |
-
return error_msg, ""
|
| 129 |
-
|
| 130 |
-
def get_chat_history(self):
|
| 131 |
-
return self.chat_history
|
| 132 |
-
|
| 133 |
-
def clear_history(self):
|
| 134 |
-
self.chat_history = []
|
| 135 |
-
log_message("История чата очищена")
|
| 136 |
-
|
| 137 |
-
def get_history_html(self):
|
| 138 |
-
if not self.chat_history:
|
| 139 |
-
return "<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; text-align: center;'>История пуста</div>"
|
| 140 |
-
|
| 141 |
-
html = "<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; max-height: 500px; overflow-y: auto;'>"
|
| 142 |
-
html += "<h3 style='color: #63b3ed; margin-top: 0;'>История чата:</h3>"
|
| 143 |
-
|
| 144 |
-
for i, entry in enumerate(reversed(self.chat_history[-10:])):
|
| 145 |
-
html += f"<div style='margin-bottom: 20px; padding: 15px; border: 1px solid #4a5568; border-radius: 8px; background-color: #1a202c;'>"
|
| 146 |
-
html += f"<div style='color: #68d391; font-weight: bold; margin-bottom: 8px;'>Вопрос {len(self.chat_history) - i}:</div>"
|
| 147 |
-
html += f"<div style='margin-bottom: 10px; font-size: 14px;'>{entry['question']}</div>"
|
| 148 |
-
html += f"<div style='color: #63b3ed; font-weight: bold; margin-bottom: 8px;'>Ответ ({entry['model']}):</div>"
|
| 149 |
-
html += f"<div style='margin-bottom: 10px; font-size: 14px; line-height: 1.4;'>{entry['answer'][:300]}{'...' if len(entry['answer']) > 300 else ''}</div>"
|
| 150 |
-
html += f"<div style='color: #a0aec0; font-size: 12px;'>Время: {entry['processing_time']:.2f}с</div>"
|
| 151 |
-
html += "</div>"
|
| 152 |
-
|
| 153 |
-
html += "</div>"
|
| 154 |
-
return html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
documents_prep.py
CHANGED
|
@@ -44,39 +44,27 @@ def process_documents_with_chunking(documents):
|
|
| 44 |
all_chunked_docs = []
|
| 45 |
chunk_info = []
|
| 46 |
table_count = 0
|
|
|
|
| 47 |
image_count = 0
|
| 48 |
text_chunks_count = 0
|
| 49 |
-
custom_processed_count = 0
|
| 50 |
|
| 51 |
for doc in documents:
|
| 52 |
doc_type = doc.metadata.get('type', 'text')
|
| 53 |
|
| 54 |
if doc_type == 'table':
|
| 55 |
table_count += 1
|
| 56 |
-
|
| 57 |
-
table_num = doc.metadata.get('table_number', 'unknown')
|
| 58 |
-
from table_prep import get_custom_config
|
| 59 |
-
method_config = get_custom_config(doc_id, table_num)
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
'document_id': doc_id,
|
| 66 |
-
'section_id': doc.metadata.get('section_id', 'unknown'),
|
| 67 |
-
'chunk_id': 0,
|
| 68 |
-
'chunk_size': len(doc.text),
|
| 69 |
-
'chunk_preview': doc.text[:200] + "..." if len(doc.text) > 200 else doc.text,
|
| 70 |
-
'type': 'table',
|
| 71 |
-
'table_number': table_num,
|
| 72 |
-
'processing_method': method_config.get('method')
|
| 73 |
-
})
|
| 74 |
-
continue
|
| 75 |
|
| 76 |
-
|
| 77 |
if doc_size > CHUNK_SIZE:
|
| 78 |
chunked_docs = chunk_document(doc)
|
| 79 |
all_chunked_docs.extend(chunked_docs)
|
|
|
|
| 80 |
|
| 81 |
for i, chunk_doc in enumerate(chunked_docs):
|
| 82 |
chunk_info.append({
|
|
@@ -87,10 +75,11 @@ def process_documents_with_chunking(documents):
|
|
| 87 |
'chunk_preview': chunk_doc.text[:200] + "..." if len(chunk_doc.text) > 200 else chunk_doc.text,
|
| 88 |
'type': 'table',
|
| 89 |
'table_number': chunk_doc.metadata.get('table_number', 'unknown'),
|
| 90 |
-
'processing_method': '
|
| 91 |
})
|
| 92 |
else:
|
| 93 |
all_chunked_docs.append(doc)
|
|
|
|
| 94 |
chunk_info.append({
|
| 95 |
'document_id': doc.metadata.get('document_id', 'unknown'),
|
| 96 |
'section_id': doc.metadata.get('section_id', 'unknown'),
|
|
@@ -158,7 +147,7 @@ def process_documents_with_chunking(documents):
|
|
| 158 |
'type': 'text'
|
| 159 |
})
|
| 160 |
|
| 161 |
-
log_message(f"Таблицы: {table_count}
|
| 162 |
|
| 163 |
return all_chunked_docs, chunk_info
|
| 164 |
|
|
|
|
| 44 |
all_chunked_docs = []
|
| 45 |
chunk_info = []
|
| 46 |
table_count = 0
|
| 47 |
+
table_added_count = 0
|
| 48 |
image_count = 0
|
| 49 |
text_chunks_count = 0
|
|
|
|
| 50 |
|
| 51 |
for doc in documents:
|
| 52 |
doc_type = doc.metadata.get('type', 'text')
|
| 53 |
|
| 54 |
if doc_type == 'table':
|
| 55 |
table_count += 1
|
| 56 |
+
doc_size = len(doc.text)
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# Log table size
|
| 59 |
+
table_num = doc.metadata.get('table_number', 'unknown')
|
| 60 |
+
doc_id = doc.metadata.get('document_id', 'unknown')
|
| 61 |
+
log_message(f"Таблица {table_num} в документе {doc_id}: размер {doc_size} символов")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
# Always add table regardless of size or custom config
|
| 64 |
if doc_size > CHUNK_SIZE:
|
| 65 |
chunked_docs = chunk_document(doc)
|
| 66 |
all_chunked_docs.extend(chunked_docs)
|
| 67 |
+
table_added_count += len(chunked_docs)
|
| 68 |
|
| 69 |
for i, chunk_doc in enumerate(chunked_docs):
|
| 70 |
chunk_info.append({
|
|
|
|
| 75 |
'chunk_preview': chunk_doc.text[:200] + "..." if len(chunk_doc.text) > 200 else chunk_doc.text,
|
| 76 |
'type': 'table',
|
| 77 |
'table_number': chunk_doc.metadata.get('table_number', 'unknown'),
|
| 78 |
+
'processing_method': 'chunked'
|
| 79 |
})
|
| 80 |
else:
|
| 81 |
all_chunked_docs.append(doc)
|
| 82 |
+
table_added_count += 1
|
| 83 |
chunk_info.append({
|
| 84 |
'document_id': doc.metadata.get('document_id', 'unknown'),
|
| 85 |
'section_id': doc.metadata.get('section_id', 'unknown'),
|
|
|
|
| 147 |
'type': 'text'
|
| 148 |
})
|
| 149 |
|
| 150 |
+
log_message(f"Таблицы: всего {table_count}, добавлено {table_added_count}, Изображения: {image_count}, Текстовые чанки: {text_chunks_count}, Итого: {len(all_chunked_docs)}")
|
| 151 |
|
| 152 |
return all_chunked_docs, chunk_info
|
| 153 |
|
utils.py
CHANGED
|
@@ -379,6 +379,20 @@ def answer_question(question, query_engine, reranker, current_model, chunks_df=N
|
|
| 379 |
retrieved_nodes = query_engine.retriever.retrieve(question)
|
| 380 |
reranked_nodes = rerank_nodes(question, retrieved_nodes, reranker, top_k=10)
|
| 381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
formatted_context = format_context_for_llm(reranked_nodes)
|
| 383 |
|
| 384 |
enhanced_question = f"""
|
|
|
|
| 379 |
retrieved_nodes = query_engine.retriever.retrieve(question)
|
| 380 |
reranked_nodes = rerank_nodes(question, retrieved_nodes, reranker, top_k=10)
|
| 381 |
|
| 382 |
+
# Add after reranking, before formatting context:
|
| 383 |
+
log_message(f"=== НАЙДЕННЫЕ ЧАНКИ ПОСЛЕ ПЕРЕРАНЖИРОВКИ ===")
|
| 384 |
+
log_message(f"Всего найдено релевантных чанков: {len(reranked_nodes)}")
|
| 385 |
+
for i, node in enumerate(reranked_nodes, 1):
|
| 386 |
+
log_message(f"Чанк {i}/{len(reranked_nodes)}:")
|
| 387 |
+
log_message(f" Документ: {node.metadata.get('document_id', 'unknown')}")
|
| 388 |
+
log_message(f" Тип: {node.metadata.get('type', 'unknown')}")
|
| 389 |
+
log_message(f" Раздел: {node.metadata.get('section_id', 'unknown')}")
|
| 390 |
+
if node.metadata.get('type') == 'table':
|
| 391 |
+
log_message(f" Таблица: {node.metadata.get('table_number', 'unknown')}")
|
| 392 |
+
log_message(f" Размер: {len(node.text)} символов")
|
| 393 |
+
log_message(f" Превью: {node.text[:150]}...")
|
| 394 |
+
log_message("-" * 50)
|
| 395 |
+
|
| 396 |
formatted_context = format_context_for_llm(reranked_nodes)
|
| 397 |
|
| 398 |
enhanced_question = f"""
|