Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,7 @@ from config import (
|
|
| 10 |
HF_REPO_ID, HF_TOKEN, DOWNLOAD_DIR, CHUNKS_FILENAME,
|
| 11 |
JSON_FILES_DIR, TABLE_DATA_DIR, IMAGE_DATA_DIR, DEFAULT_MODEL, AVAILABLE_MODELS
|
| 12 |
)
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def merge_table_chunks(chunk_info):
|
|
@@ -39,7 +40,6 @@ def merge_table_chunks(chunk_info):
|
|
| 39 |
|
| 40 |
return list(merged.values())
|
| 41 |
|
| 42 |
-
|
| 43 |
def create_chunks_display_html(chunk_info):
|
| 44 |
if not chunk_info:
|
| 45 |
return "<div style='padding: 20px; text-align: center; color: black;'>Нет данных о чанках</div>"
|
|
@@ -142,19 +142,14 @@ def initialize_system(repo_id, hf_token, download_dir, chunks_filename=None,
|
|
| 142 |
separator=" ",
|
| 143 |
backup_separators=["\n", ".", "!", "?"]
|
| 144 |
)
|
| 145 |
-
|
| 146 |
-
log_message(f"Configured chunk size: {CHUNK_SIZE} tokens")
|
| 147 |
-
log_message(f"Configured chunk overlap: {CHUNK_OVERLAP} tokens")
|
| 148 |
|
| 149 |
all_documents = []
|
| 150 |
chunks_df = None
|
| 151 |
|
| 152 |
-
# CHANGED: Use load_all_documents instead of loading separately
|
| 153 |
if use_json_instead_csv and json_files_dir:
|
| 154 |
log_message("Используем JSON файлы вместо CSV")
|
| 155 |
from documents_prep import load_all_documents
|
| 156 |
|
| 157 |
-
# This will handle text, tables, and images all together with proper logging
|
| 158 |
all_documents = load_all_documents(
|
| 159 |
repo_id=repo_id,
|
| 160 |
hf_token=hf_token,
|
|
@@ -163,12 +158,10 @@ def initialize_system(repo_id, hf_token, download_dir, chunks_filename=None,
|
|
| 163 |
image_dir=image_data_dir if image_data_dir else ""
|
| 164 |
)
|
| 165 |
else:
|
| 166 |
-
# OLD PATH: Loading separately (fallback)
|
| 167 |
if chunks_filename:
|
| 168 |
log_message("Загружаем данные из CSV")
|
| 169 |
|
| 170 |
if table_data_dir:
|
| 171 |
-
log_message("Добавляю табличные данные")
|
| 172 |
from documents_prep import load_table_documents
|
| 173 |
|
| 174 |
table_chunks = load_table_documents(repo_id, hf_token, table_data_dir)
|
|
@@ -176,7 +169,6 @@ def initialize_system(repo_id, hf_token, download_dir, chunks_filename=None,
|
|
| 176 |
all_documents.extend(table_chunks)
|
| 177 |
|
| 178 |
if image_data_dir:
|
| 179 |
-
log_message("Добавляю данные изображений")
|
| 180 |
from documents_prep import load_image_documents
|
| 181 |
|
| 182 |
image_documents = load_image_documents(repo_id, hf_token, image_data_dir)
|
|
@@ -188,7 +180,6 @@ def initialize_system(repo_id, hf_token, download_dir, chunks_filename=None,
|
|
| 188 |
vector_index = create_vector_index(all_documents)
|
| 189 |
query_engine = create_query_engine(vector_index)
|
| 190 |
|
| 191 |
-
# Create chunk_info for display (extract from documents metadata)
|
| 192 |
chunk_info = []
|
| 193 |
for doc in all_documents:
|
| 194 |
chunk_info.append({
|
|
@@ -233,7 +224,6 @@ def switch_model(model_name, vector_index):
|
|
| 233 |
log_message(error_msg)
|
| 234 |
return None, f"❌ {error_msg}"
|
| 235 |
|
| 236 |
-
# Add these global variables near the top with other globals
|
| 237 |
retrieval_params = {
|
| 238 |
'vector_top_k': 50,
|
| 239 |
'bm25_top_k': 50,
|
|
@@ -242,14 +232,12 @@ retrieval_params = {
|
|
| 242 |
'rerank_top_k': 20
|
| 243 |
}
|
| 244 |
|
| 245 |
-
# MODIFIED: Update create_query_engine call signature
|
| 246 |
def create_query_engine(vector_index, vector_top_k=50, bm25_top_k=50,
|
| 247 |
similarity_cutoff=0.55, hybrid_top_k=100):
|
| 248 |
try:
|
| 249 |
from config import CUSTOM_PROMPT
|
| 250 |
from index_retriever import create_query_engine as create_index_query_engine
|
| 251 |
|
| 252 |
-
# Pass parameters to the index_retriever function
|
| 253 |
query_engine = create_index_query_engine(
|
| 254 |
vector_index=vector_index,
|
| 255 |
vector_top_k=vector_top_k,
|
|
@@ -266,7 +254,6 @@ def create_query_engine(vector_index, vector_top_k=50, bm25_top_k=50,
|
|
| 266 |
log_message(f"Ошибка создания query engine: {str(e)}")
|
| 267 |
raise
|
| 268 |
|
| 269 |
-
# MODIFIED: Update answer_question to use global retrieval_params
|
| 270 |
def main_answer_question(question):
|
| 271 |
global query_engine, reranker, current_model, chunks_df, retrieval_params
|
| 272 |
if not question.strip():
|
|
@@ -287,7 +274,6 @@ def main_answer_question(question):
|
|
| 287 |
"<div style='color: black;'>Источники недоступны из-за ошибки</div>",
|
| 288 |
"<div style='color: black;'>Чанки недоступны из-за ошибки</div>")
|
| 289 |
|
| 290 |
-
# NEW: Function to update retrieval parameters and recreate query engine
|
| 291 |
def update_retrieval_params(vector_top_k, bm25_top_k, similarity_cutoff, hybrid_top_k, rerank_top_k):
|
| 292 |
global query_engine, vector_index, retrieval_params
|
| 293 |
|
|
@@ -430,7 +416,6 @@ def create_demo_interface(answer_question_func, switch_model_func, current_model
|
|
| 430 |
value="<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; text-align: center;'>Здесь появятся релевантные чанки...</div>",
|
| 431 |
)
|
| 432 |
|
| 433 |
-
# NEW TAB: Retrieval Parameters
|
| 434 |
with gr.Tab("⚙️ Параметры поиска"):
|
| 435 |
gr.Markdown("### Настройка параметров векторного поиска и переранжирования")
|
| 436 |
|
|
@@ -510,7 +495,6 @@ def create_demo_interface(answer_question_func, switch_model_func, current_model
|
|
| 510 |
outputs=[update_status]
|
| 511 |
)
|
| 512 |
|
| 513 |
-
# Display current parameters
|
| 514 |
gr.Markdown("### Текущие параметры:")
|
| 515 |
current_params_display = gr.Textbox(
|
| 516 |
value="Vector: 50 | BM25: 50 | Cutoff: 0.55 | Hybrid: 100 | Rerank: 20",
|
|
@@ -526,7 +510,6 @@ Similarity Cutoff: {retrieval_params['similarity_cutoff']}
|
|
| 526 |
Hybrid Top K: {retrieval_params['hybrid_top_k']}
|
| 527 |
Rerank Top K: {retrieval_params['rerank_top_k']}"""
|
| 528 |
|
| 529 |
-
# Refresh params display on tab change
|
| 530 |
demo.load(
|
| 531 |
fn=display_current_params,
|
| 532 |
outputs=[current_params_display]
|
|
@@ -537,7 +520,67 @@ Rerank Top K: {retrieval_params['rerank_top_k']}"""
|
|
| 537 |
outputs=[current_params_display]
|
| 538 |
)
|
| 539 |
|
| 540 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 541 |
switch_btn.click(
|
| 542 |
fn=switch_model_func,
|
| 543 |
inputs=[model_dropdown],
|
|
@@ -574,9 +617,6 @@ def main_switch_model(model_name):
|
|
| 574 |
|
| 575 |
return status_message
|
| 576 |
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
def main():
|
| 581 |
global query_engine, chunks_df, reranker, vector_index, current_model
|
| 582 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
|
|
|
|
| 10 |
HF_REPO_ID, HF_TOKEN, DOWNLOAD_DIR, CHUNKS_FILENAME,
|
| 11 |
JSON_FILES_DIR, TABLE_DATA_DIR, IMAGE_DATA_DIR, DEFAULT_MODEL, AVAILABLE_MODELS
|
| 12 |
)
|
| 13 |
+
from converters.converter import process_uploaded_file, convert_single_excel_to_json, convert_single_excel_to_csv
|
| 14 |
|
| 15 |
|
| 16 |
def merge_table_chunks(chunk_info):
|
|
|
|
| 40 |
|
| 41 |
return list(merged.values())
|
| 42 |
|
|
|
|
| 43 |
def create_chunks_display_html(chunk_info):
|
| 44 |
if not chunk_info:
|
| 45 |
return "<div style='padding: 20px; text-align: center; color: black;'>Нет данных о чанках</div>"
|
|
|
|
| 142 |
separator=" ",
|
| 143 |
backup_separators=["\n", ".", "!", "?"]
|
| 144 |
)
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
all_documents = []
|
| 147 |
chunks_df = None
|
| 148 |
|
|
|
|
| 149 |
if use_json_instead_csv and json_files_dir:
|
| 150 |
log_message("Используем JSON файлы вместо CSV")
|
| 151 |
from documents_prep import load_all_documents
|
| 152 |
|
|
|
|
| 153 |
all_documents = load_all_documents(
|
| 154 |
repo_id=repo_id,
|
| 155 |
hf_token=hf_token,
|
|
|
|
| 158 |
image_dir=image_data_dir if image_data_dir else ""
|
| 159 |
)
|
| 160 |
else:
|
|
|
|
| 161 |
if chunks_filename:
|
| 162 |
log_message("Загружаем данные из CSV")
|
| 163 |
|
| 164 |
if table_data_dir:
|
|
|
|
| 165 |
from documents_prep import load_table_documents
|
| 166 |
|
| 167 |
table_chunks = load_table_documents(repo_id, hf_token, table_data_dir)
|
|
|
|
| 169 |
all_documents.extend(table_chunks)
|
| 170 |
|
| 171 |
if image_data_dir:
|
|
|
|
| 172 |
from documents_prep import load_image_documents
|
| 173 |
|
| 174 |
image_documents = load_image_documents(repo_id, hf_token, image_data_dir)
|
|
|
|
| 180 |
vector_index = create_vector_index(all_documents)
|
| 181 |
query_engine = create_query_engine(vector_index)
|
| 182 |
|
|
|
|
| 183 |
chunk_info = []
|
| 184 |
for doc in all_documents:
|
| 185 |
chunk_info.append({
|
|
|
|
| 224 |
log_message(error_msg)
|
| 225 |
return None, f"❌ {error_msg}"
|
| 226 |
|
|
|
|
| 227 |
retrieval_params = {
|
| 228 |
'vector_top_k': 50,
|
| 229 |
'bm25_top_k': 50,
|
|
|
|
| 232 |
'rerank_top_k': 20
|
| 233 |
}
|
| 234 |
|
|
|
|
| 235 |
def create_query_engine(vector_index, vector_top_k=50, bm25_top_k=50,
|
| 236 |
similarity_cutoff=0.55, hybrid_top_k=100):
|
| 237 |
try:
|
| 238 |
from config import CUSTOM_PROMPT
|
| 239 |
from index_retriever import create_query_engine as create_index_query_engine
|
| 240 |
|
|
|
|
| 241 |
query_engine = create_index_query_engine(
|
| 242 |
vector_index=vector_index,
|
| 243 |
vector_top_k=vector_top_k,
|
|
|
|
| 254 |
log_message(f"Ошибка создания query engine: {str(e)}")
|
| 255 |
raise
|
| 256 |
|
|
|
|
| 257 |
def main_answer_question(question):
|
| 258 |
global query_engine, reranker, current_model, chunks_df, retrieval_params
|
| 259 |
if not question.strip():
|
|
|
|
| 274 |
"<div style='color: black;'>Источники недоступны из-за ошибки</div>",
|
| 275 |
"<div style='color: black;'>Чанки недоступны из-за ошибки</div>")
|
| 276 |
|
|
|
|
| 277 |
def update_retrieval_params(vector_top_k, bm25_top_k, similarity_cutoff, hybrid_top_k, rerank_top_k):
|
| 278 |
global query_engine, vector_index, retrieval_params
|
| 279 |
|
|
|
|
| 416 |
value="<div style='background-color: #2d3748; color: white; padding: 20px; border-radius: 10px; text-align: center;'>Здесь появятся релевантные чанки...</div>",
|
| 417 |
)
|
| 418 |
|
|
|
|
| 419 |
with gr.Tab("⚙️ Параметры поиска"):
|
| 420 |
gr.Markdown("### Настройка параметров векторного поиска и переранжирования")
|
| 421 |
|
|
|
|
| 495 |
outputs=[update_status]
|
| 496 |
)
|
| 497 |
|
|
|
|
| 498 |
gr.Markdown("### Текущие параметры:")
|
| 499 |
current_params_display = gr.Textbox(
|
| 500 |
value="Vector: 50 | BM25: 50 | Cutoff: 0.55 | Hybrid: 100 | Rerank: 20",
|
|
|
|
| 510 |
Hybrid Top K: {retrieval_params['hybrid_top_k']}
|
| 511 |
Rerank Top K: {retrieval_params['rerank_top_k']}"""
|
| 512 |
|
|
|
|
| 513 |
demo.load(
|
| 514 |
fn=display_current_params,
|
| 515 |
outputs=[current_params_display]
|
|
|
|
| 520 |
outputs=[current_params_display]
|
| 521 |
)
|
| 522 |
|
| 523 |
+
|
| 524 |
+
with gr.Tab("📤 Загрузка документов"):
|
| 525 |
+
gr.Markdown("""
|
| 526 |
+
### Загрузка новых документов в систему
|
| 527 |
+
|
| 528 |
+
Выберите тип документа и загрузите файл. Система автоматически обработает и добавит его в базу знаний.
|
| 529 |
+
""")
|
| 530 |
+
|
| 531 |
+
with gr.Row():
|
| 532 |
+
with gr.Column(scale=2):
|
| 533 |
+
file_type_radio = gr.Radio(
|
| 534 |
+
choices=["Таблица", "Изображение (метаданные)", "JSON документ"],
|
| 535 |
+
value="Таблица",
|
| 536 |
+
label="Тип документа",
|
| 537 |
+
info="Выберите тип загружаемого документа"
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
file_upload = gr.File(
|
| 541 |
+
label="Выберите файл",
|
| 542 |
+
file_types=[".xlsx", ".xls", ".csv", ".json"],
|
| 543 |
+
type="filepath"
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
upload_btn = gr.Button("Загрузить и обработать", variant="primary", size="lg")
|
| 547 |
+
|
| 548 |
+
upload_status = gr.Textbox(
|
| 549 |
+
label="Статус загрузки",
|
| 550 |
+
value="Ожидание загрузки файла...",
|
| 551 |
+
interactive=False,
|
| 552 |
+
lines=3
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
with gr.Column(scale=1):
|
| 556 |
+
gr.Markdown("""
|
| 557 |
+
### Требования к файлам:
|
| 558 |
+
|
| 559 |
+
**Таблицы (Excel → JSON):**
|
| 560 |
+
- Формат: .xlsx или .xls
|
| 561 |
+
- Обязательные колонки:
|
| 562 |
+
- Номер таблицы
|
| 563 |
+
- Обозначение документа
|
| 564 |
+
- Раздел документа
|
| 565 |
+
- Название таблицы
|
| 566 |
+
|
| 567 |
+
**Изображения (Excel → CSV):**
|
| 568 |
+
- Формат: .xlsx, .xls или .csv
|
| 569 |
+
- Метаданные изображений
|
| 570 |
+
|
| 571 |
+
**JSON документы:**
|
| 572 |
+
- Формат: .json
|
| 573 |
+
- Структурированные данные
|
| 574 |
+
|
| 575 |
+
⚠️ **Важно:** После загрузки необходимо перезапустить систему для применения изменений!
|
| 576 |
+
""")
|
| 577 |
+
|
| 578 |
+
upload_btn.click(
|
| 579 |
+
fn=process_uploaded_file,
|
| 580 |
+
inputs=[file_upload, file_type_radio],
|
| 581 |
+
outputs=[upload_status]
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
switch_btn.click(
|
| 585 |
fn=switch_model_func,
|
| 586 |
inputs=[model_dropdown],
|
|
|
|
| 617 |
|
| 618 |
return status_message
|
| 619 |
|
|
|
|
|
|
|
|
|
|
| 620 |
def main():
|
| 621 |
global query_engine, chunks_df, reranker, vector_index, current_model
|
| 622 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
|