minhvtt commited on
Commit
a356b57
·
verified ·
1 Parent(s): 358773d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +927 -32
app.py CHANGED
@@ -1,47 +1,942 @@
1
- """
2
- Hugging Face Spaces compatible app
3
- """
 
 
 
 
 
4
  import os
5
- import gradio as gr
6
- from main import app as fastapi_app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Gradio wrapper cho Hugging Face Spaces
9
- def create_gradio_interface():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  """
11
- Tạo Gradio interface để deploy trên Hugging Face Spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  """
13
- with gr.Blocks(title="Event Social Media Embeddings API") as demo:
14
- gr.Markdown("""
15
- # 🔍 Event Social Media Embeddings API
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- API để embeddings và search multimodal (text + images) với **Jina CLIP v2** + **Qdrant Cloud**
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- ## 🌟 Features:
20
- - Multimodal: Text + Image embeddings
21
- - ✅ Tiếng Việt: 100% support
22
- - ✅ High Performance: ONNX + HNSW
23
- - ✅ Cloud: Qdrant Cloud
24
 
25
- ## 📡 API Endpoints:
26
- - `POST /index` - Index data
27
- - `POST /search` - Hybrid search
28
- - `POST /search/text` - Text search
29
- - `POST /search/image` - Image search
 
 
 
30
 
31
- ### 🔗 API Docs:
32
- Truy cập `/docs` để xem API documentation đầy đủ
33
- """)
 
 
34
 
35
- gr.Markdown("### API is running at the `/docs` endpoint")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- return demo
 
 
 
 
 
38
 
39
- # Mount FastAPI app
40
- demo = create_gradio_interface()
 
 
41
 
42
- # Wrap FastAPI với Gradio
43
- app = gr.mount_gradio_app(fastapi_app, demo, path="/")
44
 
45
  if __name__ == "__main__":
46
  import uvicorn
47
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from pydantic import BaseModel
5
+ from typing import Optional, List, Dict
6
+ from PIL import Image
7
+ import io
8
+ import numpy as np
9
  import os
10
+ from datetime import datetime
11
+ from pymongo import MongoClient
12
+ from huggingface_hub import InferenceClient
13
+
14
+ from embedding_service import JinaClipEmbeddingService
15
+ from qdrant_service import QdrantVectorService
16
+ from advanced_rag import AdvancedRAG
17
+ from cag_service import CAGService
18
+ from pdf_parser import PDFIndexer
19
+ from multimodal_pdf_parser import MultimodalPDFIndexer
20
+
21
+ # Initialize FastAPI app
22
+ app = FastAPI(
23
+ title="Event Social Media Embeddings & ChatbotRAG API",
24
+ description="API để embeddings, search và ChatbotRAG với Jina CLIP v2 + Qdrant + MongoDB + LLM",
25
+ version="2.0.0"
26
+ )
27
+
28
+ # CORS middleware
29
+ app.add_middleware(
30
+ CORSMiddleware,
31
+ allow_origins=["*"],
32
+ allow_credentials=True,
33
+ allow_methods=["*"],
34
+ allow_headers=["*"],
35
+ )
36
+
37
+ # Initialize services
38
+ print("Initializing services...")
39
+ embedding_service = JinaClipEmbeddingService(model_path="jinaai/jina-clip-v2")
40
+
41
+ collection_name = os.getenv("COLLECTION_NAME", "event_social_media")
42
+ qdrant_service = QdrantVectorService(
43
+ collection_name=collection_name,
44
+ vector_size=embedding_service.get_embedding_dimension()
45
+ )
46
+ print(f"✓ Qdrant collection: {collection_name}")
47
+
48
+ # MongoDB connection
49
+ mongodb_uri = os.getenv("MONGODB_URI", "mongodb+srv://truongtn7122003:7KaI9OT5KTUxWjVI@truongtn7122003.xogin4q.mongodb.net/")
50
+ mongo_client = MongoClient(mongodb_uri)
51
+ db = mongo_client[os.getenv("MONGODB_DB_NAME", "chatbot_rag")]
52
+ documents_collection = db["documents"]
53
+ chat_history_collection = db["chat_history"]
54
+ print("✓ MongoDB connected")
55
+
56
+ # Hugging Face token
57
+ hf_token = os.getenv("HUGGINGFACE_TOKEN")
58
+ if hf_token:
59
+ print("✓ Hugging Face token configured")
60
+
61
+ # Initialize Advanced RAG (Best Case 2025)
62
+ advanced_rag = AdvancedRAG(
63
+ embedding_service=embedding_service,
64
+ qdrant_service=qdrant_service
65
+ )
66
+ print("✓ Advanced RAG pipeline initialized (with Cross-Encoder)")
67
+
68
+ # Initialize CAG Service (Semantic Cache)
69
+ try:
70
+ cag_service = CAGService(
71
+ embedding_service=embedding_service,
72
+ cache_collection="semantic_cache",
73
+ vector_size=embedding_service.get_embedding_dimension(),
74
+ similarity_threshold=0.9,
75
+ ttl_hours=24
76
+ )
77
+ print("✓ CAG Service initialized (Semantic Caching enabled)")
78
+ except Exception as e:
79
+ print(f"Warning: CAG Service initialization failed: {e}")
80
+ print("Continuing without semantic caching...")
81
+ cag_service = None
82
+
83
+ # Initialize PDF Indexer
84
+ pdf_indexer = PDFIndexer(
85
+ embedding_service=embedding_service,
86
+ qdrant_service=qdrant_service,
87
+ documents_collection=documents_collection
88
+ )
89
+ print("✓ PDF Indexer initialized")
90
+
91
+ # Initialize Multimodal PDF Indexer
92
+ multimodal_pdf_indexer = MultimodalPDFIndexer(
93
+ embedding_service=embedding_service,
94
+ qdrant_service=qdrant_service,
95
+ documents_collection=documents_collection
96
+ )
97
+ print("✓ Multimodal PDF Indexer initialized")
98
+
99
+ print("✓ Services initialized successfully")
100
+
101
+
102
+ # Pydantic models for embeddings
103
+ class SearchRequest(BaseModel):
104
+ text: Optional[str] = None
105
+ limit: int = 10
106
+ score_threshold: Optional[float] = None
107
+ text_weight: float = 0.5
108
+ image_weight: float = 0.5
109
+
110
+
111
+ class SearchResponse(BaseModel):
112
+ id: str
113
+ confidence: float
114
+ metadata: dict
115
+
116
+
117
+ class IndexResponse(BaseModel):
118
+ success: bool
119
+ id: str
120
+ message: str
121
+
122
+
123
+ # Pydantic models for ChatbotRAG
124
+ class ChatRequest(BaseModel):
125
+ message: str
126
+ use_rag: bool = True
127
+ top_k: int = 3
128
+ system_message: Optional[str] = """Bạn là trợ lý AI chuyên biệt cho hệ thống quản lý sự kiện và mạng xã hội.
129
+ Vai trò của bạn là trả lời các câu hỏi CHÍNH XÁC dựa trên dữ liệu được cung cấp từ hệ thống.
130
+
131
+ Quy tắc tuyệt đối:
132
+ - CHỈ trả lời câu hỏi liên quan đến: events, social media posts, PDFs đã upload, và dữ liệu trong knowledge base
133
+ - KHÔNG trả lời câu hỏi ngoài phạm vi (tin tức, thời tiết, toán học, lập trình, tư vấn cá nhân, v.v.)
134
+ - Nếu câu hỏi nằm ngoài phạm vi: BẮT BUỘC trả lời "Chúng tôi không thể trả lời câu hỏi này vì nó nằm ngoài vùng application xử lí."
135
+ - Luôn ưu tiên thông tin từ context được cung cấp"""
136
+ max_tokens: int = 512
137
+ temperature: float = 0.7
138
+ top_p: float = 0.95
139
+ hf_token: Optional[str] = None
140
+ # Advanced RAG options
141
+ use_advanced_rag: bool = True
142
+ use_query_expansion: bool = True
143
+ use_reranking: bool = True
144
+ use_compression: bool = True
145
+ score_threshold: float = 0.5
146
+
147
+
148
+ class ChatResponse(BaseModel):
149
+ response: str
150
+ context_used: List[Dict]
151
+ timestamp: str
152
+ rag_stats: Optional[Dict] = None # Stats from advanced RAG pipeline
153
+
154
+
155
+ class AddDocumentRequest(BaseModel):
156
+ text: str
157
+ metadata: Optional[Dict] = None
158
+
159
+
160
+ class AddDocumentResponse(BaseModel):
161
+ success: bool
162
+ doc_id: str
163
+ message: str
164
+
165
+
166
+ @app.get("/")
167
+ async def root():
168
+ """Health check endpoint with comprehensive API documentation"""
169
+ return {
170
+ "status": "running",
171
+ "service": "ChatbotRAG API",
172
+ "version": "2.0.0",
173
+ "vector_db": "Qdrant",
174
+ "document_db": "MongoDB",
175
+ "endpoints": {
176
+ "chatbot_rag": {
177
+ "API endpoint": "https://minhvtt-ChatbotRAG.hf.space/",
178
+ "POST /chat": {
179
+ "description": "Chat với AI sử dụng RAG (Retrieval-Augmented Generation)",
180
+ "request": {
181
+ "method": "POST",
182
+ "content_type": "application/json",
183
+ "body": {
184
+ "message": "string (required) - User message/question",
185
+ "use_rag": "boolean (optional, default: true) - Enable RAG context retrieval",
186
+ "top_k": "integer (optional, default: 3) - Number of context documents to retrieve",
187
+ "system_message": "string (optional) - Custom system prompt",
188
+ "max_tokens": "integer (optional, default: 512) - Max response length",
189
+ "temperature": "float (optional, default: 0.7, range: 0-1) - Creativity level",
190
+ "top_p": "float (optional, default: 0.95) - Nucleus sampling",
191
+ "hf_token": "string (optional) - Hugging Face token (fallback to env)"
192
+ }
193
+ },
194
+ "response": {
195
+ "response": "string - AI generated response",
196
+ "context_used": [
197
+ {
198
+ "id": "string - Document ID",
199
+ "confidence": "float - Relevance score",
200
+ "metadata": {
201
+ "text": "string - Retrieved context"
202
+ }
203
+ }
204
+ ],
205
+ "timestamp": "string - ISO 8601 timestamp"
206
+ },
207
+ "example_request": {
208
+ "message": "Dao có nguy hiểm không?",
209
+ "use_rag": True,
210
+ "top_k": 3,
211
+ "temperature": 0.7
212
+ },
213
+ "example_response": {
214
+ "response": "Dựa trên thông tin trong database, dao được phân loại là vũ khí nguy hiểm. Dao sắc có thể gây thương tích nghiêm trọng nếu không sử dụng đúng cách. Cần tuân thủ các quy định an toàn khi sử dụng.",
215
+ "context_used": [
216
+ {
217
+ "id": "68a3fc14c853d7621e8977b5",
218
+ "confidence": 0.92,
219
+ "metadata": {
220
+ "text": "Vũ khí"
221
+ }
222
+ },
223
+ {
224
+ "id": "68a3fc4cc853d7621e8977b6",
225
+ "confidence": 0.85,
226
+ "metadata": {
227
+ "text": "Con dao sắc"
228
+ }
229
+ }
230
+ ],
231
+ "timestamp": "2025-10-13T10:30:45.123456"
232
+ },
233
+ "notes": [
234
+ "RAG retrieves relevant context from vector DB before generating response",
235
+ "LLM uses context to provide accurate, grounded answers",
236
+ "Requires HUGGINGFACE_TOKEN environment variable or hf_token in request"
237
+ ]
238
+ },
239
+ "POST /documents": {
240
+ "description": "Add document to knowledge base for RAG",
241
+ "request": {
242
+ "method": "POST",
243
+ "content_type": "application/json",
244
+ "body": {
245
+ "text": "string (required) - Document text content",
246
+ "metadata": "object (optional) - Additional metadata (source, category, etc.)"
247
+ }
248
+ },
249
+ "response": {
250
+ "success": "boolean",
251
+ "doc_id": "string - MongoDB ObjectId",
252
+ "message": "string - Status message"
253
+ },
254
+ "example_request": {
255
+ "text": "Để tạo event mới: Click nút 'Tạo Event' ở góc trên bên phải màn hình. Điền thông tin sự kiện bao gồm tên, ngày giờ, địa điểm. Click Lưu để hoàn tất.",
256
+ "metadata": {
257
+ "source": "user_guide.pdf",
258
+ "section": "create_event",
259
+ "page": 5,
260
+ "category": "tutorial"
261
+ }
262
+ },
263
+ "example_response": {
264
+ "success": True,
265
+ "doc_id": "67a9876543210fedcba98765",
266
+ "message": "Document added successfully with ID: 67a9876543210fedcba98765"
267
+ }
268
+ },
269
+ "POST /rag/search": {
270
+ "description": "Search in knowledge base (similar to /search/text but for RAG documents)",
271
+ "request": {
272
+ "method": "POST",
273
+ "content_type": "multipart/form-data",
274
+ "body": {
275
+ "query": "string (required) - Search query",
276
+ "top_k": "integer (optional, default: 5) - Number of results",
277
+ "score_threshold": "float (optional, default: 0.5) - Minimum relevance score"
278
+ }
279
+ },
280
+ "response": [
281
+ {
282
+ "id": "string",
283
+ "confidence": "float",
284
+ "metadata": {
285
+ "text": "string",
286
+ "source": "string"
287
+ }
288
+ }
289
+ ],
290
+ "example_request": {
291
+ "query": "cách tạo sự kiện mới",
292
+ "top_k": 3,
293
+ "score_threshold": 0.6
294
+ }
295
+ },
296
+ "GET /history": {
297
+ "description": "Get chat conversation history",
298
+ "request": {
299
+ "method": "GET",
300
+ "query_params": {
301
+ "limit": "integer (optional, default: 10) - Number of messages",
302
+ "skip": "integer (optional, default: 0) - Pagination offset"
303
+ }
304
+ },
305
+ "response": {
306
+ "history": [
307
+ {
308
+ "user_message": "string",
309
+ "assistant_response": "string",
310
+ "context_used": "array",
311
+ "timestamp": "string - ISO 8601"
312
+ }
313
+ ],
314
+ "total": "integer - Total messages count"
315
+ },
316
+ "example_request": "GET /history?limit=5&skip=0",
317
+ "example_response": {
318
+ "history": [
319
+ {
320
+ "user_message": "Dao có nguy hiểm không?",
321
+ "assistant_response": "Dao được phân loại là vũ khí...",
322
+ "context_used": [],
323
+ "timestamp": "2025-10-13T10:30:45.123456"
324
+ }
325
+ ],
326
+ "total": 15
327
+ }
328
+ },
329
+ "DELETE /documents/{doc_id}": {
330
+ "description": "Delete document from knowledge base",
331
+ "request": {
332
+ "method": "DELETE",
333
+ "path_params": {
334
+ "doc_id": "string - MongoDB ObjectId"
335
+ }
336
+ },
337
+ "response": {
338
+ "success": "boolean",
339
+ "message": "string"
340
+ }
341
+ }
342
+ }
343
+ },
344
+ "usage_examples": {
345
+ "curl_chat": "curl -X POST 'http://localhost:8000/chat' -H 'Content-Type: application/json' -d '{\"message\": \"Dao có nguy hiểm không?\", \"use_rag\": true}'",
346
+ "python_chat": """
347
+ import requests
348
+
349
+ response = requests.post(
350
+ 'http://localhost:8000/chat',
351
+ json={
352
+ 'message': 'Nút tạo event ở đâu?',
353
+ 'use_rag': True,
354
+ 'top_k': 3
355
+ }
356
+ )
357
+ print(response.json()['response'])
358
+ """
359
+ },
360
+ "authentication": {
361
+ "embeddings_apis": "No authentication required",
362
+ "chat_api": "Requires HUGGINGFACE_TOKEN (env variable or request body)"
363
+ },
364
+ "rate_limits": {
365
+ "embeddings": "No limit",
366
+ "chat_with_llm": "Limited by Hugging Face API (free tier: ~1000 requests/hour)"
367
+ },
368
+ "error_codes": {
369
+ "400": "Bad Request - Missing required fields or invalid input",
370
+ "401": "Unauthorized - Invalid Hugging Face token",
371
+ "404": "Not Found - Document ID not found",
372
+ "500": "Internal Server Error - Server or database error"
373
+ },
374
+ "links": {
375
+ "docs": "http://localhost:8000/docs",
376
+ "redoc": "http://localhost:8000/redoc",
377
+ "openapi": "http://localhost:8000/openapi.json"
378
+ }
379
+ }
380
+
381
+ @app.post("/index", response_model=IndexResponse)
382
+ async def index_data(
383
+ id: str = Form(...),
384
+ text: str = Form(...),
385
+ image: Optional[UploadFile] = File(None)
386
+ ):
387
+ """
388
+ Index data vào vector database
389
+
390
+ Body:
391
+ - id: Document ID (event ID, post ID, etc.)
392
+ - text: Text content (tiếng Việt supported)
393
+ - image: Image file (optional)
394
+
395
+ Returns:
396
+ - success: True/False
397
+ - id: Document ID
398
+ - message: Status message
399
+ """
400
+ try:
401
+ # Prepare embeddings
402
+ text_embedding = None
403
+ image_embedding = None
404
+
405
+ # Encode text (tiếng Việt)
406
+ if text and text.strip():
407
+ text_embedding = embedding_service.encode_text(text)
408
+
409
+ # Encode image nếu có
410
+ if image:
411
+ image_bytes = await image.read()
412
+ pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
413
+ image_embedding = embedding_service.encode_image(pil_image)
414
+
415
+ # Combine embeddings
416
+ if text_embedding is not None and image_embedding is not None:
417
+ # Average của text và image embeddings
418
+ combined_embedding = np.mean([text_embedding, image_embedding], axis=0)
419
+ elif text_embedding is not None:
420
+ combined_embedding = text_embedding
421
+ elif image_embedding is not None:
422
+ combined_embedding = image_embedding
423
+ else:
424
+ raise HTTPException(status_code=400, detail="Phải cung cấp ít nhất text hoặc image")
425
+
426
+ # Normalize
427
+ combined_embedding = combined_embedding / np.linalg.norm(combined_embedding, axis=1, keepdims=True)
428
+
429
+ # Index vào Qdrant
430
+ metadata = {
431
+ "text": text,
432
+ "has_image": image is not None,
433
+ "image_filename": image.filename if image else None
434
+ }
435
+
436
+ result = qdrant_service.index_data(
437
+ doc_id=id,
438
+ embedding=combined_embedding,
439
+ metadata=metadata
440
+ )
441
+
442
+ return IndexResponse(
443
+ success=True,
444
+ id=result["original_id"], # Trả về MongoDB ObjectId
445
+ message=f"Đã index thành công document {result['original_id']} (Qdrant UUID: {result['qdrant_id']})"
446
+ )
447
+
448
+ except Exception as e:
449
+ raise HTTPException(status_code=500, detail=f"Lỗi khi index: {str(e)}")
450
+
451
+
452
+ @app.post("/search", response_model=List[SearchResponse])
453
+ async def search(
454
+ text: Optional[str] = Form(None),
455
+ image: Optional[UploadFile] = File(None),
456
+ limit: int = Form(10),
457
+ score_threshold: Optional[float] = Form(None),
458
+ text_weight: float = Form(0.5),
459
+ image_weight: float = Form(0.5)
460
+ ):
461
+ """
462
+ Search similar documents bằng text và/hoặc image
463
+
464
+ Body:
465
+ - text: Query text (tiếng Việt supported)
466
+ - image: Query image (optional)
467
+ - limit: Số lượng kết quả (default: 10)
468
+ - score_threshold: Minimum confidence score (0-1)
469
+ - text_weight: Weight cho text search (default: 0.5)
470
+ - image_weight: Weight cho image search (default: 0.5)
471
+
472
+ Returns:
473
+ - List of results với id, confidence, và metadata
474
+ """
475
+ try:
476
+ # Prepare query embeddings
477
+ text_embedding = None
478
+ image_embedding = None
479
+
480
+ # Encode text query
481
+ if text and text.strip():
482
+ text_embedding = embedding_service.encode_text(text)
483
+
484
+ # Encode image query
485
+ if image:
486
+ image_bytes = await image.read()
487
+ pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
488
+ image_embedding = embedding_service.encode_image(pil_image)
489
+
490
+ # Validate input
491
+ if text_embedding is None and image_embedding is None:
492
+ raise HTTPException(status_code=400, detail="Phải cung cấp ít nhất text hoặc image để search")
493
+
494
+ # Hybrid search với Qdrant
495
+ results = qdrant_service.hybrid_search(
496
+ text_embedding=text_embedding,
497
+ image_embedding=image_embedding,
498
+ text_weight=text_weight,
499
+ image_weight=image_weight,
500
+ limit=limit,
501
+ score_threshold=score_threshold,
502
+ ef=256 # High accuracy search
503
+ )
504
+
505
+ # Format response
506
+ return [
507
+ SearchResponse(
508
+ id=result["id"],
509
+ confidence=result["confidence"],
510
+ metadata=result["metadata"]
511
+ )
512
+ for result in results
513
+ ]
514
+
515
+ except Exception as e:
516
+ raise HTTPException(status_code=500, detail=f"Lỗi khi search: {str(e)}")
517
+
518
+
519
+ @app.post("/search/text", response_model=List[SearchResponse])
520
+ async def search_by_text(
521
+ text: str = Form(...),
522
+ limit: int = Form(10),
523
+ score_threshold: Optional[float] = Form(None)
524
+ ):
525
+ """
526
+ Search chỉ bằng text (tiếng Việt)
527
+
528
+ Body:
529
+ - text: Query text (tiếng Việt)
530
+ - limit: Số lượng kết quả
531
+ - score_threshold: Minimum confidence score
532
+
533
+ Returns:
534
+ - List of results
535
+ """
536
+ try:
537
+ # Encode text
538
+ text_embedding = embedding_service.encode_text(text)
539
+
540
+ # Search
541
+ results = qdrant_service.search(
542
+ query_embedding=text_embedding,
543
+ limit=limit,
544
+ score_threshold=score_threshold,
545
+ ef=256
546
+ )
547
+
548
+ return [
549
+ SearchResponse(
550
+ id=result["id"],
551
+ confidence=result["confidence"],
552
+ metadata=result["metadata"]
553
+ )
554
+ for result in results
555
+ ]
556
+
557
+ except Exception as e:
558
+ raise HTTPException(status_code=500, detail=f"Lỗi khi search: {str(e)}")
559
+
560
+
561
+ @app.post("/search/image", response_model=List[SearchResponse])
562
+ async def search_by_image(
563
+ image: UploadFile = File(...),
564
+ limit: int = Form(10),
565
+ score_threshold: Optional[float] = Form(None)
566
+ ):
567
+ """
568
+ Search chỉ bằng image
569
 
570
+ Body:
571
+ - image: Query image
572
+ - limit: Số lượng kết quả
573
+ - score_threshold: Minimum confidence score
574
+
575
+ Returns:
576
+ - List of results
577
+ """
578
+ try:
579
+ # Encode image
580
+ image_bytes = await image.read()
581
+ pil_image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
582
+ image_embedding = embedding_service.encode_image(pil_image)
583
+
584
+ # Search
585
+ results = qdrant_service.search(
586
+ query_embedding=image_embedding,
587
+ limit=limit,
588
+ score_threshold=score_threshold,
589
+ ef=256
590
+ )
591
+
592
+ return [
593
+ SearchResponse(
594
+ id=result["id"],
595
+ confidence=result["confidence"],
596
+ metadata=result["metadata"]
597
+ )
598
+ for result in results
599
+ ]
600
+
601
+ except Exception as e:
602
+ raise HTTPException(status_code=500, detail=f"Lỗi khi search: {str(e)}")
603
+
604
+
605
+ @app.delete("/delete/{doc_id}")
606
+ async def delete_document(doc_id: str):
607
+ """
608
+ Delete document by ID (MongoDB ObjectId hoặc UUID)
609
+
610
+ Args:
611
+ - doc_id: Document ID to delete
612
+
613
+ Returns:
614
+ - Success message
615
  """
616
+ try:
617
+ qdrant_service.delete_by_id(doc_id)
618
+ return {"success": True, "message": f"Đã xóa document {doc_id}"}
619
+ except Exception as e:
620
+ raise HTTPException(status_code=500, detail=f"Lỗi khi xóa: {str(e)}")
621
+
622
+
623
+ @app.get("/document/{doc_id}")
624
+ async def get_document(doc_id: str):
625
+ """
626
+ Get document by ID (MongoDB ObjectId hoặc UUID)
627
+
628
+ Args:
629
+ - doc_id: Document ID (MongoDB ObjectId)
630
+
631
+ Returns:
632
+ - Document data
633
+ """
634
+ try:
635
+ doc = qdrant_service.get_by_id(doc_id)
636
+ if doc:
637
+ return {
638
+ "success": True,
639
+ "data": doc
640
+ }
641
+ raise HTTPException(status_code=404, detail=f"Không tìm thấy document {doc_id}")
642
+ except HTTPException:
643
+ raise
644
+ except Exception as e:
645
+ raise HTTPException(status_code=500, detail=f"Lỗi khi get document: {str(e)}")
646
+
647
+
648
+ @app.get("/stats")
649
+ async def get_stats():
650
  """
651
+ Lấy thông tin thống collection
652
+
653
+ Returns:
654
+ - Collection statistics
655
+ """
656
+ try:
657
+ info = qdrant_service.get_collection_info()
658
+ return info
659
+ except Exception as e:
660
+ raise HTTPException(status_code=500, detail=f"Lỗi khi lấy stats: {str(e)}")
661
+
662
+
663
+ # ============================================
664
+ # ChatbotRAG Endpoints
665
+ # ============================================
666
+
667
+ @app.post("/chat", response_model=ChatResponse)
668
+ async def chat(request: ChatRequest):
669
+ """
670
+ Chat endpoint với RAG
671
+
672
+ Body:
673
+ - message: User message
674
+ - use_rag: Enable RAG retrieval (default: true)
675
+ - top_k: Number of documents to retrieve (default: 3)
676
+ - system_message: System prompt (optional)
677
+ - max_tokens: Max tokens for response (default: 512)
678
+ - temperature: Temperature for generation (default: 0.7)
679
+ - hf_token: Hugging Face token (optional, sẽ dùng env nếu không truyền)
680
+
681
+ Returns:
682
+ - response: Generated response
683
+ - context_used: Retrieved context documents
684
+ - timestamp: Response timestamp
685
+ """
686
+ try:
687
+ # Retrieve context if RAG enabled
688
+ context_used = []
689
+ if request.use_rag:
690
+ # Generate query embedding
691
+ query_embedding = embedding_service.encode_text(request.message)
692
+
693
+ # Search in Qdrant
694
+ results = qdrant_service.search(
695
+ query_embedding=query_embedding,
696
+ limit=request.top_k,
697
+ score_threshold=0.5
698
+ )
699
+ context_used = results
700
+
701
+ # Build context text
702
+ context_text = ""
703
+ if context_used:
704
+ context_text = "\n\nRelevant Context:\n"
705
+ for i, doc in enumerate(context_used, 1):
706
+ doc_text = doc["metadata"].get("text", "")
707
+ confidence = doc["confidence"]
708
+ context_text += f"\n[{i}] (Confidence: {confidence:.2f})\n{doc_text}\n"
709
+
710
+ # Add context to system message
711
+ system_message = f"{request.system_message}\n{context_text}\n\nPlease use the above context to answer the user's question when relevant."
712
+ else:
713
+ system_message = request.system_message
714
+
715
+ # Use token from request or fallback to env
716
+ token = request.hf_token or hf_token
717
+ # Generate response
718
+ if not token:
719
+ response = f"""[LLM Response Placeholder]
720
+
721
+ Context retrieved: {len(context_used)} documents
722
+ User question: {request.message}
723
+
724
+ To enable actual LLM generation:
725
+ 1. Set HUGGINGFACE_TOKEN environment variable, OR
726
+ 2. Pass hf_token in request body
727
+
728
+ Example:
729
+ {{
730
+ "message": "Your question",
731
+ "hf_token": "hf_xxxxxxxxxxxxx"
732
+ }}
733
+ """
734
+ else:
735
+ try:
736
+ client = InferenceClient(
737
+ token=hf_token,
738
+ model="openai/gpt-oss-20b"
739
+ )
740
+
741
+ # Build messages
742
+ messages = [
743
+ {"role": "system", "content": system_message},
744
+ {"role": "user", "content": request.message}
745
+ ]
746
 
747
+ # Generate response
748
+ response = ""
749
+ for msg in client.chat_completion(
750
+ messages,
751
+ max_tokens=request.max_tokens,
752
+ stream=True,
753
+ temperature=request.temperature,
754
+ top_p=request.top_p,
755
+ ):
756
+ choices = msg.choices
757
+ if len(choices) and choices[0].delta.content:
758
+ response += choices[0].delta.content
759
 
760
+ except Exception as e:
761
+ response = f"Error generating response with LLM: {str(e)}\n\nContext was retrieved successfully, but LLM generation failed."
 
 
 
762
 
763
+ # Save to history
764
+ chat_data = {
765
+ "user_message": request.message,
766
+ "assistant_response": response,
767
+ "context_used": context_used,
768
+ "timestamp": datetime.utcnow()
769
+ }
770
+ chat_history_collection.insert_one(chat_data)
771
 
772
+ return ChatResponse(
773
+ response=response,
774
+ context_used=context_used,
775
+ timestamp=datetime.utcnow().isoformat()
776
+ )
777
 
778
+ except Exception as e:
779
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
780
+
781
+
782
+ @app.post("/documents", response_model=AddDocumentResponse)
783
+ async def add_document(request: AddDocumentRequest):
784
+ """
785
+ Add document to knowledge base
786
+
787
+ Body:
788
+ - text: Document text
789
+ - metadata: Additional metadata (optional)
790
+
791
+ Returns:
792
+ - success: True/False
793
+ - doc_id: MongoDB document ID
794
+ - message: Status message
795
+ """
796
+ try:
797
+ # Save to MongoDB
798
+ doc_data = {
799
+ "text": request.text,
800
+ "metadata": request.metadata or {},
801
+ "created_at": datetime.utcnow()
802
+ }
803
+ result = documents_collection.insert_one(doc_data)
804
+ doc_id = str(result.inserted_id)
805
+
806
+ # Generate embedding
807
+ embedding = embedding_service.encode_text(request.text)
808
+
809
+ # Index to Qdrant
810
+ qdrant_service.index_data(
811
+ doc_id=doc_id,
812
+ embedding=embedding,
813
+ metadata={
814
+ "text": request.text,
815
+ "source": "api",
816
+ **(request.metadata or {})
817
+ }
818
+ )
819
+
820
+ return AddDocumentResponse(
821
+ success=True,
822
+ doc_id=doc_id,
823
+ message=f"Document added successfully with ID: {doc_id}"
824
+ )
825
+
826
+ except Exception as e:
827
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
828
+
829
+
830
+ @app.post("/rag/search", response_model=List[SearchResponse])
831
+ async def rag_search(
832
+ query: str = Form(...),
833
+ top_k: int = Form(5),
834
+ score_threshold: Optional[float] = Form(0.5)
835
+ ):
836
+ """
837
+ Search in knowledge base
838
+
839
+ Body:
840
+ - query: Search query
841
+ - top_k: Number of results (default: 5)
842
+ - score_threshold: Minimum score (default: 0.5)
843
+
844
+ Returns:
845
+ - results: List of matching documents
846
+ """
847
+ try:
848
+ # Generate query embedding
849
+ query_embedding = embedding_service.encode_text(query)
850
+
851
+ # Search in Qdrant
852
+ results = qdrant_service.search(
853
+ query_embedding=query_embedding,
854
+ limit=top_k,
855
+ score_threshold=score_threshold
856
+ )
857
+
858
+ return [
859
+ SearchResponse(
860
+ id=result["id"],
861
+ confidence=result["confidence"],
862
+ metadata=result["metadata"]
863
+ )
864
+ for result in results
865
+ ]
866
+
867
+ except Exception as e:
868
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
869
+
870
+
871
+ @app.get("/history")
872
+ async def get_history(limit: int = 10, skip: int = 0):
873
+ """
874
+ Get chat history
875
+
876
+ Query params:
877
+ - limit: Number of messages to return (default: 10)
878
+ - skip: Number of messages to skip (default: 0)
879
+
880
+ Returns:
881
+ - history: List of chat messages
882
+ """
883
+ try:
884
+ history = list(
885
+ chat_history_collection
886
+ .find({}, {"_id": 0})
887
+ .sort("timestamp", -1)
888
+ .skip(skip)
889
+ .limit(limit)
890
+ )
891
+
892
+ # Convert datetime to string
893
+ for msg in history:
894
+ if "timestamp" in msg:
895
+ msg["timestamp"] = msg["timestamp"].isoformat()
896
+
897
+ return {
898
+ "history": history,
899
+ "total": chat_history_collection.count_documents({})
900
+ }
901
+
902
+ except Exception as e:
903
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
904
+
905
+
906
+ @app.delete("/documents/{doc_id}")
907
+ async def delete_document_from_kb(doc_id: str):
908
+ """
909
+ Delete document from knowledge base
910
+
911
+ Args:
912
+ - doc_id: Document ID (MongoDB ObjectId)
913
+
914
+ Returns:
915
+ - success: True/False
916
+ - message: Status message
917
+ """
918
+ try:
919
+ # Delete from MongoDB
920
+ result = documents_collection.delete_one({"_id": doc_id})
921
 
922
+ # Delete from Qdrant
923
+ if result.deleted_count > 0:
924
+ qdrant_service.delete_by_id(doc_id)
925
+ return {"success": True, "message": f"Document {doc_id} deleted from knowledge base"}
926
+ else:
927
+ raise HTTPException(status_code=404, detail=f"Document {doc_id} not found")
928
 
929
+ except HTTPException:
930
+ raise
931
+ except Exception as e:
932
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
933
 
 
 
934
 
935
  if __name__ == "__main__":
936
  import uvicorn
937
+ uvicorn.run(
938
+ app,
939
+ host="0.0.0.0",
940
+ port=8000,
941
+ log_level="info"
942
+ )