File size: 4,530 Bytes
a93a6b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import re
from pathlib import Path
import pdfplumber


def clean_text(text):
    """
    Clean extracted text

    Args:
        text: Raw text

    Returns:
        Cleaned text
    """
    if not text:
        return ""
    text = re.sub(r'\s+', ' ', text).strip()
    return text


def table_to_markdown(table):
    """
    Convert extracted table to Markdown format

    Args:
        table: Extracted table data

    Returns:
        Markdown formatted table
    """
    if not table or len(table) == 0:
        return ""
    md = []
    header = [str(col).strip() if col else "" for col in table[0]]
    md.append("| " + " | ".join(header) + " |")
    md.append("| " + " | ".join("---" for _ in header) + " |")
    for row in table[1:]:
        cleaned = [str(cell).strip().replace("\n", " ") if cell else "" for cell in row]
        md.append("| " + " | ".join(cleaned) + " |")
    return "\n".join(md)


def extract_and_chunk_pdf(pdf_path, output_dir="chunks"):
    """
    Extract text and tables from PDF and create semantic chunks

    Args:
        pdf_path: Path to PDF file
        output_dir: Output directory for chunks

    Returns:
        List of chunks
    """
    chunks = []
    output_path = Path(output_dir)
    output_path.mkdir(exist_ok=True)

    with pdfplumber.open(pdf_path) as pdf:
        for page_num, page in enumerate(pdf.pages, 1):
            print(f"Processing page {page_num}...")

            full_page_text = clean_text(page.extract_text() or "")

            tables = page.extract_tables()
            for idx, table in enumerate(tables):
                if table and len(table) > 1:
                    md_table = table_to_markdown(table)
                    chunk = {
                        "chunk_id": len(chunks) + 1,
                        "page": page_num,
                        "type": "table",
                        "parent_section": "Suspension System Manual",
                        "section": f"Table on Page {page_num}",
                        "content": f"Table {idx+1} - Page {page_num}\n\n{md_table}",
                        "metadata": {
                            "doc_type": "workshop_manual",
                            "topic": "suspension_diagnosis",
                            "has_table": True
                        }
                    }
                    chunks.append(chunk)

            text = page.extract_text() or ""
            if text.strip():
                section_pattern = r'(?=(Symptom Chart|Pinpoint Test|Ride Height Measurement|Inspection and Verification|Visual Inspection Chart|Ball Joint Inspection|Camber and Caster Adjustment|Component Tests))'
                sections = re.split(section_pattern, text, flags=re.IGNORECASE)

                current_parent = "General"
                for i, section in enumerate(sections):
                    if not section.strip():
                        continue
                    cleaned = clean_text(section)
                    if len(cleaned) < 50:
                        continue

                    if re.match(section_pattern, section):
                        current_parent = section.strip()[:100]

                    chunk = {
                        "chunk_id": len(chunks) + 1,
                        "page": page_num,
                        "type": "text",
                        "parent_section": current_parent,
                        "section": current_parent,
                        "content": cleaned,
                        "metadata": {
                            "doc_type": "workshop_manual",
                            "topic": "suspension_diagnosis",
                            "has_table": False
                        }
                    }
                    chunks.append(chunk)

    json_path = output_path / "suspension_chunks.json"
    with open(json_path, 'w', encoding='utf-8') as f:
        json.dump(chunks, f, indent=2, ensure_ascii=False)

    for chunk in chunks:
        md_content = f"""# {chunk['section']}
Page: {chunk['page']} | Type: {chunk['type']} | Parent: {chunk['parent_section']}

{chunk['content']}

---
"""
        md_path = output_path / f"chunk_{chunk['chunk_id']:03d}_p{chunk['page']}_{chunk['type']}.md"
        with open(md_path, 'w', encoding='utf-8') as f:
            f.write(md_content)

    print(f"Advanced Chunking Complete!")
    print(f"Total Chunks: {len(chunks)}")
    print(f"Saved to: {output_path.resolve()}")
    print(f"JSON: suspension_chunks.json (with metadata)")

    return chunks