jurnalku-api / api /reader /document_reader.py
Fikri Bintang
feat: Deploy Jurnalku Python API to HF Spaces
ec99d5d
Raw
History Blame Contribute Delete
727 Bytes
import io
import pypdf
import docx
def extract_text_from_pdf(pdf_bytes: bytes) -> tuple[str, int]:
pdf_file = io.BytesIO(pdf_bytes)
reader = pypdf.PdfReader(pdf_file)
text = ""
for page in reader.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
return text.strip(), len(reader.pages)
def extract_text_from_docx(docx_bytes: bytes) -> tuple[str, int]:
docx_file = io.BytesIO(docx_bytes)
doc = docx.Document(docx_file)
text = ""
for paragraph in doc.paragraphs:
if paragraph.text:
text += paragraph.text + "\n"
words = len(text.split())
page_count = max(1, words // 400)
return text.strip(), page_count