Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,243 +1,243 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import io
|
| 3 |
-
from flask import Flask, render_template, request, jsonify, send_file
|
| 4 |
-
from werkzeug.utils import secure_filename
|
| 5 |
-
import PyPDF2
|
| 6 |
-
from io import BytesIO
|
| 7 |
-
from reportlab.pdfgen import canvas
|
| 8 |
-
from reportlab.lib.pagesizes import letter
|
| 9 |
-
import nltk
|
| 10 |
-
from nltk.tokenize import sent_tokenize, word_tokenize
|
| 11 |
-
from nltk.corpus import stopwords
|
| 12 |
-
from collections import defaultdict
|
| 13 |
-
import heapq
|
| 14 |
-
import tempfile
|
| 15 |
-
import json
|
| 16 |
-
|
| 17 |
-
# ==============================
|
| 18 |
-
# FIXED NLTK DOWNLOAD SECTION
|
| 19 |
-
# ==============================
|
| 20 |
-
|
| 21 |
-
def download_nltk_resources():
|
| 22 |
-
resources = ['punkt', 'punkt_tab', 'stopwords']
|
| 23 |
-
|
| 24 |
-
for resource in resources:
|
| 25 |
-
try:
|
| 26 |
-
nltk.data.find(f'tokenizers/{resource}')
|
| 27 |
-
except LookupError:
|
| 28 |
-
try:
|
| 29 |
-
nltk.data.find(f'corpora/{resource}')
|
| 30 |
-
except LookupError:
|
| 31 |
-
nltk.download(resource)
|
| 32 |
-
|
| 33 |
-
download_nltk_resources()
|
| 34 |
-
|
| 35 |
-
# ==============================
|
| 36 |
-
|
| 37 |
-
app = Flask(__name__)
|
| 38 |
-
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
|
| 39 |
-
app.config['UPLOAD_FOLDER'] = tempfile.gettempdir()
|
| 40 |
-
app.config['SECRET_KEY'] = 'your-secret-key-here'
|
| 41 |
-
|
| 42 |
-
ALLOWED_EXTENSIONS = {'pdf'}
|
| 43 |
-
|
| 44 |
-
def allowed_file(filename):
|
| 45 |
-
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def extract_text_from_pdf(pdf_file):
|
| 49 |
-
"""Extract text from uploaded PDF file"""
|
| 50 |
-
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
| 51 |
-
text = ""
|
| 52 |
-
for page in pdf_reader.pages:
|
| 53 |
-
page_text = page.extract_text()
|
| 54 |
-
if page_text:
|
| 55 |
-
text += page_text + "\n"
|
| 56 |
-
return text
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
def summarize_text(text, num_sentences=5):
|
| 60 |
-
"""Summarize text using frequency-based scoring"""
|
| 61 |
-
|
| 62 |
-
sentences = sent_tokenize(text)
|
| 63 |
-
|
| 64 |
-
if len(sentences) <= num_sentences:
|
| 65 |
-
return text
|
| 66 |
-
|
| 67 |
-
stop_words = set(stopwords.words('english'))
|
| 68 |
-
words = word_tokenize(text.lower())
|
| 69 |
-
words = [word for word in words if word.isalnum() and word not in stop_words]
|
| 70 |
-
|
| 71 |
-
word_freq = defaultdict(int)
|
| 72 |
-
for word in words:
|
| 73 |
-
word_freq[word] += 1
|
| 74 |
-
|
| 75 |
-
sentence_scores = defaultdict(int)
|
| 76 |
-
for i, sentence in enumerate(sentences):
|
| 77 |
-
sentence_words = word_tokenize(sentence.lower())
|
| 78 |
-
for word in sentence_words:
|
| 79 |
-
if word in word_freq:
|
| 80 |
-
sentence_scores[i] += word_freq[word]
|
| 81 |
-
|
| 82 |
-
top_sentences = heapq.nlargest(num_sentences, sentence_scores, key=sentence_scores.get)
|
| 83 |
-
top_sentences.sort()
|
| 84 |
-
|
| 85 |
-
summary = [sentences[i] for i in top_sentences]
|
| 86 |
-
return ' '.join(summary)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def analyze_pdf_statistics(text):
|
| 90 |
-
"""Analyze PDF and return statistics"""
|
| 91 |
-
sentences = sent_tokenize(text)
|
| 92 |
-
words = word_tokenize(text)
|
| 93 |
-
characters = len(text)
|
| 94 |
-
|
| 95 |
-
return {
|
| 96 |
-
'page_count': text.count('\f') + 1,
|
| 97 |
-
'sentence_count': len(sentences),
|
| 98 |
-
'word_count': len(words),
|
| 99 |
-
'character_count': characters,
|
| 100 |
-
'avg_sentence_length': round(len(words) / len(sentences), 2) if sentences else 0,
|
| 101 |
-
'avg_word_length': round(sum(len(word) for word in words) / len(words), 2) if words else 0
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
def create_summary_pdf(summary, filename="summary.pdf"):
|
| 106 |
-
"""Create a downloadable PDF from summary"""
|
| 107 |
-
buffer = BytesIO()
|
| 108 |
-
pdf = canvas.Canvas(buffer, pagesize=letter)
|
| 109 |
-
pdf.setTitle("PDF Summary")
|
| 110 |
-
|
| 111 |
-
pdf.setFont("Helvetica-Bold", 16)
|
| 112 |
-
pdf.drawString(72, 750, "PDF Document Summary")
|
| 113 |
-
pdf.line(72, 745, 540, 745)
|
| 114 |
-
|
| 115 |
-
pdf.setFont("Helvetica", 12)
|
| 116 |
-
y_position = 720
|
| 117 |
-
max_width = 500
|
| 118 |
-
words = summary.split()
|
| 119 |
-
line = []
|
| 120 |
-
|
| 121 |
-
for word in words:
|
| 122 |
-
line.append(word)
|
| 123 |
-
test_line = ' '.join(line)
|
| 124 |
-
|
| 125 |
-
if pdf.stringWidth(test_line, "Helvetica", 12) > max_width:
|
| 126 |
-
line.pop()
|
| 127 |
-
pdf.drawString(72, y_position, ' '.join(line))
|
| 128 |
-
y_position -= 20
|
| 129 |
-
line = [word]
|
| 130 |
-
|
| 131 |
-
if y_position < 50:
|
| 132 |
-
pdf.showPage()
|
| 133 |
-
pdf.setFont("Helvetica", 12)
|
| 134 |
-
y_position = 750
|
| 135 |
-
|
| 136 |
-
if line:
|
| 137 |
-
pdf.drawString(72, y_position, ' '.join(line))
|
| 138 |
-
|
| 139 |
-
pdf.save()
|
| 140 |
-
buffer.seek(0)
|
| 141 |
-
return buffer
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
@app.route('/')
|
| 145 |
-
def index():
|
| 146 |
-
return render_template('index.html')
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
@app.route('/upload', methods=['POST'])
|
| 150 |
-
def upload_pdf():
|
| 151 |
-
if 'pdf_file' not in request.files:
|
| 152 |
-
return jsonify({'error': 'No file uploaded'}), 400
|
| 153 |
-
|
| 154 |
-
file = request.files['pdf_file']
|
| 155 |
-
|
| 156 |
-
if file.filename == '':
|
| 157 |
-
return jsonify({'error': 'No file selected'}), 400
|
| 158 |
-
|
| 159 |
-
if not allowed_file(file.filename):
|
| 160 |
-
return jsonify({'error': 'Only PDF files are allowed'}), 400
|
| 161 |
-
|
| 162 |
-
try:
|
| 163 |
-
text = extract_text_from_pdf(file)
|
| 164 |
-
|
| 165 |
-
if not text.strip():
|
| 166 |
-
return jsonify({'error': 'Could not extract text from PDF. The PDF might be scanned or image-based.'}), 400
|
| 167 |
-
|
| 168 |
-
summary_ratio = float(request.form.get('summary_ratio', 0.3))
|
| 169 |
-
total_sentences = len(sent_tokenize(text))
|
| 170 |
-
num_sentences = max(3, int(total_sentences * summary_ratio))
|
| 171 |
-
|
| 172 |
-
summary = summarize_text(text, num_sentences)
|
| 173 |
-
stats = analyze_pdf_statistics(text)
|
| 174 |
-
|
| 175 |
-
original_words = len(word_tokenize(text))
|
| 176 |
-
summary_words = len(word_tokenize(summary))
|
| 177 |
-
|
| 178 |
-
compression_ratio = (
|
| 179 |
-
((original_words - summary_words) / original_words) * 100
|
| 180 |
-
if original_words > 0 else 0
|
| 181 |
-
)
|
| 182 |
-
|
| 183 |
-
return jsonify({
|
| 184 |
-
'success': True,
|
| 185 |
-
'summary': summary,
|
| 186 |
-
'statistics': stats,
|
| 187 |
-
'compression_ratio': round(compression_ratio, 2),
|
| 188 |
-
'summary_length': summary_words,
|
| 189 |
-
'filename': secure_filename(file.filename)
|
| 190 |
-
})
|
| 191 |
-
|
| 192 |
-
except Exception as e:
|
| 193 |
-
return jsonify({'error': f'Error processing PDF: {str(e)}'}), 500
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
@app.route('/download', methods=['POST'])
|
| 197 |
-
def download_summary():
|
| 198 |
-
data = request.json
|
| 199 |
-
summary = data.get('summary', '')
|
| 200 |
-
filename = data.get('filename', 'summary.pdf')
|
| 201 |
-
|
| 202 |
-
if not summary:
|
| 203 |
-
return jsonify({'error': 'No summary to download'}), 400
|
| 204 |
-
|
| 205 |
-
try:
|
| 206 |
-
pdf_buffer = create_summary_pdf(summary, filename)
|
| 207 |
-
|
| 208 |
-
return send_file(
|
| 209 |
-
pdf_buffer,
|
| 210 |
-
as_attachment=True,
|
| 211 |
-
download_name=filename.replace('.pdf', '_summary.pdf'),
|
| 212 |
-
mimetype='application/pdf'
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
except Exception as e:
|
| 216 |
-
return jsonify({'error': f'Error creating PDF: {str(e)}'}), 500
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
@app.route('/export', methods=['POST'])
|
| 220 |
-
def export_summary():
|
| 221 |
-
data = request.json
|
| 222 |
-
summary = data.get('summary', '')
|
| 223 |
-
|
| 224 |
-
if not summary:
|
| 225 |
-
return jsonify({'error': 'No summary to export'}), 400
|
| 226 |
-
|
| 227 |
-
return send_file(
|
| 228 |
-
BytesIO(summary.encode()),
|
| 229 |
-
as_attachment=True,
|
| 230 |
-
download_name='summary.txt',
|
| 231 |
-
mimetype='text/plain'
|
| 232 |
-
)
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
if __name__ == '__main__':
|
| 236 |
-
os.makedirs('uploads', exist_ok=True)
|
| 237 |
-
os.makedirs('templates', exist_ok=True)
|
| 238 |
-
os.makedirs('static', exist_ok=True)
|
| 239 |
-
|
| 240 |
-
print("Starting PDF Summarizer Server...")
|
| 241 |
-
print("Open your browser and navigate to: http://localhost:5000")
|
| 242 |
-
|
| 243 |
-
app.run(debug=True, host='0.0.0.0', port=
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
from flask import Flask, render_template, request, jsonify, send_file
|
| 4 |
+
from werkzeug.utils import secure_filename
|
| 5 |
+
import PyPDF2
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
from reportlab.pdfgen import canvas
|
| 8 |
+
from reportlab.lib.pagesizes import letter
|
| 9 |
+
import nltk
|
| 10 |
+
from nltk.tokenize import sent_tokenize, word_tokenize
|
| 11 |
+
from nltk.corpus import stopwords
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
import heapq
|
| 14 |
+
import tempfile
|
| 15 |
+
import json
|
| 16 |
+
|
| 17 |
+
# ==============================
|
| 18 |
+
# FIXED NLTK DOWNLOAD SECTION
|
| 19 |
+
# ==============================
|
| 20 |
+
|
| 21 |
+
def download_nltk_resources():
|
| 22 |
+
resources = ['punkt', 'punkt_tab', 'stopwords']
|
| 23 |
+
|
| 24 |
+
for resource in resources:
|
| 25 |
+
try:
|
| 26 |
+
nltk.data.find(f'tokenizers/{resource}')
|
| 27 |
+
except LookupError:
|
| 28 |
+
try:
|
| 29 |
+
nltk.data.find(f'corpora/{resource}')
|
| 30 |
+
except LookupError:
|
| 31 |
+
nltk.download(resource)
|
| 32 |
+
|
| 33 |
+
download_nltk_resources()
|
| 34 |
+
|
| 35 |
+
# ==============================
|
| 36 |
+
|
| 37 |
+
app = Flask(__name__)
|
| 38 |
+
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
|
| 39 |
+
app.config['UPLOAD_FOLDER'] = tempfile.gettempdir()
|
| 40 |
+
app.config['SECRET_KEY'] = 'your-secret-key-here'
|
| 41 |
+
|
| 42 |
+
ALLOWED_EXTENSIONS = {'pdf'}
|
| 43 |
+
|
| 44 |
+
def allowed_file(filename):
|
| 45 |
+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def extract_text_from_pdf(pdf_file):
|
| 49 |
+
"""Extract text from uploaded PDF file"""
|
| 50 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
| 51 |
+
text = ""
|
| 52 |
+
for page in pdf_reader.pages:
|
| 53 |
+
page_text = page.extract_text()
|
| 54 |
+
if page_text:
|
| 55 |
+
text += page_text + "\n"
|
| 56 |
+
return text
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def summarize_text(text, num_sentences=5):
|
| 60 |
+
"""Summarize text using frequency-based scoring"""
|
| 61 |
+
|
| 62 |
+
sentences = sent_tokenize(text)
|
| 63 |
+
|
| 64 |
+
if len(sentences) <= num_sentences:
|
| 65 |
+
return text
|
| 66 |
+
|
| 67 |
+
stop_words = set(stopwords.words('english'))
|
| 68 |
+
words = word_tokenize(text.lower())
|
| 69 |
+
words = [word for word in words if word.isalnum() and word not in stop_words]
|
| 70 |
+
|
| 71 |
+
word_freq = defaultdict(int)
|
| 72 |
+
for word in words:
|
| 73 |
+
word_freq[word] += 1
|
| 74 |
+
|
| 75 |
+
sentence_scores = defaultdict(int)
|
| 76 |
+
for i, sentence in enumerate(sentences):
|
| 77 |
+
sentence_words = word_tokenize(sentence.lower())
|
| 78 |
+
for word in sentence_words:
|
| 79 |
+
if word in word_freq:
|
| 80 |
+
sentence_scores[i] += word_freq[word]
|
| 81 |
+
|
| 82 |
+
top_sentences = heapq.nlargest(num_sentences, sentence_scores, key=sentence_scores.get)
|
| 83 |
+
top_sentences.sort()
|
| 84 |
+
|
| 85 |
+
summary = [sentences[i] for i in top_sentences]
|
| 86 |
+
return ' '.join(summary)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def analyze_pdf_statistics(text):
|
| 90 |
+
"""Analyze PDF and return statistics"""
|
| 91 |
+
sentences = sent_tokenize(text)
|
| 92 |
+
words = word_tokenize(text)
|
| 93 |
+
characters = len(text)
|
| 94 |
+
|
| 95 |
+
return {
|
| 96 |
+
'page_count': text.count('\f') + 1,
|
| 97 |
+
'sentence_count': len(sentences),
|
| 98 |
+
'word_count': len(words),
|
| 99 |
+
'character_count': characters,
|
| 100 |
+
'avg_sentence_length': round(len(words) / len(sentences), 2) if sentences else 0,
|
| 101 |
+
'avg_word_length': round(sum(len(word) for word in words) / len(words), 2) if words else 0
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def create_summary_pdf(summary, filename="summary.pdf"):
|
| 106 |
+
"""Create a downloadable PDF from summary"""
|
| 107 |
+
buffer = BytesIO()
|
| 108 |
+
pdf = canvas.Canvas(buffer, pagesize=letter)
|
| 109 |
+
pdf.setTitle("PDF Summary")
|
| 110 |
+
|
| 111 |
+
pdf.setFont("Helvetica-Bold", 16)
|
| 112 |
+
pdf.drawString(72, 750, "PDF Document Summary")
|
| 113 |
+
pdf.line(72, 745, 540, 745)
|
| 114 |
+
|
| 115 |
+
pdf.setFont("Helvetica", 12)
|
| 116 |
+
y_position = 720
|
| 117 |
+
max_width = 500
|
| 118 |
+
words = summary.split()
|
| 119 |
+
line = []
|
| 120 |
+
|
| 121 |
+
for word in words:
|
| 122 |
+
line.append(word)
|
| 123 |
+
test_line = ' '.join(line)
|
| 124 |
+
|
| 125 |
+
if pdf.stringWidth(test_line, "Helvetica", 12) > max_width:
|
| 126 |
+
line.pop()
|
| 127 |
+
pdf.drawString(72, y_position, ' '.join(line))
|
| 128 |
+
y_position -= 20
|
| 129 |
+
line = [word]
|
| 130 |
+
|
| 131 |
+
if y_position < 50:
|
| 132 |
+
pdf.showPage()
|
| 133 |
+
pdf.setFont("Helvetica", 12)
|
| 134 |
+
y_position = 750
|
| 135 |
+
|
| 136 |
+
if line:
|
| 137 |
+
pdf.drawString(72, y_position, ' '.join(line))
|
| 138 |
+
|
| 139 |
+
pdf.save()
|
| 140 |
+
buffer.seek(0)
|
| 141 |
+
return buffer
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@app.route('/')
|
| 145 |
+
def index():
|
| 146 |
+
return render_template('index.html')
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@app.route('/upload', methods=['POST'])
|
| 150 |
+
def upload_pdf():
|
| 151 |
+
if 'pdf_file' not in request.files:
|
| 152 |
+
return jsonify({'error': 'No file uploaded'}), 400
|
| 153 |
+
|
| 154 |
+
file = request.files['pdf_file']
|
| 155 |
+
|
| 156 |
+
if file.filename == '':
|
| 157 |
+
return jsonify({'error': 'No file selected'}), 400
|
| 158 |
+
|
| 159 |
+
if not allowed_file(file.filename):
|
| 160 |
+
return jsonify({'error': 'Only PDF files are allowed'}), 400
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
text = extract_text_from_pdf(file)
|
| 164 |
+
|
| 165 |
+
if not text.strip():
|
| 166 |
+
return jsonify({'error': 'Could not extract text from PDF. The PDF might be scanned or image-based.'}), 400
|
| 167 |
+
|
| 168 |
+
summary_ratio = float(request.form.get('summary_ratio', 0.3))
|
| 169 |
+
total_sentences = len(sent_tokenize(text))
|
| 170 |
+
num_sentences = max(3, int(total_sentences * summary_ratio))
|
| 171 |
+
|
| 172 |
+
summary = summarize_text(text, num_sentences)
|
| 173 |
+
stats = analyze_pdf_statistics(text)
|
| 174 |
+
|
| 175 |
+
original_words = len(word_tokenize(text))
|
| 176 |
+
summary_words = len(word_tokenize(summary))
|
| 177 |
+
|
| 178 |
+
compression_ratio = (
|
| 179 |
+
((original_words - summary_words) / original_words) * 100
|
| 180 |
+
if original_words > 0 else 0
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
return jsonify({
|
| 184 |
+
'success': True,
|
| 185 |
+
'summary': summary,
|
| 186 |
+
'statistics': stats,
|
| 187 |
+
'compression_ratio': round(compression_ratio, 2),
|
| 188 |
+
'summary_length': summary_words,
|
| 189 |
+
'filename': secure_filename(file.filename)
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
except Exception as e:
|
| 193 |
+
return jsonify({'error': f'Error processing PDF: {str(e)}'}), 500
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@app.route('/download', methods=['POST'])
|
| 197 |
+
def download_summary():
|
| 198 |
+
data = request.json
|
| 199 |
+
summary = data.get('summary', '')
|
| 200 |
+
filename = data.get('filename', 'summary.pdf')
|
| 201 |
+
|
| 202 |
+
if not summary:
|
| 203 |
+
return jsonify({'error': 'No summary to download'}), 400
|
| 204 |
+
|
| 205 |
+
try:
|
| 206 |
+
pdf_buffer = create_summary_pdf(summary, filename)
|
| 207 |
+
|
| 208 |
+
return send_file(
|
| 209 |
+
pdf_buffer,
|
| 210 |
+
as_attachment=True,
|
| 211 |
+
download_name=filename.replace('.pdf', '_summary.pdf'),
|
| 212 |
+
mimetype='application/pdf'
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
except Exception as e:
|
| 216 |
+
return jsonify({'error': f'Error creating PDF: {str(e)}'}), 500
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@app.route('/export', methods=['POST'])
|
| 220 |
+
def export_summary():
|
| 221 |
+
data = request.json
|
| 222 |
+
summary = data.get('summary', '')
|
| 223 |
+
|
| 224 |
+
if not summary:
|
| 225 |
+
return jsonify({'error': 'No summary to export'}), 400
|
| 226 |
+
|
| 227 |
+
return send_file(
|
| 228 |
+
BytesIO(summary.encode()),
|
| 229 |
+
as_attachment=True,
|
| 230 |
+
download_name='summary.txt',
|
| 231 |
+
mimetype='text/plain'
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
if __name__ == '__main__':
|
| 236 |
+
os.makedirs('uploads', exist_ok=True)
|
| 237 |
+
os.makedirs('templates', exist_ok=True)
|
| 238 |
+
os.makedirs('static', exist_ok=True)
|
| 239 |
+
|
| 240 |
+
print("Starting PDF Summarizer Server...")
|
| 241 |
+
print("Open your browser and navigate to: http://localhost:5000")
|
| 242 |
+
|
| 243 |
+
app.run(debug=True, host='0.0.0.0', port = 7860)
|