File size: 1,924 Bytes
6a4c7c4
 
 
 
 
30e58ca
 
6a4c7c4
30e58ca
6a4c7c4
 
30e58ca
6a4c7c4
 
 
 
 
30e58ca
6a4c7c4
 
30e58ca
 
 
 
6a4c7c4
30e58ca
 
 
 
6a4c7c4
 
 
 
 
30e58ca
 
 
6a4c7c4
 
 
 
 
30e58ca
6a4c7c4
 
 
 
 
 
 
30e58ca
6a4c7c4
30e58ca
 
6a4c7c4
 
30e58ca
1
2
3
4
5
6
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import gradio as gr
from pdf2image import convert_from_path
from PIL import Image
import pytesseract
from transformers import pipeline
import tempfile
import os

# Load Hugging Face summarization pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")

# Chunk text into smaller pieces for model input limit
def chunk_text(text, max_tokens=1000):
    words = text.split()
    for i in range(0, len(words), max_tokens):
        yield " ".join(words[i:i+max_tokens])

# Main function: PDF upload β†’ OCR β†’ Summarization
def summarize_image_pdf(pdf_file):
    try:
        # Save uploaded file temporarily
        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
            tmp.write(pdf_file.read())
            tmp_path = tmp.name

        # Convert PDF to images (Poppler is pre-installed on Spaces)
        images = convert_from_path(tmp_path, dpi=300)

        # OCR: Extract text from images
        extracted_text = ""
        for i, img in enumerate(images):
            text = pytesseract.image_to_string(img)
            extracted_text += f"\n\n--- Page {i+1} ---\n{text}"

        os.remove(tmp_path)  # Clean up temp file

        # Summarize text
        summaries = []
        for chunk in chunk_text(extracted_text):
            summary = summarizer(chunk, max_length=130, min_length=30, do_sample=False)[0]['summary_text']
            summaries.append(summary)

        return "\n\n".join(summaries)

    except Exception as e:
        return f"❌ Error: {str(e)}"

# Gradio UI
interface = gr.Interface(
    fn=summarize_image_pdf,
    inputs=gr.File(label="πŸ“„ Upload a scanned/image PDF", file_types=[".pdf"]),
    outputs=gr.Textbox(label="πŸ“ Summary"),
    title="πŸ“˜ OCR PDF Summarizer",
    description="Upload a scanned or image-based PDF. The app will extract text using OCR and summarize it using Hugging Face's BART model.",
)

interface.launch()