Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,61 +1,31 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
|
| 5 |
-
def
|
|
|
|
| 6 |
text = ""
|
| 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 |
-
return chunks
|
| 32 |
-
|
| 33 |
-
def process_documents(files, log_callback=None):
|
| 34 |
-
all_chunks = []
|
| 35 |
-
for file in files:
|
| 36 |
-
filename = os.path.basename(file)
|
| 37 |
-
ext = filename.split(".")[-1].lower()
|
| 38 |
-
if log_callback:
|
| 39 |
-
log_callback(f"📁 معالجة الملف: {filename}")
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
if ext == "pdf":
|
| 43 |
-
text = extract_text_from_pdf(file)
|
| 44 |
-
elif ext == "docx":
|
| 45 |
-
text = extract_text_from_docx(file)
|
| 46 |
-
elif ext == "txt":
|
| 47 |
-
text = extract_text_from_txt(file)
|
| 48 |
-
else:
|
| 49 |
-
if log_callback:
|
| 50 |
-
log_callback(f"❗️ تنسيق غير مدعوم: {ext}")
|
| 51 |
-
continue
|
| 52 |
-
|
| 53 |
-
chunks = chunk_text(text)
|
| 54 |
-
all_chunks.extend(chunks)
|
| 55 |
-
|
| 56 |
-
if log_callback:
|
| 57 |
-
log_callback(f"✅ تم استخراج {len(chunks)} مقطع من {filename}")
|
| 58 |
-
except Exception as e:
|
| 59 |
-
if log_callback:
|
| 60 |
-
log_callback(f"⚠️ فشل في معالجة {filename}: {e}")
|
| 61 |
-
return all_chunks
|
|
|
|
| 1 |
import os
|
| 2 |
+
from PyPDF2 import PdfReader
|
| 3 |
+
from docx import Document
|
| 4 |
|
| 5 |
+
def process_pdf(file_path):
|
| 6 |
+
reader = PdfReader(file_path)
|
| 7 |
text = ""
|
| 8 |
+
for page in reader.pages:
|
| 9 |
+
text += page.extract_text() + "\n"
|
| 10 |
+
return text.split('\n\n') # تقسيم النص إلى فقرات
|
| 11 |
+
|
| 12 |
+
def process_docx(file_path):
|
| 13 |
+
doc = Document(file_path)
|
| 14 |
+
paragraphs = [p.text for p in doc.paragraphs if p.text.strip() != ""]
|
| 15 |
+
return paragraphs
|
| 16 |
+
|
| 17 |
+
def process_txt(file_path):
|
| 18 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 19 |
+
text = f.read()
|
| 20 |
+
return text.split('\n\n')
|
| 21 |
+
|
| 22 |
+
def process_documents(file_path):
|
| 23 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 24 |
+
if ext == '.pdf':
|
| 25 |
+
return process_pdf(file_path)
|
| 26 |
+
elif ext == '.docx':
|
| 27 |
+
return process_docx(file_path)
|
| 28 |
+
elif ext == '.txt':
|
| 29 |
+
return process_txt(file_path)
|
| 30 |
+
else:
|
| 31 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|