MrSimple01 commited on
Commit
ce7b472
·
verified ·
1 Parent(s): 94dce77

Upload converter.py

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