datbkpro commited on
Commit
be049b0
·
verified ·
1 Parent(s): 6469f7e

Update ui/tabs.py

Browse files
Files changed (1) hide show
  1. ui/tabs.py +137 -141
ui/tabs.py CHANGED
@@ -37,154 +37,150 @@ def create_all_tabs(audio_service: AudioService, chat_service: ChatService,
37
  create_language_info_tab(rag_system.multilingual_manager)
38
  def create_rag_tab(rag_system: EnhancedRAGSystem, wikipedia_processor: WikipediaProcessor):
39
  """Tạo tab RAG với debug chi tiết"""
40
- gr.Markdown("## 📚 Upload Dữ Liệu Wikipedia")
41
 
42
- with gr.Row():
43
- with gr.Column(scale=1):
44
- gr.Markdown("### 📤 Upload Dữ Liệu")
45
- file_upload = gr.File(
46
- label="Tải lên file (TXT, CSV, JSON)",
47
- file_types=['.txt', '.csv', '.json'],
48
- file_count="single",
49
- type="filepath"
50
- )
51
- upload_btn = gr.Button("📤 Upload Data", variant="primary")
52
- upload_status = gr.Textbox(
53
- label="Trạng thái Upload",
54
- interactive=False,
55
- lines=5
56
- )
57
-
58
- gr.Markdown("### 📊 Thống kê Database")
59
- stats_btn = gr.Button("📊 Database Stats", variant="secondary")
60
- stats_display = gr.Textbox(
61
- label="Thống kê",
62
- interactive=False,
63
- lines=6
64
- )
65
-
66
- with gr.Column(scale=2):
67
- gr.Markdown("### 🔍 Tìm kiếm & Kiểm tra")
68
- search_query = gr.Textbox(
69
- label="Tìm kiếm trong database",
70
- placeholder="Nhập từ khóa để kiểm tra dữ liệu..."
71
- )
72
- search_btn = gr.Button("🔍 Tìm kiếm", variant="secondary")
73
- rag_results = gr.JSON(
74
- label="Kết quả tìm kiếm",
75
- show_label=True
76
- )
77
 
78
- def upload_wikipedia_file(file):
79
- """Xử upload file với debug đầy đủ"""
80
- if file is None:
81
- return "❌ Vui lòng chọn file để upload"
82
 
83
- try:
84
- print(f"🔄 Bắt đầu upload file: {file.name}")
85
-
86
- # Kiểm tra file tồn tại
87
- if not os.path.exists(file.name):
88
- return f"❌ File không tồn tại: {file.name}"
89
-
90
- # Xử lý file
91
- documents = wikipedia_processor.process_uploaded_file(file.name)
92
-
93
- if not documents:
94
- return "❌ Không thể trích xuất dữ liệu từ file. File có thể trống hoặc định dạng không đúng."
95
-
96
- print(f"✅ Đã xử lý {len(documents)} documents")
97
-
98
- # Tạo metadata
99
- metadatas = []
100
- for i, doc in enumerate(documents):
101
- metadata = {
102
- "source": "uploaded_file",
103
- "type": "knowledge",
104
- "file_name": os.path.basename(file.name),
105
- "language": "vi",
106
- "doc_id": i,
107
- "length": len(doc)
108
- }
109
- metadatas.append(metadata)
110
-
111
- # Thêm vào RAG system
112
- old_stats = rag_system.get_collection_stats()
113
- old_count = old_stats['total_documents']
114
-
115
- rag_system.add_documents(documents, metadatas)
116
-
117
- # Lấy thống kê mới
118
- new_stats = rag_system.get_collection_stats()
119
- new_count = new_stats['total_documents']
120
-
121
- success_msg = f"""
122
- ✅ UPLOAD THÀNH CÔNG!
123
-
124
- 📁 File: {os.path.basename(file.name)}
125
- 📄 Documents xử lý: {len(documents)}
126
- 📊 Documents thêm vào: {new_count - old_count}
127
- 🏷️ Tổng documents: {new_count}
128
- 🔤 Embeddings: {new_stats['embedding_count']}
129
- 🌐 Ngôn ngữ: {new_stats['language_distribution']}
130
-
131
- 💡 Bạn có thể tìm kiếm ngay để kiểm tra dữ liệu!
132
- """
133
- return success_msg
134
-
135
- except Exception as e:
136
- error_msg = f"❌ LỖI UPLOAD: {str(e)}"
137
- print(f"UPLOAD ERROR: {traceback.format_exc()}")
138
- return error_msg
139
-
140
- def get_rag_stats():
141
- """Lấy thống kê chi tiết"""
142
- try:
143
- stats = rag_system.get_collection_stats()
144
- return f"""
145
- 📊 THỐNG KÊ RAG DATABASE:
146
-
147
- • 📄 Tổng documents: {stats['total_documents']}
148
- • 🔤 Số embeddings: {stats['embedding_count']}
149
- • 📐 Dimension: {stats['embedding_dimension']}
150
- • 🌐 Phân bố ngôn ngữ: {stats['language_distribution']}
151
- • ✅ Trạng thái: {stats['status']}
152
- • 🏷️ Tên: {stats['name']}
153
-
154
- 💡 Embeddings: {'Có' if stats['has_embeddings'] else 'Không'}
155
- """
156
- except Exception as e:
157
- return f"❌ Lỗi lấy thống kê: {str(e)}"
158
-
159
- def search_rag_database(query):
160
- """Tìm kiếm để kiểm tra dữ liệu"""
161
- if not query.strip():
162
- return [{"message": "Nhập từ khóa để tìm kiếm"}]
163
 
164
- try:
165
- results = rag_system.semantic_search(query, top_k=3)
166
-
167
- if not results:
168
- return [{"message": "Không tìm thấy kết quả nào", "query": query}]
169
-
170
- formatted_results = []
171
- for i, result in enumerate(results):
172
- formatted_results.append({
173
- 'id': result.id,
174
- 'text': result.text[:150] + "..." if len(result.text) > 150 else result.text,
175
- 'similarity': round(result.similarity, 3),
176
- 'metadata': result.metadata
177
- })
178
 
179
- return formatted_results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
- except Exception as e:
182
- return [{"error": f"Lỗi tìm kiếm: {str(e)}"}]
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
- # Event handlers
185
- upload_btn.click(upload_wikipedia_file, inputs=[file_upload], outputs=[upload_status])
186
- stats_btn.click(get_rag_stats, inputs=[], outputs=[stats_display])
187
- search_btn.click(search_rag_database, inputs=[search_query], outputs=[rag_results])
188
  def create_audio_tab(audio_service: AudioService):
189
  gr.Markdown("## Nói chuyện với AI (Đa ngôn ngữ)")
190
  audio_input, transcription_output, response_output, tts_audio_output, process_button = create_audio_components()
 
37
  create_language_info_tab(rag_system.multilingual_manager)
38
  def create_rag_tab(rag_system: EnhancedRAGSystem, wikipedia_processor: WikipediaProcessor):
39
  """Tạo tab RAG với debug chi tiết"""
 
40
 
41
+ # Initialize systems if not provided
42
+ if rag_system is None:
43
+ rag_system = EnhancedRAGSystem()
44
+ if wikipedia_processor is None:
45
+ wikipedia_processor = WikipediaProcessor()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ with gr.Blocks() as rag_tab:
48
+ gr.Markdown("## 📚 Upload Dữ Liệu Wikipedia")
 
 
49
 
50
+ with gr.Row():
51
+ with gr.Column(scale=1):
52
+ gr.Markdown("### 📤 Upload Dữ Liệu")
53
+ file_upload = gr.File(
54
+ label="Tải lên file (TXT, CSV, JSON)",
55
+ file_types=['.txt', '.csv', '.json'],
56
+ file_count="single"
57
+ )
58
+ upload_btn = gr.Button("📤 Upload Data", variant="primary")
59
+ upload_status = gr.Textbox(
60
+ label="Trạng thái Upload",
61
+ interactive=False,
62
+ lines=5
63
+ )
64
+
65
+ gr.Markdown("### 📊 Thống kê Database")
66
+ stats_btn = gr.Button("📊 Database Stats", variant="secondary")
67
+ stats_display = gr.Textbox(
68
+ label="Thống kê",
69
+ interactive=False,
70
+ lines=6
71
+ )
72
+
73
+ with gr.Column(scale=2):
74
+ gr.Markdown("### 🔍 Tìm kiếm & Kiểm tra")
75
+ search_query = gr.Textbox(
76
+ label="Tìm kiếm trong database",
77
+ placeholder="Nhập từ khóa để kiểm tra dữ liệu..."
78
+ )
79
+ search_btn = gr.Button("🔍 Tìm kiếm", variant="secondary")
80
+ rag_results = gr.JSON(
81
+ label="Kết quả tìm kiếm",
82
+ show_label=True
83
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ def upload_wikipedia_file(file):
86
+ """Xử upload file với debug đầy đủ"""
87
+ if file is None:
88
+ return "❌ Vui lòng chọn file để upload"
 
 
 
 
 
 
 
 
 
 
89
 
90
+ try:
91
+ print(f"🔄 Bắt đầu upload file: {file.name}")
92
+
93
+ # Kiểm tra file tồn tại
94
+ if not os.path.exists(file.name):
95
+ return f"❌ File không tồn tại: {file.name}"
96
+
97
+ # Xử lý file
98
+ documents = wikipedia_processor.process_uploaded_file(file.name)
99
+
100
+ if not documents:
101
+ return "❌ Không thể trích xuất dữ liệu từ file. File có thể trống hoặc định dạng không đúng."
102
+
103
+ print(f"✅ Đã xử lý {len(documents)} documents")
104
+
105
+ # Tạo metadata
106
+ metadatas = []
107
+ for i, doc in enumerate(documents):
108
+ metadata = {
109
+ "source": "uploaded_file",
110
+ "type": "knowledge",
111
+ "file_name": os.path.basename(file.name),
112
+ "language": "vi",
113
+ "doc_id": i,
114
+ "length": len(doc)
115
+ }
116
+ metadatas.append(metadata)
117
+
118
+ # Thêm vào RAG system
119
+ old_stats = rag_system.get_collection_stats()
120
+ old_count = old_stats['total_documents']
121
+
122
+ rag_system.add_documents(documents, metadatas)
123
+
124
+ # Lấy thống kê mới
125
+ new_stats = rag_system.get_collection_stats()
126
+ new_count = new_stats['total_documents']
127
+
128
+ success_msg = f"""
129
+ ✅ UPLOAD THÀNH CÔNG!
130
+ 📁 File: {os.path.basename(file.name)}
131
+ 📄 Documents xử lý: {len(documents)}
132
+ 📊 Documents thêm vào: {new_count - old_count}
133
+ 🏷️ Tổng documents: {new_count}
134
+ 🔤 Embeddings: {new_stats['embedding_count']}
135
+ 🌐 Ngôn ngữ: {new_stats['language_distribution']}
136
+ 💡 Bạn có thể tìm kiếm ngay để kiểm tra dữ liệu!
137
+ """
138
+ return success_msg
139
+
140
+ except Exception as e:
141
+ error_msg = f"❌ LỖI UPLOAD: {str(e)}"
142
+ print(f"UPLOAD ERROR: {traceback.format_exc()}")
143
+ return error_msg
144
+
145
+ def get_rag_stats():
146
+ """Lấy thống kê chi tiết"""
147
+ try:
148
+ stats = rag_system.get_collection_stats()
149
+ return f"""
150
+ 📊 THỐNG KÊ RAG DATABASE:
151
+ • 📄 Tổng documents: {stats['total_documents']}
152
+ • 🔤 Số embeddings: {stats['embedding_count']}
153
+ • 📐 Dimension: {stats['embedding_dimension']}
154
+ • 🌐 Phân bố ngôn ngữ: {stats['language_distribution']}
155
+ • ✅ Trạng thái: {stats['status']}
156
+ • 🏷️ Tên: {stats['name']}
157
+ 💡 Embeddings: {'Có' if stats['has_embeddings'] else 'Không'}
158
+ """
159
+ except Exception as e:
160
+ return f"❌ Lỗi lấy thống kê: {str(e)}"
161
+
162
+ def search_rag_database(query):
163
+ """Tìm kiếm để kiểm tra dữ liệu"""
164
+ if not query.strip():
165
+ return [{"message": "Nhập từ khóa để tìm kiếm"}]
166
 
167
+ try:
168
+ results = rag_system.semantic_search(query, top_k=3)
169
+
170
+ if not results:
171
+ return [{"message": "Không tìm thấy kết quả nào", "query": query}]
172
+
173
+ return results
174
+
175
+ except Exception as e:
176
+ return [{"error": f"Lỗi tìm kiếm: {str(e)}"}]
177
+
178
+ # Event handlers
179
+ upload_btn.click(upload_wikipedia_file, inputs=[file_upload], outputs=[upload_status])
180
+ stats_btn.click(get_rag_stats, inputs=[], outputs=[stats_display])
181
+ search_btn.click(search_rag_database, inputs=[search_query], outputs=[rag_results])
182
 
183
+ return rag_tab
 
 
 
184
  def create_audio_tab(audio_service: AudioService):
185
  gr.Markdown("## Nói chuyện với AI (Đa ngôn ngữ)")
186
  audio_input, transcription_output, response_output, tts_audio_output, process_button = create_audio_components()