-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconverter.py
More file actions
1333 lines (1097 loc) · 49.2 KB
/
converter.py
File metadata and controls
1333 lines (1097 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import logging
from pathlib import Path
from typing import Callable, Dict
import pandas as pd
import numpy as np
from pdf2docx import Converter
from docx import Document
from openpyxl import load_workbook, Workbook
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import markdown
import csv
import tempfile
import fitz
from PyPDF2 import PdfReader
import html
from pptx import Presentation
from docx2pdf import convert
import mammoth
import html2text
import pdfplumber
# ver 13.01 -> nâng cấp chuyển đổi từ pdf->docx
import io
import re
import pytesseract
import shutil
import subprocess
from PIL import Image
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
import html
import statistics
# Thiết lập logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
def chuyen_doi_an_toan(func: Callable) -> Callable:
"""Decorator để xử lý ngoại lệ trong các hàm chuyển đổi."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logging.error(f"Lỗi trong {func.__name__}: {str(e)}")
return None
return wrapper
@chuyen_doi_an_toan
def chuyen_doi_pdf_sang_docx(duong_dan_pdf: str) -> str: # đã được nâng cấp 25/03
"""
Chuyển đổi PDF sang DOCX với khả năng bảo toàn công thức toán học và hình ảnh
sử dụng phương pháp hoàn toàn miễn phí.
Args:
duong_dan_pdf: Đường dẫn đến tệp PDF
Returns:
Đường dẫn đến tệp DOCX đã tạo
"""
duong_dan_docx = Path(duong_dan_pdf).with_suffix(".docx")
# Kiểm tra xem LibreOffice có sẵn không (phương pháp tốt nhất)
if has_libreoffice():
try:
logging.info("Đang thử chuyển đổi bằng LibreOffice...")
result = convert_with_libreoffice(duong_dan_pdf, duong_dan_docx)
if result:
logging.info(
f"Đã chuyển đổi thành công bằng LibreOffice: {duong_dan_docx}"
)
return str(duong_dan_docx)
except Exception as e:
logging.error(f"Lỗi khi sử dụng LibreOffice: {str(e)}")
# Phương pháp 2: Sử dụng phương pháp hình ảnh + văn bản
try:
# Tạo document mới
doc = Document()
# Thiết lập font và kích thước mặc định
style = doc.styles["Normal"]
style.font.name = "Times New Roman"
style.font.size = Pt(12)
# Mở PDF bằng PyMuPDF
pdf_doc = fitz.open(duong_dan_pdf)
total_pages = len(pdf_doc)
# Tạo thư mục tạm
with tempfile.TemporaryDirectory() as temp_dir:
logging.info(f"Đang xử lý PDF có {total_pages} trang...")
for page_num, page in enumerate(pdf_doc):
logging.info(f"Đang xử lý trang {page_num + 1}/{total_pages}")
# Thêm tiêu đề trang
heading = doc.add_heading(f"Trang {page_num + 1}", level=1)
heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Phân tích trang để tìm các vùng văn bản và công thức
blocks = page.get_text("dict")["blocks"]
# Trích xuất toàn bộ trang dưới dạng hình ảnh với độ phân giải cao
page_img = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72))
page_img_path = os.path.join(temp_dir, f"page_{page_num + 1}.png")
page_img.save(page_img_path)
# Phân tích các khối để xác định văn bản thông thường và công thức
for block_idx, block in enumerate(blocks):
if block["type"] == 0: # Khối văn bản
block_text = ""
for line in block["lines"]:
line_text = ""
for span in line["spans"]:
line_text += span["text"] + " "
block_text += line_text.strip() + "\n"
# Kiểm tra xem có phải công thức không
if is_likely_formula(block_text):
# Trích xuất công thức dưới dạng hình ảnh
formula_rect = fitz.Rect(block["bbox"])
formula_img = page.get_pixmap(
clip=formula_rect, matrix=fitz.Matrix(3, 3)
)
formula_img_path = os.path.join(
temp_dir, f"page_{page_num + 1}_formula_{block_idx}.png"
)
formula_img.save(formula_img_path)
# Thêm hình ảnh công thức vào tài liệu
para = doc.add_paragraph()
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = para.add_run()
run.add_picture(formula_img_path, width=None, height=None)
else:
# Thêm văn bản thông thường
if block_text.strip():
para = doc.add_paragraph(block_text.strip())
elif block["type"] == 1: # Khối hình ảnh
# Trích xuất hình ảnh từ trang
img_rect = fitz.Rect(block["bbox"])
img = page.get_pixmap(clip=img_rect, matrix=fitz.Matrix(2, 2))
img_path = os.path.join(
temp_dir, f"page_{page_num + 1}_block_img_{block_idx}.png"
)
img.save(img_path)
# Thêm hình ảnh vào tài liệu
para = doc.add_paragraph()
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = para.add_run()
run.add_picture(img_path, width=None, height=None)
# Trích xuất các hình ảnh nhúng
image_list = page.get_images(full=True)
for img_idx, img_info in enumerate(image_list):
xref = img_info[0]
base_image = pdf_doc.extract_image(xref)
image_bytes = base_image["image"]
# Lưu hình ảnh
img_filename = os.path.join(
temp_dir, f"page_{page_num + 1}_img_{img_idx}.png"
)
with open(img_filename, "wb") as img_file:
img_file.write(image_bytes)
# Kiểm tra kích thước hình ảnh
try:
pil_img = Image.open(img_filename)
if (
pil_img.width > 50 and pil_img.height > 50
): # Bỏ qua hình ảnh quá nhỏ
para = doc.add_paragraph()
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = para.add_run()
run.add_picture(img_filename, width=None, height=None)
except Exception as img_err:
logging.warning(f"Không thể xử lý hình ảnh: {str(img_err)}")
# Thêm ngắt trang sau mỗi trang PDF
if page_num < total_pages - 1:
doc.add_page_break()
# Lưu tài liệu
doc.save(duong_dan_docx)
logging.info(f"Đã lưu tài liệu DOCX: {duong_dan_docx}")
return str(duong_dan_docx)
except Exception as e:
logging.error(f"Lỗi khi chuyển đổi PDF sang DOCX: {str(e)}")
# Phương pháp dự phòng: Chuyển toàn bộ trang thành hình ảnh
try:
logging.info("Đang thử phương pháp dự phòng...")
# Tạo document mới
doc = Document()
# Mở PDF bằng PyMuPDF
pdf_doc = fitz.open(duong_dan_pdf)
for page_num, page in enumerate(pdf_doc):
# Thêm tiêu đề trang
heading = doc.add_heading(f"Trang {page_num + 1}", level=1)
heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Chuyển trang thành hình ảnh với độ phân giải cao
pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72))
img_bytes = pix.tobytes("png")
# Thêm hình ảnh trang vào tài liệu
para = doc.add_paragraph()
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = para.add_run()
run.add_picture(io.BytesIO(img_bytes), width=Inches(6))
# Thêm ngắt trang
if page_num < len(pdf_doc) - 1:
doc.add_page_break()
# Lưu tài liệu
doc.save(duong_dan_docx)
logging.info(
f"Đã lưu tài liệu DOCX (phương pháp dự phòng): {duong_dan_docx}"
)
return str(duong_dan_docx)
except Exception as e2:
logging.error(f"Phương pháp dự phòng cũng thất bại: {str(e2)}")
return None
def is_likely_formula(text): # đã được nâng cấp 25/03
"""Kiểm tra xem một đoạn văn bản có khả năng là công thức toán học không."""
# Các mẫu regex để nhận dạng công thức toán học
math_patterns = [
r"[=+\-*/^]", # Các toán tử cơ bản
r"\\[a-zA-Z]+", # Lệnh LaTeX
r"[α-ωΑ-Ω]", # Ký tự Hy Lạp
r"[∫∑∏√∂∇∆]", # Ký hiệu toán học
r"\$.*?\$", # Công thức LaTeX
r"$$\d+$$", # Tham chiếu phương trình
r"_{.*?}", # Chỉ số dưới
r"\^{.*?}", # Chỉ số trên
]
# Kiểm tra các mẫu công thức
for pattern in math_patterns:
if re.search(pattern, text) and not pattern == r"[=+\-*/^]":
return True
elif pattern == r"[=+\-*/^]" and len(re.findall(pattern, text)) > 3:
return True
# Kiểm tra tỷ lệ ký tự đặc biệt
special_chars = sum(1 for c in text if c in "=+-*/^()[]{}\\<>~_|")
if len(text) > 0 and special_chars / len(text) > 0.15:
return True
return False
def has_libreoffice(): # đã được nâng cấp 25/03 - cần cài sẵn libreoffice
"""Kiểm tra xem LibreOffice có được cài đặt không."""
try:
# Kiểm tra lệnh soffice (LibreOffice)
subprocess.run(["soffice", "--version"], capture_output=True, check=False)
return True
except (FileNotFoundError, subprocess.SubprocessError):
# Kiểm tra lệnh libreoffice
try:
subprocess.run(
["libreoffice", "--version"], capture_output=True, check=False
)
return True
except (FileNotFoundError, subprocess.SubprocessError):
return False
def convert_with_libreoffice(input_path, output_path): # đã được nâng cấp 25/03
"""Sử dụng LibreOffice để chuyển đổi PDF sang DOCX."""
try:
# Tạo thư mục tạm
with tempfile.TemporaryDirectory() as temp_dir:
# Xác định lệnh LibreOffice
libreoffice_cmd = "soffice"
try:
subprocess.run(
[libreoffice_cmd, "--version"], capture_output=True, check=False
)
except (FileNotFoundError, subprocess.SubprocessError):
libreoffice_cmd = "libreoffice"
# Lệnh chuyển đổi
cmd = [
libreoffice_cmd,
"--headless",
"--convert-to",
"docx",
"--outdir",
temp_dir,
str(input_path),
]
# Thực thi lệnh
process = subprocess.run(cmd, capture_output=True, text=True, check=False)
if process.returncode == 0:
# Tìm tệp đầu ra
output_filename = Path(input_path).stem + ".docx"
temp_output_path = os.path.join(temp_dir, output_filename)
if os.path.exists(temp_output_path):
# Sao chép tệp kết quả
shutil.copy2(temp_output_path, output_path)
return True
logging.error(f"LibreOffice không thành công: {process.stderr}")
return False
except Exception as e:
logging.error(f"Lỗi khi sử dụng LibreOffice: {str(e)}")
return False
def check_for_math_formulas(pdf_path): # đã được nâng cấp 25/03
"""Kiểm tra xem PDF có chứa công thức toán học không."""
try:
# Mở PDF bằng PyMuPDF
doc = fitz.open(pdf_path)
# Các mẫu regex để nhận dạng công thức toán học
math_patterns = [
r"[=+\-*/^]", # Các toán tử cơ bản
r"\\[a-zA-Z]+", # Lệnh LaTeX
r"[α-ωΑ-Ω]", # Ký tự Hy Lạp
r"[∫∑∏√∂∇∆]", # Ký hiệu toán học
r"\$.*?\$", # Công thức LaTeX
r"$$\d+$$", # Tham chiếu phương trình
r"_{.*?}", # Chỉ số dưới
r"\^{.*?}", # Chỉ số trên
]
# Kiểm tra một số trang đầu tiên
pages_to_check = min(5, len(doc))
for page_num in range(pages_to_check):
page = doc[page_num]
text = page.get_text()
# Kiểm tra các mẫu công thức
for pattern in math_patterns:
if re.search(pattern, text) and not pattern == r"[=+\-*/^]":
return True
elif pattern == r"[=+\-*/^]" and len(re.findall(pattern, text)) > 10:
return True
return False
except Exception as e:
logging.warning(f"Không thể kiểm tra công thức toán học: {str(e)}")
return False
def is_likely_formula(text): # đã được nâng cấp 25/03
"""Kiểm tra xem một đoạn văn bản có khả năng là công thức toán học không."""
# Các mẫu regex để nhận dạng công thức toán học
math_patterns = [
r"[=+\-*/^]", # Các toán tử cơ bản
r"\\[a-zA-Z]+", # Lệnh LaTeX
r"[α-ωΑ-Ω]", # Ký tự Hy Lạp
r"[∫∑∏√∂∇∆]", # Ký hiệu toán học
r"\$.*?\$", # Công thức LaTeX
r"$$\d+$$", # Tham chiếu phương trình
r"_{.*?}", # Chỉ số dưới
r"\^{.*?}", # Chỉ số trên
]
# Kiểm tra các mẫu công thức
for pattern in math_patterns:
if re.search(pattern, text) and not pattern == r"[=+\-*/^]":
return True
elif pattern == r"[=+\-*/^]" and len(re.findall(pattern, text)) > 3:
return True
# Kiểm tra tỷ lệ ký tự đặc biệt
special_chars = sum(1 for c in text if c in "=+-*/^()[]{}\\<>~_|")
if len(text) > 0 and special_chars / len(text) > 0.2:
return True
return False
def verify_conversion_quality(pdf_path, docx_path): # đã được nâng cấp 25/03
"""Kiểm tra chất lượng chuyển đổi bằng cách so sánh số lượng văn bản."""
try:
# Đọc văn bản từ PDF
pdf_doc = fitz.open(pdf_path)
pdf_text = ""
for page in pdf_doc:
pdf_text += page.get_text()
# Đọc văn bản từ DOCX
doc = Document(docx_path)
docx_text = ""
for para in doc.paragraphs:
docx_text += para.text + "\n"
# So sánh độ dài văn bản (loại bỏ khoảng trắng)
pdf_text_len = len(re.sub(r"\s+", "", pdf_text))
docx_text_len = len(re.sub(r"\s+", "", docx_text))
# Nếu DOCX chứa ít nhất 70% văn bản từ PDF, coi là chất lượng tốt
if pdf_text_len > 0 and docx_text_len / pdf_text_len >= 0.7:
return True
return False
except Exception as e:
logging.warning(f"Không thể kiểm tra chất lượng chuyển đổi: {str(e)}")
return True # Mặc định là chấp nhận
def has_libreoffice(): # đã được nâng cấp 25/03
"""Kiểm tra xem LibreOffice có được cài đặt không."""
try:
subprocess.run(["soffice", "--version"], capture_output=True)
return True
except (FileNotFoundError, subprocess.SubprocessError):
return False
def chuyen_doi_pdf_sang_html(duong_dan_pdf: str) -> str:
"""
Chuyển đổi PDF sang HTML với khả năng bảo toàn định dạng, hình ảnh và công thức toán học,
đồng thời đảm bảo kích thước chữ và định dạng đồng nhất giữa các trang.
Args:
duong_dan_pdf: Đường dẫn đến tệp PDF
Returns:
Đường dẫn đến tệp HTML đã tạo
"""
duong_dan_html = Path(duong_dan_pdf).with_suffix(".html")
try:
# Mở PDF bằng PyMuPDF
pdf_doc = fitz.open(duong_dan_pdf)
total_pages = len(pdf_doc)
# Phân tích sơ bộ để xác định kích thước chữ phổ biến nhất
font_sizes = []
for page in pdf_doc:
blocks = page.get_text("dict")["blocks"]
for block in blocks:
if block["type"] == 0: # Khối văn bản
for line in block["lines"]:
for span in line["spans"]:
if "size" in span:
font_sizes.append(span["size"])
# Xác định kích thước chữ phổ biến nhất
default_font_size = 12 # Mặc định
if font_sizes:
# Sử dụng mode (giá trị xuất hiện nhiều nhất) hoặc median
try:
default_font_size = statistics.mode(font_sizes)
except statistics.StatisticsError:
default_font_size = statistics.median(font_sizes)
logging.info(f"Kích thước chữ phổ biến nhất: {default_font_size}pt")
# Tạo thư mục tạm và thư mục cho hình ảnh
with tempfile.TemporaryDirectory() as temp_dir:
# Tạo thư mục cho hình ảnh
images_dir = os.path.join(os.path.dirname(duong_dan_html), "images")
os.makedirs(images_dir, exist_ok=True)
logging.info(f"Đang xử lý PDF có {total_pages} trang...")
# Bắt đầu tạo HTML
html_content = f"""<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{Path(duong_dan_pdf).stem}</title>
<style>
body {{
font-family: 'Times New Roman', serif;
line-height: 1.6;
margin: 20px;
color: #333;
font-size: {default_font_size}px;
}}
.page {{
border: 1px solid #ddd;
margin-bottom: 30px;
padding: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
background-color: white;
max-width: 800px;
margin-left: auto;
margin-right: auto;
}}
.page-title {{
text-align: center;
font-weight: bold;
margin-bottom: 20px;
color: #444;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
font-size: {default_font_size * 1.5}px;
}}
.formula {{
text-align: center;
margin: 15px 0;
}}
.image {{
text-align: center;
margin: 15px 0;
}}
img {{
max-width: 100%;
height: auto;
}}
.text-block {{
margin-bottom: 15px;
text-align: justify;
font-size: {default_font_size}px;
}}
.heading {{
font-weight: bold;
font-size: {default_font_size * 1.2}px;
margin-top: 20px;
margin-bottom: 10px;
}}
.math-formula {{
font-style: italic;
background-color: #f9f9f9;
padding: 5px;
border-radius: 3px;
}}
/* Thêm nút chuyển đổi chế độ xem */
.view-toggle {{
position: fixed;
top: 10px;
right: 10px;
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
z-index: 1000;
}}
/* Chế độ xem hình ảnh trang */
.page-image-view {{
display: none;
}}
/* Chế độ xem văn bản */
.text-view {{
display: block;
}}
</style>
</head>
<body>
<button id="viewToggle" class="view-toggle">Chuyển chế độ xem</button>
"""
# Xử lý từng trang
for page_num, page in enumerate(pdf_doc):
logging.info(f"Đang xử lý trang {page_num + 1}/{total_pages}")
# Thêm tiêu đề trang
html_content += f'<div class="page" id="page-{page_num + 1}">\n'
html_content += f'<h1 class="page-title">Trang {page_num + 1}</h1>\n'
# Trích xuất toàn bộ trang dưới dạng hình ảnh với độ phân giải cao
page_img = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72))
page_img_filename = f"page_{page_num + 1}.png"
page_img_path = os.path.join(images_dir, page_img_filename)
page_img.save(page_img_path)
# Thêm hình ảnh trang đầy đủ (cho chế độ xem hình ảnh)
html_content += f'<div class="page-image-view">\n'
html_content += f'<img src="images/{page_img_filename}" alt="Trang {page_num + 1}" />\n'
html_content += f"</div>\n"
# Thêm phần văn bản (cho chế độ xem văn bản)
html_content += f'<div class="text-view">\n'
# Phân tích các khối văn bản và hình ảnh
blocks = page.get_text("dict")["blocks"]
for block_idx, block in enumerate(blocks):
if block["type"] == 0: # Khối văn bản
block_text = ""
block_is_heading = False
block_font_size = default_font_size
block_is_bold = False
# Phân tích thuộc tính của khối văn bản
for line in block["lines"]:
line_text = ""
for span in line["spans"]:
line_text += span["text"] + " "
# Kiểm tra xem có phải tiêu đề không
if (
"size" in span
and span["size"] > default_font_size * 1.2
):
block_is_heading = True
block_font_size = span["size"]
# Kiểm tra độ đậm
if (
"flags" in span and span["flags"] & 2
): # 2 là mã cho bold
block_is_bold = True
block_text += line_text.strip() + "\n"
# Kiểm tra xem có phải công thức không
if is_likely_formula(block_text):
# Trích xuất công thức dưới dạng hình ảnh
formula_rect = fitz.Rect(block["bbox"])
formula_img = page.get_pixmap(
clip=formula_rect, matrix=fitz.Matrix(3, 3)
)
formula_img_filename = (
f"page_{page_num + 1}_formula_{block_idx}.png"
)
formula_img_path = os.path.join(
images_dir, formula_img_filename
)
formula_img.save(formula_img_path)
# Thêm hình ảnh công thức vào HTML
html_content += f'<div class="formula">\n'
html_content += f'<img src="images/{formula_img_filename}" alt="Công thức" />\n'
html_content += f"</div>\n"
else:
# Thêm văn bản thông thường với định dạng phù hợp
if block_text.strip():
# Escape HTML characters
safe_text = html.escape(block_text.strip())
# Replace newlines with <br>
safe_text = safe_text.replace("\n", "<br>\n")
if block_is_heading:
# Tính toán kích thước chữ tương đối
relative_size = block_font_size / default_font_size
font_size = default_font_size * min(
relative_size, 2
) # Giới hạn kích thước tối đa
html_content += f'<div class="heading" style="font-size: {font_size}px;">{safe_text}</div>\n'
else:
# Thêm văn bản thông thường
style_attr = ""
if block_is_bold:
style_attr = ' style="font-weight: bold;"'
html_content += f'<div class="text-block"{style_attr}>{safe_text}</div>\n'
elif block["type"] == 1: # Khối hình ảnh
# Trích xuất hình ảnh từ trang
img_rect = fitz.Rect(block["bbox"])
img = page.get_pixmap(clip=img_rect, matrix=fitz.Matrix(2, 2))
img_filename = f"page_{page_num + 1}_block_img_{block_idx}.png"
img_path = os.path.join(images_dir, img_filename)
img.save(img_path)
# Thêm hình ảnh vào HTML
html_content += f'<div class="image">\n'
html_content += (
f'<img src="images/{img_filename}" alt="Hình ảnh" />\n'
)
html_content += f"</div>\n"
# Trích xuất các hình ảnh nhúng
image_list = page.get_images(full=True)
for img_idx, img_info in enumerate(image_list):
xref = img_info[0]
base_image = pdf_doc.extract_image(xref)
image_bytes = base_image["image"]
# Lưu hình ảnh
img_filename = f"page_{page_num + 1}_img_{img_idx}.png"
img_path = os.path.join(images_dir, img_filename)
with open(img_path, "wb") as img_file:
img_file.write(image_bytes)
# Kiểm tra kích thước hình ảnh
try:
pil_img = Image.open(img_path)
if (
pil_img.width > 50 and pil_img.height > 50
): # Bỏ qua hình ảnh quá nhỏ
html_content += f'<div class="image">\n'
html_content += f'<img src="images/{img_filename}" alt="Hình ảnh nhúng" />\n'
html_content += f"</div>\n"
except Exception as img_err:
logging.warning(f"Không thể xử lý hình ảnh: {str(img_err)}")
# Kết thúc phần văn bản
html_content += "</div>\n"
# Kết thúc trang
html_content += "</div>\n"
# Thêm JavaScript để chuyển đổi chế độ xem
html_content += """
<script>
document.addEventListener('DOMContentLoaded', function() {
const viewToggle = document.getElementById('viewToggle');
const textViews = document.querySelectorAll('.text-view');
const imageViews = document.querySelectorAll('.page-image-view');
let showingText = true;
viewToggle.addEventListener('click', function() {
if (showingText) {
// Chuyển sang chế độ xem hình ảnh
textViews.forEach(view => view.style.display = 'none');
imageViews.forEach(view => view.style.display = 'block');
viewToggle.textContent = 'Xem văn bản';
} else {
// Chuyển sang chế độ xem văn bản
textViews.forEach(view => view.style.display = 'block');
imageViews.forEach(view => view.style.display = 'none');
viewToggle.textContent = 'Xem hình ảnh';
}
showingText = !showingText;
});
});
</script>
</body>
</html>
"""
# Lưu tệp HTML
with open(duong_dan_html, "w", encoding="utf-8") as f:
f.write(html_content)
logging.info(f"Đã lưu tài liệu HTML: {duong_dan_html}")
return str(duong_dan_html)
except Exception as e:
logging.error(f"Lỗi khi chuyển đổi PDF sang HTML: {str(e)}")
# Phương pháp dự phòng: Chuyển toàn bộ trang thành hình ảnh
try:
logging.info("Đang thử phương pháp dự phòng...")
# Tạo thư mục cho hình ảnh
images_dir = os.path.join(os.path.dirname(duong_dan_html), "images")
os.makedirs(images_dir, exist_ok=True)
# Mở PDF bằng PyMuPDF
pdf_doc = fitz.open(duong_dan_pdf)
# Bắt đầu tạo HTML
html_content = f"""<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{Path(duong_dan_pdf).stem}</title>
<style>
body {{
font-family: 'Times New Roman', serif;
line-height: 1.6;
margin: 20px;
color: #333;
}}
.page {{
border: 1px solid #ddd;
margin-bottom: 30px;
padding: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
background-color: white;
text-align: center;
max-width: 800px;
margin-left: auto;
margin-right: auto;
}}
.page-title {{
text-align: center;
font-weight: bold;
margin-bottom: 20px;
color: #444;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}}
img {{
max-width: 100%;
height: auto;
}}
</style>
</head>
<body>
"""
# Xử lý từng trang
for page_num, page in enumerate(pdf_doc):
# Thêm tiêu đề trang
html_content += f'<div class="page">\n'
html_content += f'<h1 class="page-title">Trang {page_num + 1}</h1>\n'
# Chuyển trang thành hình ảnh với độ phân giải cao
pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72))
img_filename = f"page_{page_num + 1}.png"
img_path = os.path.join(images_dir, img_filename)
pix.save(img_path)
# Thêm hình ảnh trang vào HTML
html_content += (
f'<img src="images/{img_filename}" alt="Trang {page_num + 1}" />\n'
)
# Kết thúc trang
html_content += "</div>\n"
# Kết thúc HTML
html_content += """
</body>
</html>
"""
# Lưu tệp HTML
with open(duong_dan_html, "w", encoding="utf-8") as f:
f.write(html_content)
logging.info(
f"Đã lưu tài liệu HTML (phương pháp dự phòng): {duong_dan_html}"
)
return str(duong_dan_html)
except Exception as e2:
logging.error(f"Phương pháp dự phòng cũng thất bại: {str(e2)}")
return None
def is_likely_formula(text):
"""Kiểm tra xem một đoạn văn bản có khả năng là công thức toán học không."""
# Các mẫu regex để nhận dạng công thức toán học
math_patterns = [
r"[=+\-*/^]", # Các toán tử cơ bản
r"\\[a-zA-Z]+", # Lệnh LaTeX
r"[α-ωΑ-Ω]", # Ký tự Hy Lạp
r"[∫∑∏√∂∇∆]", # Ký hiệu toán học
r"\$.*?\$", # Công thức LaTeX
r"$$\d+$$", # Tham chiếu phương trình
r"_{.*?}", # Chỉ số dưới
r"\^{.*?}", # Chỉ số trên
]
# Kiểm tra các mẫu công thức
for pattern in math_patterns:
if re.search(pattern, text) and not pattern == r"[=+\-*/^]":
return True
elif pattern == r"[=+\-*/^]" and len(re.findall(pattern, text)) > 3:
return True
# Kiểm tra tỷ lệ ký tự đặc biệt
special_chars = sum(1 for c in text if c in "=+-*/^()[]{}\\<>~_|")
if len(text) > 0 and special_chars / len(text) > 0.15:
return True
return False
# chuyển đổi từ pdf-docx vừa được cải tiến, ver13.01 - 25/03
@chuyen_doi_an_toan
def chuyen_doi_pdf_sang_xlsx(duong_dan_pdf: str) -> str:
"""
Chuyển đổi PDF sang XLSX với khả năng phát hiện và trích xuất bảng.
Args:
duong_dan_pdf: Đường dẫn đến tệp PDF
Returns:
Đường dẫn đến tệp XLSX đã tạo
"""
duong_dan_xlsx = Path(duong_dan_pdf).with_suffix(".xlsx")
try:
with pdfplumber.open(duong_dan_pdf) as pdf:
with pd.ExcelWriter(duong_dan_xlsx, engine="openpyxl") as writer:
for i, page in enumerate(pdf.pages):
tables = page.extract_tables()
if tables:
for j, table in enumerate(tables):
df = pd.DataFrame(
table[1:], columns=table[0] if table else None
)
sheet_name = f"Trang_{i+1}_Bảng_{j+1}"
df.to_excel(writer, sheet_name=sheet_name, index=False)
logging.info(f"Đã trích xuất bảng {j+1} từ trang {i+1}")
else:
text = page.extract_text()
if text:
lines = [
line.split()
for line in text.split("\n")
if line.strip()
]
df = pd.DataFrame(lines)
sheet_name = f"Trang_{i+1}_Văn_bản"
df.to_excel(
writer, sheet_name=sheet_name, index=False, header=False
)
logging.info(
f"Đã chuyển đổi thành công '{duong_dan_pdf}' sang '{duong_dan_xlsx}'"
)
return str(duong_dan_xlsx)
except Exception as e:
logging.error(f"Lỗi khi chuyển đổi PDF sang XLSX: {str(e)}")
return None
@chuyen_doi_an_toan
def chuyen_doi_docx_sang_pdf(duong_dan_docx: str) -> str:
duong_dan_pdf = Path(duong_dan_docx).with_suffix(".pdf")
convert(duong_dan_docx, str(duong_dan_pdf))
return str(duong_dan_pdf)
@chuyen_doi_an_toan
def chuyen_doi_xlsx_sang_docx(duong_dan_xlsx: str) -> str:
duong_dan_docx = Path(duong_dan_xlsx).with_suffix(".docx")
df = pd.read_excel(duong_dan_xlsx)
doc = Document()
for column in df.columns:
doc.add_heading(column, level=1)
for value in df[column]:
doc.add_paragraph(str(value))
doc.add_paragraph() # Thêm một dòng trống giữa các cột
doc.save(duong_dan_docx)
return str(duong_dan_docx)
@chuyen_doi_an_toan
def chuyen_doi_docx_sang_xlsx(duong_dan_docx: str) -> str:
duong_dan_xlsx = Path(duong_dan_docx).with_suffix(".xlsx")
doc = Document(duong_dan_docx)
data = []
for paragraph in doc.paragraphs:
data.append([paragraph.text])
df = pd.DataFrame(data)
df.to_excel(duong_dan_xlsx, index=False, header=False)
return str(duong_dan_xlsx)
@chuyen_doi_an_toan
def chuyen_doi_xlsx_sang_pdf(duong_dan_xlsx: str) -> str:
duong_dan_pdf = Path(duong_dan_xlsx).with_suffix(".pdf")
df = pd.read_excel(duong_dan_xlsx)
pdf = canvas.Canvas(str(duong_dan_pdf), pagesize=letter)
y = 750 # Tọa độ y bắt đầu
for column in df.columns:
pdf.drawString(100, y, column)
y -= 20
for value in df[column]:
pdf.drawString(120, y, str(value))
y -= 15
if y < 50: # Bắt đầu trang mới nếu gần đến cuối trang
pdf.showPage()
y = 750
pdf.save()
return str(duong_dan_pdf)
@chuyen_doi_an_toan
def chuyen_doi_xlsx_sang_csv(duong_dan_xlsx: str) -> str: