MrSimple07 commited on
Commit
19e03d0
·
2 Parent(s): a9f5786 b38db64

Merge branch 'main' of https://huggingface.co/spaces/MrSimple01/RAG_AIEXP_01

Browse files
Files changed (3) hide show
  1. .gitattributes +3 -0
  2. documents_prep.py +0 -1
  3. utils.py +271 -0
.gitattributes CHANGED
@@ -34,9 +34,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  *.json filter=lfs diff=lfs merge=lfs -text
 
37
  *.png filter=lfs diff=lfs merge=lfs -text
38
  *.jpg filter=lfs diff=lfs merge=lfs -text
39
  *.jpeg filter=lfs diff=lfs merge=lfs -text
40
  *.gif filter=lfs diff=lfs merge=lfs -text
41
  *.bmp filter=lfs diff=lfs merge=lfs -text
42
  *.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  *.json filter=lfs diff=lfs merge=lfs -text
37
+ <<<<<<< HEAD
38
  *.png filter=lfs diff=lfs merge=lfs -text
39
  *.jpg filter=lfs diff=lfs merge=lfs -text
40
  *.jpeg filter=lfs diff=lfs merge=lfs -text
41
  *.gif filter=lfs diff=lfs merge=lfs -text
42
  *.bmp filter=lfs diff=lfs merge=lfs -text
43
  *.pdf filter=lfs diff=lfs merge=lfs -text
44
+ =======
45
+ >>>>>>> b38db646fba42cf62de437de07713765675b4628
documents_prep.py CHANGED
@@ -13,7 +13,6 @@ def chunk_document(doc, chunk_size=None, chunk_overlap=None):
13
  chunk_size = CHUNK_SIZE
14
  if chunk_overlap is None:
15
  chunk_overlap = CHUNK_OVERLAP
16
-
17
  text_splitter = SentenceSplitter(
18
  chunk_size=chunk_size,
19
  chunk_overlap=chunk_overlap,
 
13
  chunk_size = CHUNK_SIZE
14
  if chunk_overlap is None:
15
  chunk_overlap = CHUNK_OVERLAP
 
16
  text_splitter = SentenceSplitter(
17
  chunk_size=chunk_size,
18
  chunk_overlap=chunk_overlap,
utils.py CHANGED
@@ -226,6 +226,277 @@ def answer_question(question, query_engine, reranker, current_model, chunks_df=N
226
  Контекст из базы данных:
227
  {formatted_context}
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  Вопрос пользователя: {question}"""
230
 
231
  response = query_engine.query(enhanced_question)
 
226
  Контекст из базы данных:
227
  {formatted_context}
228
 
229
+ Вопрос пользователя: {question}"""
230
+
231
+ response = query_engine.query(enhanced_question)
232
+
233
+ log_message(f"ОТВЕТ LLM: {response.response}")
234
+
235
+ end_time = time.time()
236
+ processing_time = end_time - start_time
237
+
238
+ log_message(f"Обработка завершена за {processing_time:.2f} секунд")
239
+
240
+ sources_html = generate_sources_html(reranked_nodes, chunks_df)
241
+
242
+ answer_with_time = f"""<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; margin-bottom: 10px;'>
243
+ <h3 style='color: #63b3ed; margin-top: 0;'>Ответ (Модель: {current_model}):</h3>
244
+ <div style='line-height: 1.6; font-size: 16px;'>{response.response}</div>
245
+ <div style='margin-top: 15px; padding-top: 10px; border-top: 1px solid #4a5568; font-size: 14px; color: #a0aec0;'>
246
+ Время обработки: {processing_time:.2f} секунд
247
+ </div>
248
+ </div>"""
249
+
250
+ chunk_info = []
251
+ for node in reranked_nodes:
252
+ section_id = node.metadata.get('section_id', node.metadata.get('section', 'unknown'))
253
+ chunk_info.append({
254
+ 'document_id': node.metadata.get('document_id', 'unknown'),
255
+ 'section_id': section_id,
256
+ 'chunk_size': len(node.text),
257
+ 'chunk_text': node.text
258
+ })
259
+ from app import create_chunks_display_html
260
+ chunks_html = create_chunks_display_html(chunk_info)
261
+
262
+ return answer_with_time, sources_html, chunks_html
263
+
264
+ except Exception as e:
265
+ log_message(f"Ошибка обработки вопроса: {str(e)}")
266
+ error_msg = f"<div style='background-color: #e53e3e; color: white; padding: 20px; border-radius: 10px;'>Ошибка обработки вопроса: {str(e)}</div>"
267
+ return error_msg, ""
268
+ import logging
269
+ import sys
270
+ from llama_index.llms.google_genai import GoogleGenAI
271
+ from llama_index.llms.openai import OpenAI
272
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
273
+ from sentence_transformers import CrossEncoder
274
+ from config import AVAILABLE_MODELS, DEFAULT_MODEL, GOOGLE_API_KEY
275
+ import time
276
+ from index_retriever import rerank_nodes
277
+ from my_logging import log_message
278
+ from config import PROMPT_SIMPLE_POISK
279
+
280
+ def get_llm_model(model_name):
281
+ try:
282
+ model_config = AVAILABLE_MODELS.get(model_name)
283
+ if not model_config:
284
+ log_message(f"Модель {model_name} не найдена, использую модель по умолчанию")
285
+ model_config = AVAILABLE_MODELS[DEFAULT_MODEL]
286
+
287
+ if not model_config.get("api_key"):
288
+ raise Exception(f"API ключ не найден для модели {model_name}")
289
+
290
+ if model_config["provider"] == "google":
291
+ return GoogleGenAI(
292
+ model=model_config["model_name"],
293
+ api_key=model_config["api_key"]
294
+ )
295
+ elif model_config["provider"] == "openai":
296
+ return OpenAI(
297
+ model=model_config["model_name"],
298
+ api_key=model_config["api_key"]
299
+ )
300
+ else:
301
+ raise Exception(f"Неподдерживаемый провайдер: {model_config['provider']}")
302
+
303
+ except Exception as e:
304
+ log_message(f"Ошибка создания модели {model_name}: {str(e)}")
305
+ return GoogleGenAI(model="gemini-2.0-flash", api_key=GOOGLE_API_KEY)
306
+
307
+ def get_embedding_model(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"):
308
+ return HuggingFaceEmbedding(model_name=model_name)
309
+
310
+ def get_reranker_model(model_name='cross-encoder/ms-marco-MiniLM-L-12-v2'):
311
+ return CrossEncoder(model_name)
312
+
313
+ def format_context_for_llm(nodes):
314
+ context_parts = []
315
+
316
+ for node in nodes:
317
+ metadata = node.metadata if hasattr(node, 'metadata') else {}
318
+ doc_id = metadata.get('document_id', 'Неизвестный документ')
319
+
320
+ section_info = ""
321
+
322
+ if metadata.get('section_path'):
323
+ section_path = metadata['section_path']
324
+ section_text = metadata.get('section_text', '')
325
+ parent_section = metadata.get('parent_section', '')
326
+ parent_title = metadata.get('parent_title', '')
327
+
328
+ if metadata.get('level') in ['subsection', 'sub_subsection', 'sub_sub_subsection'] and parent_section and parent_title:
329
+ section_info = f"пункт {section_path} ({section_text}) в разделе {parent_section} ({parent_title})"
330
+ elif section_text:
331
+ section_info = f"пункт {section_path} ({section_text})"
332
+ else:
333
+ section_info = f"пунк�� {section_path}"
334
+ elif metadata.get('section_id'):
335
+ section_id = metadata['section_id']
336
+ section_text = metadata.get('section_text', '')
337
+ if section_text:
338
+ section_info = f"пункт {section_id} ({section_text})"
339
+ else:
340
+ section_info = f"пункт {section_id}"
341
+
342
+ if metadata.get('type') == 'table' and metadata.get('table_number'):
343
+ table_num = metadata['table_number']
344
+ if not str(table_num).startswith('№'):
345
+ table_num = f"№{table_num}"
346
+ section_info = f"таблица {table_num}"
347
+
348
+ if metadata.get('type') == 'image' and metadata.get('image_number'):
349
+ image_num = metadata['image_number']
350
+ if not str(image_num).startswith('№'):
351
+ image_num = f"№{image_num}"
352
+ section_info = f"рисунок {image_num}"
353
+
354
+ context_text = node.text if hasattr(node, 'text') else str(node)
355
+
356
+ if section_info:
357
+ formatted_context = f"[ИСТОЧНИК: {section_info} документа {doc_id}]\n{context_text}\n"
358
+ else:
359
+ formatted_context = f"[ИСТОЧНИК: документ {doc_id}]\n{context_text}\n"
360
+
361
+ context_parts.append(formatted_context)
362
+
363
+ return "\n".join(context_parts)
364
+
365
+ def generate_sources_html(nodes, chunks_df=None):
366
+ html = "<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; max-height: 400px; overflow-y: auto;'>"
367
+ html += "<h3 style='color: #63b3ed; margin-top: 0;'>Источники:</h3>"
368
+
369
+ # Group nodes by document to avoid duplicates
370
+ sources_by_doc = {}
371
+
372
+ for i, node in enumerate(nodes):
373
+ metadata = node.metadata if hasattr(node, 'metadata') else {}
374
+ doc_type = metadata.get('type', 'text')
375
+ doc_id = metadata.get('document_id', 'unknown')
376
+ section_id = metadata.get('section_id', '')
377
+ section_text = metadata.get('section_text', '')
378
+ section_path = metadata.get('section_path', '')
379
+
380
+ # Create a unique key for grouping
381
+ if doc_type == 'table':
382
+ table_num = metadata.get('table_number', 'unknown')
383
+ key = f"{doc_id}_table_{table_num}"
384
+ elif doc_type == 'image':
385
+ image_num = metadata.get('image_number', 'unknown')
386
+ key = f"{doc_id}_image_{image_num}"
387
+ else:
388
+ # For text documents, group by section path or section id
389
+ section_key = section_path if section_path else section_id
390
+ key = f"{doc_id}_text_{section_key}"
391
+
392
+ if key not in sources_by_doc:
393
+ sources_by_doc[key] = {
394
+ 'doc_id': doc_id,
395
+ 'doc_type': doc_type,
396
+ 'metadata': metadata,
397
+ 'sections': set()
398
+ }
399
+
400
+ # Add section information
401
+ if section_path:
402
+ sources_by_doc[key]['sections'].add(f"пункт {section_path}")
403
+ elif section_id and section_id != 'unknown':
404
+ sources_by_doc[key]['sections'].add(f"пункт {section_id}")
405
+
406
+ # Generate HTML for each unique source
407
+ for source_info in sources_by_doc.values():
408
+ metadata = source_info['metadata']
409
+ doc_type = source_info['doc_type']
410
+ doc_id = source_info['doc_id']
411
+
412
+ html += f"<div style='margin-bottom: 15px; padding: 15px; border: 1px solid #4a5568; border-radius: 8px; background-color: #1a202c;'>"
413
+
414
+ if doc_type == 'text':
415
+ html += f"<h4 style='margin: 0 0 10px 0; color: #63b3ed;'>📄 {doc_id}</h4>"
416
+ # Show all sections for this document
417
+ if source_info['sections']:
418
+ sections_text = ", ".join(sorted(source_info['sections']))
419
+ html += f"<p style='margin: 5px 0; color: #a0aec0; font-size: 14px;'>{sections_text}</p>"
420
+
421
+ elif doc_type == 'table' or doc_type == 'table_row':
422
+ table_num = metadata.get('table_number', 'unknown')
423
+ table_title = metadata.get('table_title', '')
424
+ if table_num and table_num != 'unknown':
425
+ if not str(table_num).startswith('№'):
426
+ table_num = f"№{table_num}"
427
+ html += f"<h4 style='margin: 0 0 10px 0; color: #68d391;'>📊 Таблица {table_num} - {doc_id}</h4>"
428
+ if table_title and table_title != 'unknown':
429
+ html += f"<p style='margin: 5px 0; color: #a0aec0; font-size: 14px;'>{table_title}</p>"
430
+ else:
431
+ html += f"<h4 style='margin: 0 0 10px 0; color: #68d391;'>📊 Таблица - {doc_id}</h4>"
432
+
433
+ elif doc_type == 'image':
434
+ image_num = metadata.get('image_number', 'unknown')
435
+ image_title = metadata.get('image_title', '')
436
+ section = metadata.get('section', '')
437
+ if image_num and image_num != 'unknown':
438
+ if not str(image_num).startswith('№'):
439
+ image_num = f"№{image_num}"
440
+ html += f"<h4 style='margin: 0 0 10px 0; color: #fbb6ce;'>🖼️ Изображение {image_num} - {doc_id}</h4>"
441
+ if image_title and image_title != 'unknown':
442
+ html += f"<p style='margin: 5px 0; color: #a0aec0; font-size: 14px;'>{image_title}</p>"
443
+ if section and section != 'unknown':
444
+ html += f"<p style='margin: 5px 0; color: #a0aec0; font-size: 12px;'>Раздел: {section}</p>"
445
+ else:
446
+ html += f"<h4 style='margin: 0 0 10px 0; color: #fbb6ce;'>🖼️ Изображение - {doc_id}</h4>"
447
+
448
+ # Add file link if available
449
+ if chunks_df is not None and 'file_link' in chunks_df.columns and doc_type == 'text':
450
+ doc_rows = chunks_df[chunks_df['document_id'] == doc_id]
451
+ if not doc_rows.empty:
452
+ file_link = doc_rows.iloc[0]['file_link']
453
+ html += f"<a href='{file_link}' target='_blank' style='color: #68d391; text-decoration: none; font-size: 14px; display: inline-block; margin-top: 10px;'>🔗 Ссылка на документ</a><br>"
454
+
455
+ html += "</div>"
456
+
457
+ html += "</div>"
458
+ return html
459
+
460
+ def answer_question(question, query_engine, reranker, current_model, chunks_df=None):
461
+ if query_engine is None:
462
+ return "<div style='background-color: #e53e3e; color: white; padding: 20px; border-radius: 10px;'>Система не инициализирована</div>", ""
463
+
464
+ try:
465
+ log_message(f"Получен вопрос: {question}")
466
+ start_time = time.time()
467
+
468
+ # Извлечение узлов
469
+ retrieved_nodes = query_engine.retriever.retrieve(question)
470
+ log_message(f"Извлечено {len(retrieved_nodes)} узлов")
471
+
472
+ # ДЕТАЛЬНОЕ ЛОГИРОВАНИЕ ИСТОЧНИКОВ
473
+ log_message("=== ДЕТАЛЬНАЯ ИНФОРМАЦИЯ О НАЙДЕННЫХ УЗЛАХ ===")
474
+ for i, node in enumerate(retrieved_nodes):
475
+ log_message(f"Узел {i+1}:")
476
+ log_message(f" Документ: {node.metadata.get('document_id', 'unknown')}")
477
+ log_message(f" Тип: {node.metadata.get('type', 'unknown')}")
478
+ log_message(f" Раздел: {node.metadata.get('section_id', 'unknown')}")
479
+ log_message(f" Текст (первые 200 символов): {node.text[:200]}...")
480
+ log_message(f" Метаданные: {node.metadata}")
481
+
482
+ # Переранжировка
483
+ reranked_nodes = rerank_nodes(question, retrieved_nodes, reranker, top_k=10)
484
+
485
+ log_message("=== УЗЛЫ ПОСЛЕ ПЕРЕРАНЖИРОВКИ ===")
486
+ for i, node in enumerate(reranked_nodes):
487
+ log_message(f"Переранжированный узел {i+1}:")
488
+ log_message(f" Документ: {node.metadata.get('document_id', 'unknown')}")
489
+ log_message(f" Тип: {node.metadata.get('type', 'unknown')}")
490
+ log_message(f" Раздел: {node.metadata.get('section_id', 'unknown')}")
491
+ log_message(f" Полный текст: {node.text}")
492
+
493
+ formatted_context = format_context_for_llm(reranked_nodes)
494
+ log_message(f"ПОЛНЫЙ КОНТЕКСТ ДЛЯ LLM:\n{formatted_context}")
495
+
496
+ enhanced_question = f"""
497
+ Контекст из базы данных:
498
+ {formatted_context}
499
+
500
  Вопрос пользователя: {question}"""
501
 
502
  response = query_engine.query(enhanced_question)