MrSimple01 commited on
Commit
48c1e22
·
verified ·
1 Parent(s): eae2fa3

Update converters/converter.py

Browse files
Files changed (1) hide show
  1. 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
- 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
 
 
 
 
 
 
 
 
 
 
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