File size: 6,252 Bytes
5ea2bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Pdf-Data 1.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1IB0DbFJbA27C0womZkoMQZ7oIkgJkHYU

# Install & import libs
"""

!pip install pypdf pandas tqdm

!apt-get install -y tesseract-ocr
!pip install pytesseract pdf2image pypdf pandas tqdm pillow
!apt-get install -y tesseract-ocr-ara

!apt-get install -y poppler-utils

import os
import pandas as pd
from pypdf import PdfReader
from tqdm import tqdm

"""# Mount Google Drive"""

from google.colab import drive
drive.mount('/content/drive')

"""# Config paths"""

BASE_FOLDER = "/content/drive/MyDrive/OitLab/Text"
OUTPUT_CSV = "/content/drive/MyDrive/OitLab/Text/pdf_dataset1.csv"

"""# Core extraction logic"""

# import os
# from pypdf import PdfReader
# from pdf2image import convert_from_path
# import pytesseract
# from tqdm.notebook import tqdm
# import re

# rows = []

# def clean_text(text):
#     text = re.sub(r'\s+', ' ', text)
#     return text.strip()

# for category in os.listdir(BASE_FOLDER):
#     category_path = os.path.join(BASE_FOLDER, category)

#     if not os.path.isdir(category_path):
#         continue

#     print(f"\nProcessing category: {category}")

#     files = [f for f in os.listdir(category_path) if f.lower().endswith(".pdf")]

#     for file in tqdm(files, desc="PDF files"):
#         pdf_path = os.path.join(category_path, file)

#         try:
#             reader = PdfReader(pdf_path)
#             total_pages = len(reader.pages)

#             for page_num, page in enumerate(
#                 tqdm(reader.pages, desc=f"{file}", total=total_pages, leave=False)
#             ):
#                 text = page.extract_text()
#                 text = "" if text is None else clean_text(text)

#                 # --------- OCR FALLBACK ----------
#                 if len(text) < 30:
#                     images = convert_from_path(
#                         pdf_path,
#                         first_page=page_num + 1,
#                         last_page=page_num + 1
#                     )
#                     ocr_text = pytesseract.image_to_string(
#                         images[0],
#                         lang="ara+eng"
#                     )
#                     text = clean_text(ocr_text)

#                 rows.append({
#                     "name": file,
#                     "page": page_num + 1,
#                     "content": text,
#                     "category": category,
#                     "char": len(text)
#                 })

#         except Exception as e:
#             print(f"Error with {pdf_path}: {e}")

import os
import pandas as pd
from pypdf import PdfReader
from pdf2image import convert_from_path
import pytesseract
from tqdm import tqdm
import re
from multiprocessing import Pool, cpu_count
from functools import partial

# ---------------- HELPERS ----------------
def clean_text(text):
    text = re.sub(r'\s+', ' ', text)
    return text.strip()

# ---------------- CONFIG ----------------
BASE_FOLDER = "/content/drive/MyDrive/OitLab/Text"
OUTPUT_CSV = "/content/drive/MyDrive/OitLab/Text/pdf_dataset1.csv"
PREFERRED_CATEGORIES = ["Historique","Religion","Muslim"]
N_WORKERS = max(1, cpu_count() - 1)

print(f"N_WORKERS: {N_WORKERS}")

# ---------------- LOAD EXISTING CSV ----------------
if os.path.exists(OUTPUT_CSV):
    df_existing = pd.read_csv(OUTPUT_CSV)
else:
    df_existing = pd.DataFrame(columns=["name","page","content","category","char"])

processed_set = set(zip(df_existing['category'], df_existing['name']))

# ---------------- PDF PROCESSOR ----------------
def process_pdf(task):
    category, pdf_path, file_name = task
    pdf_rows = []

    try:
        reader = PdfReader(pdf_path)
        total_pages = len(reader.pages)

        for page_num, page in enumerate(reader.pages):
            text = page.extract_text()
            text = "" if text is None else clean_text(text)

            # OCR fallback
            if len(text) < 30:
                images = convert_from_path(
                    pdf_path,
                    first_page=page_num + 1,
                    last_page=page_num + 1
                )
                ocr_text = pytesseract.image_to_string(
                    images[0],
                    lang="ara+eng"
                )
                text = clean_text(ocr_text)

            pdf_rows.append({
                "name": file_name,
                "page": page_num + 1,
                "content": text,
                "category": category,
                "char": len(text)
            })

    except Exception as e:
        print(f"Error processing {pdf_path}: {e}")

    return pdf_rows

# ---------------- BUILD TASK LIST ----------------
all_categories = [f for f in os.listdir(BASE_FOLDER)
                  if os.path.isdir(os.path.join(BASE_FOLDER, f))]

sorted_categories = []
for p_cat in PREFERRED_CATEGORIES:
    if p_cat in all_categories:
        sorted_categories.append(p_cat)
        all_categories.remove(p_cat)
sorted_categories.extend(all_categories)

tasks = []
for category in sorted_categories:
    category_path = os.path.join(BASE_FOLDER, category)
    files_in_category = [f for f in os.listdir(category_path)
                         if f.lower().endswith(".pdf")]

    for file_name in files_in_category:
        if (category, file_name) in processed_set:
            continue
        pdf_path = os.path.join(category_path, file_name)
        tasks.append((category, pdf_path, file_name))

print(f"Total PDFs to process: {len(tasks)}")
print(f"Using {N_WORKERS} workers")

# ---------------- MULTIPROCESSING ----------------
all_rows = []

with Pool(N_WORKERS) as pool:
    for pdf_rows in tqdm(pool.imap_unordered(process_pdf, tasks),
                         total=len(tasks)):
        if pdf_rows:
            all_rows.extend(pdf_rows)

            # incremental save (safe: only main process writes)
            df_temp = pd.DataFrame(pdf_rows)
            write_header = not os.path.exists(OUTPUT_CSV) or df_existing.empty
            df_temp.to_csv(
                OUTPUT_CSV,
                mode='a',
                header=write_header,
                index=False
            )

print("Processing complete!")