student2222333051 commited on
Commit
a0746e3
·
verified ·
1 Parent(s): 5bed521

Update pdf_reader.py

Browse files
Files changed (1) hide show
  1. pdf_reader.py +42 -11
pdf_reader.py CHANGED
@@ -1,16 +1,47 @@
 
1
  import io
2
- from PyPDF2 import PdfReader
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  def extract_text_from_pdf(pdf_bytes: bytes) -> str:
5
- try:
6
- reader = PdfReader(io.BytesIO(pdf_bytes))
7
- text = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- for page in reader.pages:
10
- page_text = page.extract_text()
11
- if page_text:
12
- text += page_text + "\n"
13
 
14
- return text
15
- except:
16
- return ""
 
1
+ # pdf_reader.py
2
  import io
3
+ from typing import Optional
4
+
5
+ # Бірнеше кітапхана арқылы оқуды қолдаймыз — ең алдымен PyPDF2, егер қажет болса pdfminer.six
6
+ try:
7
+ from PyPDF2 import PdfReader
8
+ _has_pypdf2 = True
9
+ except Exception:
10
+ _has_pypdf2 = False
11
+
12
+ try:
13
+ from pdfminer.high_level import extract_text as pdfminer_extract_text
14
+ _has_pdfminer = True
15
+ except Exception:
16
+ _has_pdfminer = False
17
 
18
  def extract_text_from_pdf(pdf_bytes: bytes) -> str:
19
+ """
20
+ PDF-тен мәтін алу. Бірнеше әдісті қолданып көреді.
21
+ """
22
+ # 1) PyPDF2
23
+ if _has_pypdf2:
24
+ try:
25
+ reader = PdfReader(io.BytesIO(pdf_bytes))
26
+ text = ""
27
+ for page in reader.pages:
28
+ page_text = page.extract_text()
29
+ if page_text:
30
+ text += page_text + "\n"
31
+ if text.strip():
32
+ return text
33
+ except Exception:
34
+ pass
35
+
36
+ # 2) pdfminer.six (әдетте күрделі PDF-тарға жақсы)
37
+ if _has_pdfminer:
38
+ try:
39
+ text = pdfminer_extract_text(io.BytesIO(pdf_bytes))
40
+ if text and text.strip():
41
+ return text
42
+ except Exception:
43
+ pass
44
 
45
+ # Егер ештеңе шықпаса — бос қайтарың
46
+ return ""
 
 
47