minhvtt commited on
Commit
db3cd2b
·
verified ·
1 Parent(s): 2f50e28

Delete MULTIMODAL_PDF_GUIDE.md

Browse files
Files changed (1) hide show
  1. MULTIMODAL_PDF_GUIDE.md +0 -525
MULTIMODAL_PDF_GUIDE.md DELETED
@@ -1,525 +0,0 @@
1
- # Multimodal PDF Guide - PDFs với Text + Hình Ảnh
2
-
3
- ## Tổng Quan
4
-
5
- Hệ thống giờ hỗ trợ **Multimodal PDF** - PDFs có:
6
- - ✅ Text hướng dẫn
7
- - ✅ Image URLs (links đến hình ảnh)
8
- - ✅ Markdown images: `![alt](url)`
9
- - ✅ HTML images: `<img src="url">`
10
-
11
- **Perfect cho**: User guides với screenshots, tutorials với diagrams, documentation với visual aids.
12
-
13
- ---
14
-
15
- ## Tại Sao Cần Multimodal?
16
-
17
- ### Vấn Đề Với PDF Thông Thường
18
-
19
- PDF hướng dẫn thường có:
20
- ```
21
- Bước 1: Mở trang chủ
22
- [Xem hình ảnh: https://example.com/homepage.png]
23
-
24
- Bước 2: Click vào "Tạo mới"
25
- ![Create button](https://example.com/create-button.png)
26
-
27
- Bước 3: Điền thông tin
28
- <img src="https://example.com/form.png" alt="Form" />
29
- ```
30
-
31
- **PDF parser cũ** chỉ extract text → **MẤT hết image URLs** → Chatbot không biết hình ảnh nào liên quan!
32
-
33
- **Multimodal PDF parser mới**:
34
- - ✓ Extract text
35
- - ✓ Detect tất cả image URLs
36
- - ✓ Link images với text chunks tương ứng
37
- - ✓ Store URLs trong metadata
38
- - ✓ Return images cùng text khi chat
39
-
40
- ---
41
-
42
- ## So Sánh: PDF Thường vs Multimodal PDF
43
-
44
- | Feature | PDF Thường (`/upload-pdf`) | Multimodal PDF (`/upload-pdf-multimodal`) |
45
- |---------|---------------------------|-------------------------------------------|
46
- | Extract text | ✓ | ✓ |
47
- | Detect image URLs | ✗ | ✓ |
48
- | Link images to chunks | ✗ | ✓ |
49
- | Return images in chat | ✗ | ✓ |
50
- | URL formats supported | ✗ | http://, https://, markdown, HTML |
51
- | Use case | Simple text documents | User guides, tutorials, docs with images |
52
-
53
- ---
54
-
55
- ## Cách Sử Dụng
56
-
57
- ### 1. Upload Multimodal PDF
58
-
59
- **Endpoint:** `POST /upload-pdf-multimodal`
60
-
61
- **Curl:**
62
- ```bash
63
- curl -X POST "http://localhost:8000/upload-pdf-multimodal" \
64
- -F "file=@user_guide_with_images.pdf" \
65
- -F "title=Hướng dẫn sử dụng hệ thống" \
66
- -F "description=User guide with screenshots" \
67
- -F "category=user_guide"
68
- ```
69
-
70
- **Python:**
71
- ```python
72
- import requests
73
-
74
- with open('user_guide_with_images.pdf', 'rb') as f:
75
- response = requests.post(
76
- 'http://localhost:8000/upload-pdf-multimodal',
77
- files={'file': f},
78
- data={
79
- 'title': 'User Guide with Screenshots',
80
- 'category': 'user_guide'
81
- }
82
- )
83
-
84
- result = response.json()
85
- print(f"Indexed: {result['chunks_indexed']} chunks")
86
- print(f"Images found: {result['message']}")
87
- ```
88
-
89
- **Response:**
90
- ```json
91
- {
92
- "success": true,
93
- "document_id": "pdf_multimodal_20251029_150000",
94
- "filename": "user_guide_with_images.pdf",
95
- "chunks_indexed": 25,
96
- "message": "PDF 'user_guide_with_images.pdf' indexed successfully with 25 chunks and 15 images"
97
- }
98
- ```
99
-
100
- ### 2. Chat Với Multimodal Context
101
-
102
- ```python
103
- import requests
104
-
105
- response = requests.post('http://localhost:8000/chat', json={
106
- 'message': 'Làm sao để tạo event mới?',
107
- 'use_rag': True,
108
- 'use_advanced_rag': True,
109
- 'top_k': 3,
110
- 'hf_token': 'your_token'
111
- })
112
-
113
- result = response.json()
114
-
115
- # Response text
116
- print("Answer:", result['response'])
117
-
118
- # Retrieved context with images
119
- for ctx in result['context_used']:
120
- print(f"\n--- Source: Page {ctx['metadata']['page']} ---")
121
- print(f"Text: {ctx['metadata']['text'][:200]}...")
122
-
123
- # Check if this chunk has images
124
- if ctx['metadata'].get('has_images'):
125
- print(f"Images ({ctx['metadata']['num_images']}):")
126
- for img_url in ctx['metadata'].get('image_urls', []):
127
- print(f" - {img_url}")
128
- ```
129
-
130
- **Example Output:**
131
- ```
132
- Answer: Để tạo event mới, bạn thực hiện các bước sau:
133
- 1. Mở trang chủ và click vào nút "Tạo Event" (xem hình minh họa)
134
- 2. Điền thông tin event...
135
-
136
- --- Source: Page 5 ---
137
- Text: Bước 1: Mở trang chủ và click vào nút "Tạo Event"...
138
- Images (2):
139
- - https://example.com/homepage.png
140
- - https://example.com/create-button.png
141
- ```
142
-
143
- ---
144
-
145
- ## Cách Chuẩn Bị PDF
146
-
147
- ### Format Hỗ Trợ
148
-
149
- Multimodal parser detect các format sau:
150
-
151
- 1. **Standard URLs:**
152
- ```
153
- Xem hình: https://example.com/image.png
154
- Screenshot: http://cdn.example.com/screenshot.jpg
155
- ```
156
-
157
- 2. **Markdown Images:**
158
- ```markdown
159
- ![Homepage](https://example.com/homepage.png)
160
- ![Button](https://example.com/button.png)
161
- ```
162
-
163
- 3. **HTML Images:**
164
- ```html
165
- <img src="https://example.com/form.png" alt="Form" />
166
- <img src="http://example.com/result.jpg">
167
- ```
168
-
169
- 4. **Image Extensions:**
170
- ```
171
- https://example.com/pic.jpg
172
- https://example.com/chart.png
173
- https://example.com/diagram.svg
174
- ```
175
-
176
- ### Best Practices
177
-
178
- #### ✓ Tốt
179
-
180
- **PDF Content Example:**
181
- ```
182
- # Hướng Dẫn Tạo Event
183
-
184
- ## Bước 1: Mở Trang Chủ
185
-
186
- Truy cập vào trang chủ hệ thống tại homepage.
187
-
188
- ![Homepage Screenshot](https://docs.example.com/images/homepage.png)
189
-
190
- Bạn sẽ thấy màn hình chính với menu bên trái.
191
-
192
- ## Bước 2: Click "Tạo Event"
193
-
194
- Tìm và click vào nút "Tạo Event" ở góc trên phải.
195
-
196
- ![Create Event Button](https://docs.example.com/images/create-button.png)
197
-
198
- ## Bước 3: Điền Thông Tin
199
-
200
- Điền các thông tin sau vào form:
201
- - Tên event
202
- - Ngày giờ
203
- - Địa điểm
204
-
205
- Xem mẫu form: https://docs.example.com/images/event-form.png
206
- ```
207
-
208
- **Why good:**
209
- - Có cấu trúc rõ ràng (headings)
210
- - Mỗi bước có text + hình ảnh
211
- - URLs rõ ràng, dễ detect
212
- - Context gắn chặt với hình
213
-
214
- #### ✗ Tránh
215
-
216
- ```
217
- Xem các hình dưới đây [1] [2] [3]
218
-
219
- [Các hình ảnh ở cuối tài liệu]
220
-
221
- ...
222
-
223
- [1] homepage.png
224
- [2] button.png
225
- [3] form.png
226
- ```
227
-
228
- **Why bad:**
229
- - Images references không có URLs
230
- - Images tách biệt khỏi context
231
- - Không có full URLs (chỉ filenames)
232
-
233
- ---
234
-
235
- ## Ví Dụ Thực Tế
236
-
237
- ### Tạo PDF Hướng Dẫn Multimodal
238
-
239
- **File: `chatbot_guide_with_images.md`**
240
-
241
- ```markdown
242
- # Hướng Dẫn Sử Dụng ChatbotRAG
243
-
244
- ## 1. Upload PDF
245
-
246
- ### Bước 1: Chuẩn bị file PDF
247
-
248
- Đảm bảo file PDF của bạn đã sẵn sàng.
249
-
250
- ![PDF File Icon](https://via.placeholder.com/150?text=PDF+File)
251
-
252
- ### Bước 2: Sử dụng cURL hoặc Python
253
-
254
- **Với cURL:**
255
-
256
- \`\`\`bash
257
- curl -X POST "http://localhost:8000/upload-pdf-multimodal" \\
258
- -F "file=@your_file.pdf"
259
- \`\`\`
260
-
261
- ![cURL Command Example](https://via.placeholder.com/400x100?text=cURL+Command)
262
-
263
- **Với Python:**
264
-
265
- \`\`\`python
266
- import requests
267
- # Upload code here
268
- \`\`\`
269
-
270
- ### Bước 3: Verify Upload
271
-
272
- Kiểm tra kết quả upload:
273
-
274
- https://via.placeholder.com/500x300?text=Upload+Success+Message
275
-
276
- ## 2. Chat Với Chatbot
277
-
278
- Sau khi upload, bạn có thể hỏi chatbot:
279
-
280
- ![Chat Interface](https://via.placeholder.com/600x400?text=Chat+Interface)
281
-
282
- **Ví dụ câu hỏi:**
283
- - "Làm sao để upload PDF?"
284
- - "Các bước tạo event là gì?"
285
-
286
- ![Chat Example](https://via.placeholder.com/600x300?text=Chat+Example)
287
-
288
- ## 3. Xem Kết Quả
289
-
290
- Chatbot sẽ trả lời dựa trên PDF content:
291
-
292
- https://via.placeholder.com/600x350?text=Chat+Response+with+Images
293
- ```
294
-
295
- **Convert to PDF:**
296
- ```bash
297
- pandoc chatbot_guide_with_images.md -o chatbot_guide_with_images.pdf
298
- ```
299
-
300
- **Upload:**
301
- ```bash
302
- curl -X POST "http://localhost:8000/upload-pdf-multimodal" \
303
- -F "file=@chatbot_guide_with_images.pdf" \
304
- -F "title=ChatbotRAG Guide" \
305
- -F "category=user_guide"
306
- ```
307
-
308
- ---
309
-
310
- ## Advanced: Custom Image Handling
311
-
312
- ### Option 1: Local Images
313
-
314
- Nếu images ở local, bạn cần host chúng:
315
-
316
- ```bash
317
- # Simple HTTP server
318
- cd /path/to/images
319
- python -m http.server 8080
320
-
321
- # Images available at:
322
- # http://localhost:8080/image1.png
323
- # http://localhost:8080/image2.png
324
- ```
325
-
326
- Trong PDF, reference:
327
- ```
328
- ![Image](http://localhost:8080/image1.png)
329
- ```
330
-
331
- ### Option 2: Cloud Storage
332
-
333
- Upload images lên cloud (AWS S3, Cloudinary, Imgur, etc.):
334
-
335
- ```python
336
- # Example: Upload to Imgur
337
- import requests
338
-
339
- def upload_to_imgur(image_path):
340
- client_id = 'YOUR_CLIENT_ID'
341
- headers = {'Authorization': f'Client-ID {client_id}'}
342
-
343
- with open(image_path, 'rb') as img:
344
- response = requests.post(
345
- 'https://api.imgur.com/3/image',
346
- headers=headers,
347
- files={'image': img}
348
- )
349
-
350
- return response.json()['data']['link']
351
-
352
- # Upload images
353
- url1 = upload_to_imgur('screenshot1.png')
354
- url2 = upload_to_imgur('screenshot2.png')
355
-
356
- # Use URLs in PDF
357
- print(f"![Screenshot 1]({url1})")
358
- ```
359
-
360
- ### Option 3: Embed Images as Base64
361
-
362
- Nếu PDF có images embedded, extract chúng:
363
-
364
- ```python
365
- import pypdfium2 as pdfium
366
- from PIL import Image
367
- import io
368
- import base64
369
-
370
- def extract_images_from_pdf(pdf_path):
371
- """Extract embedded images from PDF"""
372
- pdf = pdfium.PdfDocument(pdf_path)
373
- images = []
374
-
375
- for page_num in range(len(pdf)):
376
- page = pdf[page_num]
377
- # Render page as image
378
- bitmap = page.render(scale=2.0)
379
- pil_image = bitmap.to_pil()
380
-
381
- # Save or convert to base64
382
- buffered = io.BytesIO()
383
- pil_image.save(buffered, format="PNG")
384
- img_str = base64.b64encode(buffered.getvalue()).decode()
385
-
386
- images.append({
387
- 'page': page_num + 1,
388
- 'base64': img_str,
389
- 'url': f'data:image/png;base64,{img_str}'
390
- })
391
-
392
- return images
393
- ```
394
-
395
- ---
396
-
397
- ## Troubleshooting
398
-
399
- ### Images không được detect
400
-
401
- **Nguyên nhân:**
402
- - URLs không đúng format (thiếu http://)
403
- - URLs bị line break
404
- - Markdown syntax sai
405
-
406
- **Giải pháp:**
407
- ```python
408
- # Test URL detection
409
- from multimodal_pdf_parser import MultimodalPDFParser
410
-
411
- parser = MultimodalPDFParser()
412
- test_text = """
413
- Xem hình: https://example.com/image.png
414
- ![Alt](https://example.com/pic.jpg)
415
- """
416
-
417
- urls = parser.extract_image_urls(test_text)
418
- print("Found URLs:", urls)
419
- ```
420
-
421
- ### Chatbot không return images
422
-
423
- **Check:**
424
- 1. Verify PDF đã được index với multimodal parser:
425
- ```bash
426
- curl http://localhost:8000/documents/pdf
427
- # Look for "type": "multimodal_pdf"
428
- ```
429
-
430
- 2. Check metadata có `image_urls`:
431
- ```python
432
- response = requests.post('http://localhost:8000/chat', ...)
433
- for ctx in response.json()['context_used']:
434
- print(ctx['metadata'].get('image_urls', []))
435
- ```
436
-
437
- ### Images quá nhiều → chunks lớn
438
-
439
- **Solution:** Giảm số images mỗi chunk:
440
-
441
- ```python
442
- # In multimodal_pdf_parser.py
443
- parser = MultimodalPDFParser(
444
- chunk_size=300, # Smaller chunks
445
- chunk_overlap=30,
446
- extract_images=True
447
- )
448
- ```
449
-
450
- ---
451
-
452
- ## Kết Luận
453
-
454
- ### Khi Nào Dùng Multimodal PDF?
455
-
456
- ✓ **Sử dụng `/upload-pdf-multimodal` khi:**
457
- - PDF có hình ảnh minh họa (screenshots, diagrams)
458
- - Cần chatbot reference hình ảnh khi trả lời
459
- - User guides, tutorials với visual instructions
460
- - Documentation với charts, tables as images
461
-
462
- ✓ **Sử dụng `/upload-pdf` thường khi:**
463
- - PDF chỉ có text thuần
464
- - Không cần images trong context
465
- - Simple documents, FAQs
466
-
467
- ### Workflow Hoàn Chỉnh
468
-
469
- 1. **Tạo PDF** với text + image URLs (Markdown/HTML)
470
- 2. **Upload** qua `/upload-pdf-multimodal`
471
- 3. **Verify** images đã được detect
472
- 4. **Chat** - images sẽ tự động được include in context
473
- 5. **Display** images trong UI của bạn
474
-
475
- ---
476
-
477
- ## Example: Full Workflow
478
-
479
- ```python
480
- """
481
- Complete workflow: Create, upload, and chat with multimodal PDF
482
- """
483
- import requests
484
-
485
- # 1. Upload multimodal PDF
486
- print("=== Uploading Multimodal PDF ===")
487
- with open('user_guide_with_images.pdf', 'rb') as f:
488
- response = requests.post(
489
- 'http://localhost:8000/upload-pdf-multimodal',
490
- files={'file': f},
491
- data={'title': 'User Guide', 'category': 'guide'}
492
- )
493
-
494
- result = response.json()
495
- print(f"✓ Indexed: {result['chunks_indexed']} chunks")
496
- print(f"✓ Message: {result['message']}")
497
-
498
- # 2. Chat with multimodal context
499
- print("\n=== Chatting ===")
500
- response = requests.post('http://localhost:8000/chat', json={
501
- 'message': 'Làm sao để tạo event mới? Cho tôi xem hình minh họa.',
502
- 'use_rag': True,
503
- 'use_advanced_rag': True,
504
- 'top_k': 3,
505
- 'hf_token': 'your_token'
506
- })
507
-
508
- chat_result = response.json()
509
- print(f"Answer: {chat_result['response']}\n")
510
-
511
- # 3. Display context with images
512
- print("=== Context with Images ===")
513
- for i, ctx in enumerate(chat_result['context_used'], 1):
514
- print(f"\n[{i}] Page {ctx['metadata']['page']}, Confidence: {ctx['confidence']:.2%}")
515
- print(f"Text: {ctx['metadata']['text'][:150]}...")
516
-
517
- if ctx['metadata'].get('has_images'):
518
- print(f"Images ({ctx['metadata']['num_images']}):")
519
- for url in ctx['metadata']['image_urls']:
520
- print(f" 🖼️ {url}")
521
- ```
522
-
523
- ---
524
-
525
- **Bây giờ PDF của bạn có hình ảnh minh họa sẽ work perfectly! 🎨📄**