import pdfplumber
import re
import json
import os
files = [
'/home/x79/sisvietnamvn_01/sisvietnamvn_Trang chính thức hiện tại/DaoTao/2.-CHUONG-TRINH-CAN-THIEP-MACH-MAU-THAN-KINH-NANG-CAO-BO-SUNG-FINAL.pdf',
'/home/x79/sisvietnamvn_01/sisvietnamvn_Trang chính thức hiện tại/DaoTao/CHUONG-TRINH-CAN-THIEP-MACH-MAU-CAC-TANG-VA-MACH-MAU-NGOAI-BIEN-CO-BAN.pdf',
'/home/x79/sisvietnamvn_01/sisvietnamvn_Trang chính thức hiện tại/DaoTao/CHUONG-TRINH-CHUAN-BI-DUNG-CU-VA-CHAM-SOC-BENH-NHAN-TRONG-PHONG-CHUP-MACH.pdf',
'/home/x79/sisvietnamvn_01/sisvietnamvn_Trang chính thức hiện tại/DaoTao/CHUONG-TRINH-DAO-TAO-TIM-MACH-CAN-THIEP-1.pdf'
]
slugs = [
"can-thiep-mach-mau-than-kinh-nang-cao",
"can-thiep-mach-mau-cac-tang-va-ngoai-bien-co-ban",
"chuan-bi-dung-cu-va-cham-soc-benh-nhan-trong-phong-chup-mach",
"tim-mach-can-thiep-co-ban"
]
def extract_section(text, start_keywords, end_keywords=None):
lines = text.split('\n')
started = False
content = []
for line in lines:
line_lower = line.lower()
if not started:
for k in start_keywords:
if k in line_lower:
started = True
split_idx = line_lower.find(k) + len(k)
val = line[split_idx:].strip(': ').strip()
if val:
content.append(val)
break
else:
if end_keywords:
for k in end_keywords:
if k in line_lower:
return '\n'.join(content).strip()
# Stop if we hit a new numbered section like "10." or empty lines after some text
if re.match(r'^\d+\.', line) or re.match(r'^[A-Z\s]+$', line):
return '\n'.join(content).strip()
if line.strip():
content.append(line.strip())
return '\n'.join(content).strip()
def make_text_block(text):
return {
"type": "paragraph",
"data": {
"text": text.replace('\n', '
')
}
}
def make_header_block(text, level=3):
return {
"type": "header",
"data": {
"text": text,
"level": level
}
}
os.makedirs('pdf_json_output', exist_ok=True)
for f, slug in zip(files, slugs):
print(f"--- Rebuilding {slug} ---")
blocks = []
with pdfplumber.open(f) as pdf:
text = ''
pdf_blocks = []
for page in pdf.pages:
page_text = page.extract_text()
if not page_text:
continue
text += page_text + '\n'
# Simple heuristic: split by double newlines or single newlines
paragraphs = page_text.split('\n')
current_p = []
for line in paragraphs:
line = line.strip()
if not line:
continue
if re.match(r'^(\d+)\.\s+(.*)$', line) or line.isupper():
if current_p:
pdf_blocks.append(make_text_block(' '.join(current_p)))
current_p = []
pdf_blocks.append(make_header_block(line, level=3))
else:
current_p.append(line)
if current_p:
pdf_blocks.append(make_text_block(' '.join(current_p)))
# Try to extract tables
tables = page.extract_tables()
for table in tables:
if not table: continue
html = "
| {cell_text} | " html += "