GPL License Alternative PDF Scraper Implementation

Author: y8ymfx8zqb-creatorCreated Jan 5, 2026Updated Sep 30, 2026
Labelsneeds-maintainer-decision

Hey, Happy new year. Since you still have not fixed the mymupdf licensing issue (https://github.com/assafelovic/gpt-researcher/issues/1571). I want to share my alternative pdf scraper using pdfminer six library which is running under MIT and can be used inside your project: https://pypi.org/project/pdfminer.six/

I use this custom scraper to overcome the GPL license infection your project includes.

Cheers

python
"""
Custom PDF Scraper using pdfminer.six (MIT license) instead of PyMuPDF (AGPL).
This scraper handles PDF documents and extracts text content for processing.
"""

import io
import logging
import requests
from typing import Tuple, List
from pdfminer.high_level import extract_text
from pdfminer.pdfparser import PDFSyntaxError
from urllib.parse import urlparse

logger = logging.getLogger(__name__)


class PDFMinerScraper:
    """
    PDF scraper that uses pdfminer.six for text extraction.
    Compatible with the GPTResearcher scraper interface.
    """

    def __init__(self, link: str, session: requests.Session = None):
        """
        Initialize the PDF scraper.

        Args:
            link: URL or path to the PDF document
            session: Optional requests session for HTTP downloads
        """
        self.link = link
        self.session = session or requests.Session()

    def scrape(self) -> Tuple[str, List[str], str]:
        """
        Extract text content from PDF document.

        Returns:
            tuple: (content, image_urls, title)
                - content: Extracted text from PDF
                - image_urls: Empty list (PDF images not extracted)
                - title: PDF title or filename
        """
        try:
            # Download or read PDF content
            pdf_content = self._get_pdf_content()
            if not pdf_content:
                logger.error(f"Could not retrieve PDF content from {self.link}")
                return "", [], self._get_title_from_url()

            # Extract text using pdfminer.six
            text_content = self._extract_text_from_pdf(pdf_content)

            if not text_content.strip():
                logger.warning(f"No text content extracted from PDF: {self.link}")
                return "", [], self._get_title_from_url()

            # Clean up the extracted text
            cleaned_content = self._clean_text(text_content)

            title = self._get_title_from_url()

            logger.info(f"✅ Extracted {len(cleaned_content)} characters from PDF: {title}")

            return cleaned_content, [], title

        except Exception as e:
            logger.error(f"Error extracting PDF content from {self.link}: {str(e)}")
            return f"Error processing PDF: {str(e)}", [], self._get_title_from_url()

    def _get_pdf_content(self) -> bytes:
        """
        Download PDF content from URL or read from local file.

        Returns:
            bytes: PDF file content
        """
        try:
            # Check if it's a URL or local file path
            parsed = urlparse(self.link)

            if parsed.scheme in ('http', 'https'):
                # Download from URL
                response = self.session.get(self.link, timeout=30)
                response.raise_for_status()

                # Verify content type
                content_type = response.headers.get('content-type', '').lower()
                if 'pdf' not in content_type and not self.link.lower().endswith('.pdf'):
                    logger.warning(f"Unexpected content type for PDF: {content_type}")

                return response.content

            else:
                # Read from local file
                with open(self.link, 'rb') as f:
                    return f.read()

        except requests.RequestException as e:
            logger.error(f"Failed to download PDF from {self.link}: {str(e)}")
            return b""
        except FileNotFoundError:
            logger.error(f"PDF file not found: {self.link}")
            return b""
        except Exception as e:
            logger.error(f"Unexpected error getting PDF content: {str(e)}")
            return b""

    def _extract_text_from_pdf(self, pdf_content: bytes) -> str:
        """
        Extract text from PDF bytes using pdfminer.six.

        Args:
            pdf_content: PDF file content as bytes

        Returns:
            str: Extracted text content
        """
        try:
            # Create a file-like object from bytes
            pdf_file = io.BytesIO(pdf_content)

            # Extract text using pdfminer.six
            text = extract_text(pdf_file)

            return text

        except PDFSyntaxError as e:
            logger.error(f"PDF syntax error: {str(e)}")
            return ""
        except Exception as e:
            logger.error(f"Error extracting text from PDF: {str(e)}")
            return ""

    def _clean_text(self, text: str) -> str:
        """
        Clean and normalize extracted text.

        Args:
            text: Raw extracted text

        Returns:
            str: Cleaned text
        """
        if not text:
            return ""

        # Remove excessive whitespace and normalize line breaks
        lines = []
        for line in text.split('\n'):
            line = line.strip()
            if line:  # Skip empty lines
                lines.append(line)

        # Join lines with single spaces, but preserve paragraph breaks
        cleaned = '\n'.join(lines)

        # Remove excessive spacing
        import re
        cleaned = re.sub(r'\s+', ' ', cleaned)
        cleaned = re.sub(r'\n\s*\n', '\n\n', cleaned)

        return cleaned.strip()

    def _get_title_from_url(self) -> str:
        """
        Extract a title from the PDF URL or file path.

        Returns:
            str: PDF title or filename
        """
        try:
            # Extract filename from URL or path
            parsed = urlparse(self.link)
            if parsed.path:
                filename = parsed.path.split('/')[-1]
                if filename:
                    # Remove .pdf extension for cleaner title
                    if filename.lower().endswith('.pdf'):
                        filename = filename[:-4]
                    return filename

            # Fallback to full URL/path
            return self.link

        except Exception:
            return "PDF Document"

Source: assafelovic/gpt-researcher