Spaces:
Sleeping
Sleeping
Download utils.py from Haroonk/pdf-summarizer: direct link, hf CLI and curl.
- Browser
- Download file 1.51 kB
-
https://huggingface.co/spaces/Haroonk/pdf-summarizer/resolve/main/utils.py
- Command line
-
hf download hf://spaces/Haroonk/pdf-summarizer/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Haroonk/pdf-summarizer/resolve/main/utils.py
1.51 kB
| import pypdf | |
| from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM | |
| import torch # ← ADD THIS LINE - This was missing! | |
| def extract_text_from_pdf(pdf_file): | |
| """Extract text from uploaded PDF file""" | |
| pdf_reader = pypdf.PdfReader(pdf_file) | |
| text = "" | |
| for page in pdf_reader.pages: | |
| text += page.extract_text() + "\n" | |
| return text | |
| def initialize_summarizer(): | |
| """Initialize the summarization model (runs once)""" | |
| # Using facebook/bart-large-cnn - one of the best free summarization models | |
| tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn") | |
| model = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn") | |
| summarizer = pipeline( | |
| "summarization", | |
| model=model, | |
| tokenizer=tokenizer, | |
| device=0 if torch.cuda.is_available() else -1 # Use GPU if available | |
| ) | |
| return summarizer | |
| def summarize_with_hf(text, max_length=200, min_length=50): | |
| """Summarize text using Hugging Face transformers""" | |
| # Truncate text to fit model's context (BART handles ~1024 tokens) | |
| text = text[:3000] # Safe limit for free model | |
| # Initialize summarizer (only once per session) | |
| summarizer = initialize_summarizer() | |
| # Generate summary | |
| summary = summarizer( | |
| text, | |
| max_length=max_length, | |
| min_length=min_length, | |
| do_sample=False, | |
| truncation=True | |
| ) | |
| return summary[0]['summary_text'] |