Spaces:
Sleeping
Sleeping
Update converters/converter.py
Browse files- converters/converter.py +125 -116
converters/converter.py
CHANGED
|
@@ -1,116 +1,125 @@
|
|
| 1 |
-
from config import *
|
| 2 |
-
from utils import log_message
|
| 3 |
-
import json
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import os
|
| 6 |
-
|
| 7 |
-
def process_uploaded_file(file, file_type):
|
| 8 |
-
"""Обработка загруженного файла и добавление в систему"""
|
| 9 |
-
try:
|
| 10 |
-
if file is None:
|
| 11 |
-
return "❌ Файл не выбран"
|
| 12 |
-
|
| 13 |
-
from huggingface_hub import HfApi
|
| 14 |
-
import tempfile
|
| 15 |
-
import shutil
|
| 16 |
-
|
| 17 |
-
# Создаем временную директорию
|
| 18 |
-
with tempfile.TemporaryDirectory() as temp_dir:
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
"
|
| 68 |
-
|
| 69 |
-
"
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
"
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from config import *
|
| 2 |
+
from utils import log_message
|
| 3 |
+
import json
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
def process_uploaded_file(file, file_type):
|
| 8 |
+
"""Обработка загруженного файла и добавление в систему"""
|
| 9 |
+
try:
|
| 10 |
+
if file is None:
|
| 11 |
+
return "❌ Файл не выбран"
|
| 12 |
+
|
| 13 |
+
from huggingface_hub import HfApi
|
| 14 |
+
import tempfile
|
| 15 |
+
import shutil
|
| 16 |
+
|
| 17 |
+
# Создаем временную директорию
|
| 18 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 19 |
+
# Получаем путь к файлу (file может быть путем или объектом)
|
| 20 |
+
source_path = file if isinstance(file, str) else file.name
|
| 21 |
+
filename = os.path.basename(source_path)
|
| 22 |
+
|
| 23 |
+
# Создаем путь в временной директории
|
| 24 |
+
file_path = os.path.join(temp_dir, filename)
|
| 25 |
+
|
| 26 |
+
# Копируем только если источник и назначение разные
|
| 27 |
+
if os.path.abspath(source_path) != os.path.abspath(file_path):
|
| 28 |
+
shutil.copy(source_path, file_path)
|
| 29 |
+
else:
|
| 30 |
+
file_path = source_path
|
| 31 |
+
|
| 32 |
+
# Определяем целевую директорию на HuggingFace
|
| 33 |
+
if file_type == "Таблица":
|
| 34 |
+
target_dir = TABLE_DATA_DIR
|
| 35 |
+
# Конвертируем Excel в JSON
|
| 36 |
+
if filename.endswith(('.xlsx', '.xls')):
|
| 37 |
+
json_path = convert_single_excel_to_json(file_path, temp_dir)
|
| 38 |
+
upload_file = json_path
|
| 39 |
+
else:
|
| 40 |
+
upload_file = file_path
|
| 41 |
+
elif file_type == "Изображение (метаданные)":
|
| 42 |
+
target_dir = IMAGE_DATA_DIR
|
| 43 |
+
# Конвертируем Excel в CSV
|
| 44 |
+
if filename.endswith(('.xlsx', '.xls')):
|
| 45 |
+
csv_path = convert_single_excel_to_csv(file_path, temp_dir)
|
| 46 |
+
upload_file = csv_path
|
| 47 |
+
else:
|
| 48 |
+
upload_file = file_path
|
| 49 |
+
else: # JSON документ
|
| 50 |
+
target_dir = JSON_FILES_DIR
|
| 51 |
+
upload_file = file_path
|
| 52 |
+
|
| 53 |
+
# Загружаем на HuggingFace
|
| 54 |
+
api = HfApi()
|
| 55 |
+
api.upload_file(
|
| 56 |
+
path_or_fileobj=upload_file,
|
| 57 |
+
path_in_repo=f"{target_dir}/{os.path.basename(upload_file)}",
|
| 58 |
+
repo_id=HF_REPO_ID,
|
| 59 |
+
token=HF_TOKEN,
|
| 60 |
+
repo_type="dataset"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
log_message(f"Файл {filename} успешно загружен в {target_dir}")
|
| 64 |
+
return f"✅ Файл успешно загружен и обработан: {os.path.basename(upload_file)}\n⚠️ Перезапустите систему для применения изменений"
|
| 65 |
+
|
| 66 |
+
except Exception as e:
|
| 67 |
+
error_msg = f"Ошибка обработки файла: {str(e)}"
|
| 68 |
+
log_message(error_msg)
|
| 69 |
+
return f"❌ {error_msg}"
|
| 70 |
+
|
| 71 |
+
def convert_single_excel_to_json(excel_path, output_dir):
|
| 72 |
+
"""Конвертация одного Excel файла в JSON для таблиц"""
|
| 73 |
+
df_dict = pd.read_excel(excel_path, sheet_name=None)
|
| 74 |
+
|
| 75 |
+
result = {
|
| 76 |
+
"document": os.path.basename(excel_path),
|
| 77 |
+
"total_sheets": len(df_dict),
|
| 78 |
+
"sheets": []
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
for sheet_name, df in df_dict.items():
|
| 82 |
+
if df.empty or "Номер таблицы" not in df.columns:
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
df = df.dropna(how='all').fillna("")
|
| 86 |
+
grouped = df.groupby("Номер таблицы")
|
| 87 |
+
|
| 88 |
+
for table_number, group in grouped:
|
| 89 |
+
group = group.reset_index(drop=True)
|
| 90 |
+
|
| 91 |
+
sheet_data = {
|
| 92 |
+
"sheet_name": sheet_name,
|
| 93 |
+
"document_id": str(group.iloc[0].get("Обозначение документа", "")),
|
| 94 |
+
"section": str(group.iloc[0].get("Раздел документа", "")),
|
| 95 |
+
"table_number": str(table_number),
|
| 96 |
+
"table_title": str(group.iloc[0].get("Название таблицы", "")),
|
| 97 |
+
"table_description": str(group.iloc[0].get("Примечание", "")),
|
| 98 |
+
"headers": [col for col in df.columns if col not in
|
| 99 |
+
["Обозначение документа", "Раздел документа", "Номер таблицы",
|
| 100 |
+
"Название таблицы", "Приме��ание"]],
|
| 101 |
+
"data": []
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
for _, row in group.iterrows():
|
| 105 |
+
row_dict = {col: str(row[col]) if pd.notna(row[col]) else ""
|
| 106 |
+
for col in sheet_data["headers"]}
|
| 107 |
+
sheet_data["data"].append(row_dict)
|
| 108 |
+
|
| 109 |
+
result["sheets"].append(sheet_data)
|
| 110 |
+
|
| 111 |
+
json_filename = os.path.basename(excel_path).replace('.xlsx', '.json').replace('.xls', '.json')
|
| 112 |
+
json_path = os.path.join(output_dir, json_filename)
|
| 113 |
+
|
| 114 |
+
with open(json_path, 'w', encoding='utf-8') as f:
|
| 115 |
+
json.dump(result, f, ensure_ascii=False, indent=2)
|
| 116 |
+
|
| 117 |
+
return json_path
|
| 118 |
+
|
| 119 |
+
def convert_single_excel_to_csv(excel_path, output_dir):
|
| 120 |
+
"""Конвертация одного Excel файла в CSV для изображений"""
|
| 121 |
+
df = pd.read_excel(excel_path)
|
| 122 |
+
csv_filename = os.path.basename(excel_path).replace('.xlsx', '.csv').replace('.xls', '.csv')
|
| 123 |
+
csv_path = os.path.join(output_dir, csv_filename)
|
| 124 |
+
df.to_csv(csv_path, index=False, encoding='utf-8')
|
| 125 |
+
return csv_path
|