Spaces:
Sleeping
Sleeping
Commit
·
da3779b
1
Parent(s):
c825d58
Fixed HF_REPO_ID + Added force_download=True + Enhanced status messages
Browse files- app.py +12 -2
- config.py +1 -2
- converters/converter.py +31 -26
- documents_prep.py +2 -1
app.py
CHANGED
|
@@ -18,6 +18,17 @@ def restart_system():
|
|
| 18 |
|
| 19 |
try:
|
| 20 |
log_message("Начало перезапуска системы...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
query_engine, chunks_df, reranker, vector_index, chunk_info = initialize_system(
|
| 23 |
repo_id=HF_REPO_ID,
|
|
@@ -40,7 +51,6 @@ def restart_system():
|
|
| 40 |
log_message(error_msg)
|
| 41 |
return f"❌ {error_msg}"
|
| 42 |
|
| 43 |
-
|
| 44 |
def initialize_system(repo_id, hf_token, download_dir, chunks_filename=None,
|
| 45 |
json_files_dir=None, table_data_dir=None, image_data_dir=None,
|
| 46 |
use_json_instead_csv=False):
|
|
@@ -451,7 +461,7 @@ Rerank Top K: {retrieval_params['rerank_top_k']}"""
|
|
| 451 |
with gr.Row():
|
| 452 |
with gr.Column(scale=2):
|
| 453 |
file_type_radio = gr.Radio(
|
| 454 |
-
choices=["Таблица", "Изображение
|
| 455 |
value="Таблица",
|
| 456 |
label="Тип документа",
|
| 457 |
info="Выберите тип загружаемого документа"
|
|
|
|
| 18 |
|
| 19 |
try:
|
| 20 |
log_message("Начало перезапуска системы...")
|
| 21 |
+
log_message("Очистка кэша HuggingFace...")
|
| 22 |
+
|
| 23 |
+
# Clear HuggingFace cache to force fresh download
|
| 24 |
+
import shutil
|
| 25 |
+
cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
|
| 26 |
+
if os.path.exists(cache_dir):
|
| 27 |
+
try:
|
| 28 |
+
shutil.rmtree(cache_dir)
|
| 29 |
+
log_message("✓ Кэш очищен")
|
| 30 |
+
except:
|
| 31 |
+
log_message("⚠ Не удалось очистить кэш полностью")
|
| 32 |
|
| 33 |
query_engine, chunks_df, reranker, vector_index, chunk_info = initialize_system(
|
| 34 |
repo_id=HF_REPO_ID,
|
|
|
|
| 51 |
log_message(error_msg)
|
| 52 |
return f"❌ {error_msg}"
|
| 53 |
|
|
|
|
| 54 |
def initialize_system(repo_id, hf_token, download_dir, chunks_filename=None,
|
| 55 |
json_files_dir=None, table_data_dir=None, image_data_dir=None,
|
| 56 |
use_json_instead_csv=False):
|
|
|
|
| 461 |
with gr.Row():
|
| 462 |
with gr.Column(scale=2):
|
| 463 |
file_type_radio = gr.Radio(
|
| 464 |
+
choices=["Таблица", "Изображение", "Текстовый JSON"],
|
| 465 |
value="Таблица",
|
| 466 |
label="Тип документа",
|
| 467 |
info="Выберите тип загружаемого документа"
|
config.py
CHANGED
|
@@ -5,7 +5,6 @@ SIMILARITY_THRESHOLD = 0.7
|
|
| 5 |
RAG_FILES_DIR = "rag_files"
|
| 6 |
PROCESSED_DATA_FILE = "processed_chunks.csv"
|
| 7 |
|
| 8 |
-
REPO_ID = "RAG-AIEXP/ragfiles"
|
| 9 |
faiss_index_filename = "cleaned_faiss_index.index"
|
| 10 |
CHUNKS_FILENAME = "processed_chunks.csv"
|
| 11 |
TABLE_DATA_DIR = "Табличные данные_JSON"
|
|
@@ -15,7 +14,7 @@ JSON_FILES_DIR ="JSON"
|
|
| 15 |
|
| 16 |
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
|
| 17 |
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
|
| 18 |
-
HF_REPO_ID = "
|
| 19 |
HF_TOKEN = os.getenv('HF_TOKEN')
|
| 20 |
|
| 21 |
AVAILABLE_MODELS = {
|
|
|
|
| 5 |
RAG_FILES_DIR = "rag_files"
|
| 6 |
PROCESSED_DATA_FILE = "processed_chunks.csv"
|
| 7 |
|
|
|
|
| 8 |
faiss_index_filename = "cleaned_faiss_index.index"
|
| 9 |
CHUNKS_FILENAME = "processed_chunks.csv"
|
| 10 |
TABLE_DATA_DIR = "Табличные данные_JSON"
|
|
|
|
| 14 |
|
| 15 |
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
|
| 16 |
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
|
| 17 |
+
HF_REPO_ID = "RAG-AIEXP/ragfiles"
|
| 18 |
HF_TOKEN = os.getenv('HF_TOKEN')
|
| 19 |
|
| 20 |
AVAILABLE_MODELS = {
|
converters/converter.py
CHANGED
|
@@ -27,7 +27,6 @@ def process_uploaded_file(file, file_type):
|
|
| 27 |
else:
|
| 28 |
file_path = source_path
|
| 29 |
|
| 30 |
-
# Get original file size
|
| 31 |
original_size_bytes = os.path.getsize(file_path)
|
| 32 |
original_size_mb = original_size_bytes / (1024 * 1024)
|
| 33 |
|
|
@@ -35,13 +34,32 @@ def process_uploaded_file(file, file_type):
|
|
| 35 |
status_info.append(f"📁 Исходный файл: {filename}")
|
| 36 |
status_info.append(f"📦 Размер файла: {original_size_mb:.2f} МБ ({original_size_bytes:,} байт)")
|
| 37 |
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
target_dir = TABLE_DATA_DIR
|
| 40 |
if filename.endswith(('.xlsx', '.xls')):
|
| 41 |
json_path = convert_single_excel_to_json(file_path, temp_dir)
|
| 42 |
upload_file = json_path
|
| 43 |
|
| 44 |
-
# Get processed file size
|
| 45 |
processed_size_bytes = os.path.getsize(json_path)
|
| 46 |
processed_size_mb = processed_size_bytes / (1024 * 1024)
|
| 47 |
|
|
@@ -55,9 +73,11 @@ def process_uploaded_file(file, file_type):
|
|
| 55 |
status_info.append(f"📝 Всего строк данных: {total_rows:,}")
|
| 56 |
status_info.append(f"💾 Размер после обработки: {processed_size_mb:.2f} МБ")
|
| 57 |
status_info.append(f"📤 Загружен как: {os.path.basename(json_path)}")
|
|
|
|
| 58 |
else:
|
| 59 |
upload_file = file_path
|
| 60 |
status_info.append(f"📤 Загружен как: {filename}")
|
|
|
|
| 61 |
|
| 62 |
elif file_type == "Изображение (метаданные)":
|
| 63 |
target_dir = IMAGE_DATA_DIR
|
|
@@ -65,7 +85,6 @@ def process_uploaded_file(file, file_type):
|
|
| 65 |
csv_path = convert_single_excel_to_csv(file_path, temp_dir)
|
| 66 |
upload_file = csv_path
|
| 67 |
|
| 68 |
-
# Get processed file size
|
| 69 |
processed_size_bytes = os.path.getsize(csv_path)
|
| 70 |
processed_size_mb = processed_size_bytes / (1024 * 1024)
|
| 71 |
|
|
@@ -74,6 +93,7 @@ def process_uploaded_file(file, file_type):
|
|
| 74 |
status_info.append(f"📋 Колонок метаданных: {len(df.columns)}")
|
| 75 |
status_info.append(f"💾 Размер после обработки: {processed_size_mb:.2f} МБ")
|
| 76 |
status_info.append(f"📤 Загружен как: {os.path.basename(csv_path)}")
|
|
|
|
| 77 |
else:
|
| 78 |
upload_file = file_path
|
| 79 |
try:
|
|
@@ -83,33 +103,17 @@ def process_uploaded_file(file, file_type):
|
|
| 83 |
except:
|
| 84 |
pass
|
| 85 |
status_info.append(f"📤 Загружен как: {filename}")
|
| 86 |
-
|
| 87 |
-
else: # JSON документ
|
| 88 |
-
target_dir = JSON_FILES_DIR
|
| 89 |
-
upload_file = file_path
|
| 90 |
-
|
| 91 |
-
try:
|
| 92 |
-
with open(upload_file, 'r', encoding='utf-8') as f:
|
| 93 |
-
json_data = json.load(f)
|
| 94 |
-
|
| 95 |
-
if isinstance(json_data, list):
|
| 96 |
-
status_info.append(f"📝 Документов в JSON: {len(json_data):,}")
|
| 97 |
-
elif isinstance(json_data, dict):
|
| 98 |
-
status_info.append(f"📝 JSON объект (словарь)")
|
| 99 |
-
# Count keys if it's structured data
|
| 100 |
-
if 'sheets' in json_data:
|
| 101 |
-
status_info.append(f"📊 Таблиц в документе: {len(json_data.get('sheets', []))}")
|
| 102 |
-
status_info.append(f"🔑 Ключей верхнего уровня: {len(json_data.keys())}")
|
| 103 |
-
except:
|
| 104 |
-
pass
|
| 105 |
-
status_info.append(f"📤 Загружен как: {filename}")
|
| 106 |
|
| 107 |
# Загружаем на HuggingFace
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
| 109 |
api = HfApi()
|
| 110 |
api.upload_file(
|
| 111 |
path_or_fileobj=upload_file,
|
| 112 |
-
path_in_repo=
|
| 113 |
repo_id=HF_REPO_ID,
|
| 114 |
token=HF_TOKEN,
|
| 115 |
repo_type="dataset"
|
|
@@ -119,6 +123,7 @@ def process_uploaded_file(file, file_type):
|
|
| 119 |
|
| 120 |
result_message = f"✅ Файл успешно загружен и обработан\n\n"
|
| 121 |
result_message += "\n".join(status_info)
|
|
|
|
| 122 |
result_message += "\n\n⚠️ Нажмите кнопку 'Перезапустить систему' для применения изменений"
|
| 123 |
|
| 124 |
return result_message
|
|
|
|
| 27 |
else:
|
| 28 |
file_path = source_path
|
| 29 |
|
|
|
|
| 30 |
original_size_bytes = os.path.getsize(file_path)
|
| 31 |
original_size_mb = original_size_bytes / (1024 * 1024)
|
| 32 |
|
|
|
|
| 34 |
status_info.append(f"📁 Исходный файл: {filename}")
|
| 35 |
status_info.append(f"📦 Размер файла: {original_size_mb:.2f} МБ ({original_size_bytes:,} байт)")
|
| 36 |
|
| 37 |
+
# ADDED: Text document handling
|
| 38 |
+
if file_type == "JSON документ":
|
| 39 |
+
target_dir = JSON_FILES_DIR
|
| 40 |
+
upload_file = file_path
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
with open(upload_file, 'r', encoding='utf-8') as f:
|
| 44 |
+
json_data = json.load(f)
|
| 45 |
+
|
| 46 |
+
# Count sections
|
| 47 |
+
section_count = len(json_data.get('sections', []))
|
| 48 |
+
status_info.append(f"📝 Разделов в документе: {section_count}")
|
| 49 |
+
status_info.append(f"📄 ID документа: {json_data.get('document_metadata', {}).get('document_id', 'N/A')}")
|
| 50 |
+
|
| 51 |
+
except Exception as e:
|
| 52 |
+
return f"❌ Ошибка чтения JSON: {str(e)}"
|
| 53 |
+
|
| 54 |
+
status_info.append(f"📤 Загружен как: {filename}")
|
| 55 |
+
status_info.append(f"📂 Целевая директория: {target_dir}")
|
| 56 |
+
|
| 57 |
+
elif file_type == "Таблица":
|
| 58 |
target_dir = TABLE_DATA_DIR
|
| 59 |
if filename.endswith(('.xlsx', '.xls')):
|
| 60 |
json_path = convert_single_excel_to_json(file_path, temp_dir)
|
| 61 |
upload_file = json_path
|
| 62 |
|
|
|
|
| 63 |
processed_size_bytes = os.path.getsize(json_path)
|
| 64 |
processed_size_mb = processed_size_bytes / (1024 * 1024)
|
| 65 |
|
|
|
|
| 73 |
status_info.append(f"📝 Всего строк данных: {total_rows:,}")
|
| 74 |
status_info.append(f"💾 Размер после обработки: {processed_size_mb:.2f} МБ")
|
| 75 |
status_info.append(f"📤 Загружен как: {os.path.basename(json_path)}")
|
| 76 |
+
status_info.append(f"📂 Целевая директория: {target_dir}")
|
| 77 |
else:
|
| 78 |
upload_file = file_path
|
| 79 |
status_info.append(f"📤 Загружен как: {filename}")
|
| 80 |
+
status_info.append(f"📂 Целевая директория: {target_dir}")
|
| 81 |
|
| 82 |
elif file_type == "Изображение (метаданные)":
|
| 83 |
target_dir = IMAGE_DATA_DIR
|
|
|
|
| 85 |
csv_path = convert_single_excel_to_csv(file_path, temp_dir)
|
| 86 |
upload_file = csv_path
|
| 87 |
|
|
|
|
| 88 |
processed_size_bytes = os.path.getsize(csv_path)
|
| 89 |
processed_size_mb = processed_size_bytes / (1024 * 1024)
|
| 90 |
|
|
|
|
| 93 |
status_info.append(f"📋 Колонок метаданных: {len(df.columns)}")
|
| 94 |
status_info.append(f"💾 Размер после обработки: {processed_size_mb:.2f} МБ")
|
| 95 |
status_info.append(f"📤 Загружен как: {os.path.basename(csv_path)}")
|
| 96 |
+
status_info.append(f"📂 Целевая директория: {target_dir}")
|
| 97 |
else:
|
| 98 |
upload_file = file_path
|
| 99 |
try:
|
|
|
|
| 103 |
except:
|
| 104 |
pass
|
| 105 |
status_info.append(f"📤 Загружен как: {filename}")
|
| 106 |
+
status_info.append(f"📂 Целевая директория: {target_dir}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
# Загружаем на HuggingFace
|
| 109 |
+
upload_path = f"{target_dir}/{os.path.basename(upload_file)}"
|
| 110 |
+
log_message(f"Загрузка на HuggingFace: {upload_path}")
|
| 111 |
+
status_info.append(f"⬆️ Загрузка в репозиторий...")
|
| 112 |
+
|
| 113 |
api = HfApi()
|
| 114 |
api.upload_file(
|
| 115 |
path_or_fileobj=upload_file,
|
| 116 |
+
path_in_repo=upload_path,
|
| 117 |
repo_id=HF_REPO_ID,
|
| 118 |
token=HF_TOKEN,
|
| 119 |
repo_type="dataset"
|
|
|
|
| 123 |
|
| 124 |
result_message = f"✅ Файл успешно загружен и обработан\n\n"
|
| 125 |
result_message += "\n".join(status_info)
|
| 126 |
+
result_message += f"\n\n✅ Файл добавлен в: {upload_path}"
|
| 127 |
result_message += "\n\n⚠️ Нажмите кнопку 'Перезапустить систему' для применения изменений"
|
| 128 |
|
| 129 |
return result_message
|
documents_prep.py
CHANGED
|
@@ -382,7 +382,8 @@ def load_json_documents(repo_id, hf_token, json_dir):
|
|
| 382 |
repo_id=repo_id,
|
| 383 |
filename=zip_path,
|
| 384 |
repo_type="dataset",
|
| 385 |
-
token=hf_token
|
|
|
|
| 386 |
)
|
| 387 |
|
| 388 |
with zipfile.ZipFile(local_zip, 'r') as zf:
|
|
|
|
| 382 |
repo_id=repo_id,
|
| 383 |
filename=zip_path,
|
| 384 |
repo_type="dataset",
|
| 385 |
+
token=hf_token,
|
| 386 |
+
force_download=True
|
| 387 |
)
|
| 388 |
|
| 389 |
with zipfile.ZipFile(local_zip, 'r') as zf:
|