Rulga commited on
Commit
3f6bcbe
·
1 Parent(s): 954b9d0

Implement DatasetManager for managing Hugging Face dataset structure and chat history

Browse files
Files changed (1) hide show
  1. src/knowledge_base/dataset.py +135 -0
src/knowledge_base/dataset.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from datetime import datetime
4
+ from huggingface_hub import HfApi
5
+ from config.settings import VECTOR_STORE_PATH
6
+
7
+ class DatasetManager:
8
+ def __init__(self, dataset_name="Rulga/status-law-knowledge-base"):
9
+ self.api = HfApi()
10
+ self.dataset_name = dataset_name
11
+
12
+ def init_dataset_structure(self):
13
+ """Инициализация структуры датасета на Hugging Face"""
14
+ try:
15
+ # Создаем пустые .gitkeep файлы для поддержания структуры
16
+ self.api.upload_file(
17
+ path_or_fileobj=b"",
18
+ path_in_repo="vector_store/.gitkeep",
19
+ repo_id=self.dataset_name,
20
+ repo_type="dataset"
21
+ )
22
+
23
+ self.api.upload_file(
24
+ path_or_fileobj=b"",
25
+ path_in_repo="chat_history/.gitkeep",
26
+ repo_id=self.dataset_name,
27
+ repo_type="dataset"
28
+ )
29
+
30
+ return True, "Структура датасета успешно создана"
31
+ except Exception as e:
32
+ return False, f"Ошибка при создании структуры датасета: {str(e)}"
33
+
34
+ def upload_vector_store(self):
35
+ """Загрузка векторного хранилища в датасет"""
36
+ try:
37
+ # Проверяем наличие файлов
38
+ index_path = os.path.join(VECTOR_STORE_PATH, "index.faiss")
39
+ config_path = os.path.join(VECTOR_STORE_PATH, "index.pkl")
40
+
41
+ if not (os.path.exists(index_path) and os.path.exists(config_path)):
42
+ return False, "Файлы векторного хранилища не найдены"
43
+
44
+ # Загружаем файлы
45
+ self.api.upload_file(
46
+ path_or_fileobj=index_path,
47
+ path_in_repo="vector_store/index.faiss",
48
+ repo_id=self.dataset_name,
49
+ repo_type="dataset"
50
+ )
51
+
52
+ self.api.upload_file(
53
+ path_or_fileobj=config_path,
54
+ path_in_repo="vector_store/index.pkl",
55
+ repo_id=self.dataset_name,
56
+ repo_type="dataset"
57
+ )
58
+
59
+ return True, "Векторное хранилище успешно загружено"
60
+ except Exception as e:
61
+ return False, f"Ошибка при загрузке векторного хранилища: {str(e)}"
62
+
63
+ def download_vector_store(self):
64
+ """Загрузка векторного хранилища из датасета"""
65
+ try:
66
+ # Создаем директорию если её нет
67
+ os.makedirs(VECTOR_STORE_PATH, exist_ok=True)
68
+
69
+ # Загружаем файлы
70
+ self.api.hf_hub_download(
71
+ repo_id=self.dataset_name,
72
+ filename="vector_store/index.faiss",
73
+ repo_type="dataset",
74
+ local_dir=VECTOR_STORE_PATH
75
+ )
76
+
77
+ self.api.hf_hub_download(
78
+ repo_id=self.dataset_name,
79
+ filename="vector_store/index.pkl",
80
+ repo_type="dataset",
81
+ local_dir=VECTOR_STORE_PATH
82
+ )
83
+
84
+ return True, "Векторное хранилище успешно загружено"
85
+ except Exception as e:
86
+ return False, f"Ошибка при загрузке векторного хранилища: {str(e)}"
87
+
88
+ def save_chat_history(self, conversation_id, messages):
89
+ """Сохранение истории чата в датасет"""
90
+ try:
91
+ # Формируем имя файла с временной меткой
92
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
93
+ filename = f"chat_history/{conversation_id}_{timestamp}.json"
94
+
95
+ # Создаем временный файл
96
+ chat_data = {
97
+ "conversation_id": conversation_id,
98
+ "timestamp": timestamp,
99
+ "messages": messages
100
+ }
101
+
102
+ temp_file = f"temp_{conversation_id}.json"
103
+ with open(temp_file, "w", encoding="utf-8") as f:
104
+ json.dump(chat_data, f, ensure_ascii=False, indent=2)
105
+
106
+ # Загружаем файл в датасет
107
+ self.api.upload_file(
108
+ path_or_fileobj=temp_file,
109
+ path_in_repo=filename,
110
+ repo_id=self.dataset_name,
111
+ repo_type="dataset"
112
+ )
113
+
114
+ # Удаляем временный файл
115
+ os.remove(temp_file)
116
+
117
+ return True, "История чата сохранена"
118
+ except Exception as e:
119
+ return False, f"Ошибка при сохранении истории чата: {str(e)}"
120
+
121
+ def test_dataset_connection():
122
+ """Тестовая функция для проверки подключения к датасету"""
123
+ try:
124
+ manager = DatasetManager()
125
+ success, message = manager.init_dataset_structure()
126
+ print(f"Тест инициализации: {message}")
127
+
128
+ return True, "Подключение к датасету работает"
129
+ except Exception as e:
130
+ return False, f"Ошибка подключения к датасету: {str(e)}"
131
+
132
+ if __name__ == "__main__":
133
+ # Тестируем подключение
134
+ success, message = test_dataset_connection()
135
+ print(message)