Ouaill commited on
Commit
5ea2bd5
·
verified ·
1 Parent(s): ef8266e

Create script.py

Browse files
Files changed (1) hide show
  1. script.py +212 -0
script.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Pdf-Data 1.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1IB0DbFJbA27C0womZkoMQZ7oIkgJkHYU
8
+
9
+ # Install & import libs
10
+ """
11
+
12
+ !pip install pypdf pandas tqdm
13
+
14
+ !apt-get install -y tesseract-ocr
15
+ !pip install pytesseract pdf2image pypdf pandas tqdm pillow
16
+ !apt-get install -y tesseract-ocr-ara
17
+
18
+ !apt-get install -y poppler-utils
19
+
20
+ import os
21
+ import pandas as pd
22
+ from pypdf import PdfReader
23
+ from tqdm import tqdm
24
+
25
+ """# Mount Google Drive"""
26
+
27
+ from google.colab import drive
28
+ drive.mount('/content/drive')
29
+
30
+ """# Config paths"""
31
+
32
+ BASE_FOLDER = "/content/drive/MyDrive/OitLab/Text"
33
+ OUTPUT_CSV = "/content/drive/MyDrive/OitLab/Text/pdf_dataset1.csv"
34
+
35
+ """# Core extraction logic"""
36
+
37
+ # import os
38
+ # from pypdf import PdfReader
39
+ # from pdf2image import convert_from_path
40
+ # import pytesseract
41
+ # from tqdm.notebook import tqdm
42
+ # import re
43
+
44
+ # rows = []
45
+
46
+ # def clean_text(text):
47
+ # text = re.sub(r'\s+', ' ', text)
48
+ # return text.strip()
49
+
50
+ # for category in os.listdir(BASE_FOLDER):
51
+ # category_path = os.path.join(BASE_FOLDER, category)
52
+
53
+ # if not os.path.isdir(category_path):
54
+ # continue
55
+
56
+ # print(f"\nProcessing category: {category}")
57
+
58
+ # files = [f for f in os.listdir(category_path) if f.lower().endswith(".pdf")]
59
+
60
+ # for file in tqdm(files, desc="PDF files"):
61
+ # pdf_path = os.path.join(category_path, file)
62
+
63
+ # try:
64
+ # reader = PdfReader(pdf_path)
65
+ # total_pages = len(reader.pages)
66
+
67
+ # for page_num, page in enumerate(
68
+ # tqdm(reader.pages, desc=f"{file}", total=total_pages, leave=False)
69
+ # ):
70
+ # text = page.extract_text()
71
+ # text = "" if text is None else clean_text(text)
72
+
73
+ # # --------- OCR FALLBACK ----------
74
+ # if len(text) < 30:
75
+ # images = convert_from_path(
76
+ # pdf_path,
77
+ # first_page=page_num + 1,
78
+ # last_page=page_num + 1
79
+ # )
80
+ # ocr_text = pytesseract.image_to_string(
81
+ # images[0],
82
+ # lang="ara+eng"
83
+ # )
84
+ # text = clean_text(ocr_text)
85
+
86
+ # rows.append({
87
+ # "name": file,
88
+ # "page": page_num + 1,
89
+ # "content": text,
90
+ # "category": category,
91
+ # "char": len(text)
92
+ # })
93
+
94
+ # except Exception as e:
95
+ # print(f"Error with {pdf_path}: {e}")
96
+
97
+ import os
98
+ import pandas as pd
99
+ from pypdf import PdfReader
100
+ from pdf2image import convert_from_path
101
+ import pytesseract
102
+ from tqdm import tqdm
103
+ import re
104
+ from multiprocessing import Pool, cpu_count
105
+ from functools import partial
106
+
107
+ # ---------------- HELPERS ----------------
108
+ def clean_text(text):
109
+ text = re.sub(r'\s+', ' ', text)
110
+ return text.strip()
111
+
112
+ # ---------------- CONFIG ----------------
113
+ BASE_FOLDER = "/content/drive/MyDrive/OitLab/Text"
114
+ OUTPUT_CSV = "/content/drive/MyDrive/OitLab/Text/pdf_dataset1.csv"
115
+ PREFERRED_CATEGORIES = ["Historique","Religion","Muslim"]
116
+ N_WORKERS = max(1, cpu_count() - 1)
117
+
118
+ print(f"N_WORKERS: {N_WORKERS}")
119
+
120
+ # ---------------- LOAD EXISTING CSV ----------------
121
+ if os.path.exists(OUTPUT_CSV):
122
+ df_existing = pd.read_csv(OUTPUT_CSV)
123
+ else:
124
+ df_existing = pd.DataFrame(columns=["name","page","content","category","char"])
125
+
126
+ processed_set = set(zip(df_existing['category'], df_existing['name']))
127
+
128
+ # ---------------- PDF PROCESSOR ----------------
129
+ def process_pdf(task):
130
+ category, pdf_path, file_name = task
131
+ pdf_rows = []
132
+
133
+ try:
134
+ reader = PdfReader(pdf_path)
135
+ total_pages = len(reader.pages)
136
+
137
+ for page_num, page in enumerate(reader.pages):
138
+ text = page.extract_text()
139
+ text = "" if text is None else clean_text(text)
140
+
141
+ # OCR fallback
142
+ if len(text) < 30:
143
+ images = convert_from_path(
144
+ pdf_path,
145
+ first_page=page_num + 1,
146
+ last_page=page_num + 1
147
+ )
148
+ ocr_text = pytesseract.image_to_string(
149
+ images[0],
150
+ lang="ara+eng"
151
+ )
152
+ text = clean_text(ocr_text)
153
+
154
+ pdf_rows.append({
155
+ "name": file_name,
156
+ "page": page_num + 1,
157
+ "content": text,
158
+ "category": category,
159
+ "char": len(text)
160
+ })
161
+
162
+ except Exception as e:
163
+ print(f"Error processing {pdf_path}: {e}")
164
+
165
+ return pdf_rows
166
+
167
+ # ---------------- BUILD TASK LIST ----------------
168
+ all_categories = [f for f in os.listdir(BASE_FOLDER)
169
+ if os.path.isdir(os.path.join(BASE_FOLDER, f))]
170
+
171
+ sorted_categories = []
172
+ for p_cat in PREFERRED_CATEGORIES:
173
+ if p_cat in all_categories:
174
+ sorted_categories.append(p_cat)
175
+ all_categories.remove(p_cat)
176
+ sorted_categories.extend(all_categories)
177
+
178
+ tasks = []
179
+ for category in sorted_categories:
180
+ category_path = os.path.join(BASE_FOLDER, category)
181
+ files_in_category = [f for f in os.listdir(category_path)
182
+ if f.lower().endswith(".pdf")]
183
+
184
+ for file_name in files_in_category:
185
+ if (category, file_name) in processed_set:
186
+ continue
187
+ pdf_path = os.path.join(category_path, file_name)
188
+ tasks.append((category, pdf_path, file_name))
189
+
190
+ print(f"Total PDFs to process: {len(tasks)}")
191
+ print(f"Using {N_WORKERS} workers")
192
+
193
+ # ---------------- MULTIPROCESSING ----------------
194
+ all_rows = []
195
+
196
+ with Pool(N_WORKERS) as pool:
197
+ for pdf_rows in tqdm(pool.imap_unordered(process_pdf, tasks),
198
+ total=len(tasks)):
199
+ if pdf_rows:
200
+ all_rows.extend(pdf_rows)
201
+
202
+ # incremental save (safe: only main process writes)
203
+ df_temp = pd.DataFrame(pdf_rows)
204
+ write_header = not os.path.exists(OUTPUT_CSV) or df_existing.empty
205
+ df_temp.to_csv(
206
+ OUTPUT_CSV,
207
+ mode='a',
208
+ header=write_header,
209
+ index=False
210
+ )
211
+
212
+ print("Processing complete!")