text: from PIL import Image
  import fitz
  import pytesseract
  import os
  from docx import Document
  
  pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
  
  
  def doc_getter(path):
      return fitz.open(path)
  
  
  def pdf_state_checker(pdf, password=None):
      if pdf.isEncrypted and password:
          pdf.authenticate(password)
  
      return pdf.isEncrypted
  
  
  def pdf_extractor(doc, img_path, page_nums=None):
  
      pages = []
  
      if page_nums is None:
          page_nums = [num for num in range(len(doc))]
  
      for page in page_nums:
          imglist = doc.getPageImageList(page)
          for img in imglist:
              xref = img[0]  # xref number
              pix = fitz.Pixmap(doc, xref)  # make pixmap from image
              if pix.n - pix.alpha < 4:  # can be saved as PNG
                  pix.writePNG(img_path + f"{page}-{xref}.png")
                  pages.append((f"page{page}", img_path + f"{page}-{xref}.png"))
              else:  # CMYK: must convert first
                  pix0 = fitz.Pixmap(fitz.csRGB, pix)
                  pix0.writePNG(img_path + f"{page}-{xref}.png")
                  pages.append((f"page{page}", img_path + f"{page}-{xref}.png"))
                  pix0 = None  # free Pixmap resources
              pix = None  # free Pixmap resources
  
      return pages
  
  
  def text_extractor(pdfs: list, name="ocr.txt", flag="eng"):
      raw = ""
      document = Document()
  
      for page in pdfs:
          raw += page[0] + "\n" + pytesseract.image_to_string(Image.open(page[1]), lang=flag) + "\n"
  
      for paragraph in raw.split("\n\n"):
          document.add_paragraph(paragraph.replace("\n", " "))
  
      document.save(name)
  
  
  def cleanup(pdfs: list):
  
      for pdf in pdfs:
          os.remove(pdf[1])
  
  
  if __name__ == "__main__":
  
      input_path = r"D:\Downloads\MAC Work\Session 2\[Unfinished]Jami Alalum\jami-ul-uloom.pdf"
      img_path = r"../PDF_OCR/IMGs/" if os.path.exists(r"../PDF_OCR/IMGs/") else os.makedirs(r"../PDF_OCR/IMGs/")
      *folder_path, file_name, useless = input_path.split(r"\ ".rstrip())
      output_path = r"\ ".rstrip().join(folder_path) + ((r"\ ".rstrip() + file_name) * 2) + ".docx"
      file_pages = "98-110,302-322"
  
      if "," in file_pages:
          if "-" in file_pages:
              file_pages = file_pages.split(",")
              all_pages = []
              for chapter in file_pages:
                  all_pages.extend(
                      [number - 1 for number in range(int(chapter.split("-")[0]), int(chapter.split("-")[1]) + 1)])
              file_pages = all_pages
          else:
              file_pages = [int(number) - 1 for number in file_pages.split(",")]
  
      elif "-" in file_pages:
          file_pages = file_pages.split("-")
          file_pages = [number - 1 for number in range(int(file_pages[0]), int(file_pages[1]) + 1)]
  
      elif file_pages.isdigit():
          file_pages = [int(file_pages) - 1]
  
      doc = doc_getter(input_path)
  
      files = pdf_extractor(doc, img_path, None if file_pages == "" else file_pages)
      text_extractor(files, output_path, flag="eng")
      cleanup(files)
  