Ari commited on
Commit
c0d316e
1 Parent(s): f336636

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -38
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import gradio as gr
2
  import os
3
  import re
4
- import numpy as np
5
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
6
  from fpdf import FPDF
7
  from gtts import gTTS
@@ -9,43 +8,44 @@ from pdfminer.high_level import extract_text
9
  from docx import Document
10
  from reportlab.lib.pagesizes import letter
11
  from reportlab.pdfgen import canvas
12
- from concurrent.futures import ThreadPoolExecutor
13
 
14
- tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
15
- model = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn")
 
16
 
17
- # Function to chunk text into sentence-based chunks
18
- def chunk_text(text, max_token_len=1024):
19
- sentences = [sent.strip() + '.' for sent in re.split(r'(?<!\d)\.\s', text) if len(sent) > 1]
20
- token_lengths = [len(tokenizer.tokenize(sent)) for sent in sentences]
21
-
22
- chunk_size = max_token_len
23
- chunks = []
24
- current_chunk = []
25
- current_length = 0
 
 
 
 
26
 
27
- for sent, length in zip(sentences, token_lengths):
28
- if current_length + length <= chunk_size:
29
- current_chunk.append(sent)
30
- current_length += length
31
- else:
32
- chunks.append(" ".join(current_chunk))
33
- current_chunk = [sent]
34
- current_length = length
35
 
36
- if current_chunk:
37
- chunks.append(" ".join(current_chunk))
 
38
 
39
- return chunks
 
 
40
 
41
- # Summarization function
42
- def summarize_chunk(chunk, min_length=80):
43
- inputs = tokenizer([chunk], max_length=1024, truncation=True, return_tensors="pt")
44
- summary_ids = model.generate(inputs["input_ids"], num_beams=1, min_length=min_length, max_length=min_length + 300)
45
- return tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)[0]
46
 
47
- # Main processing function using parallel summarization
48
- def pdf_to_text(text, PDF, min_length=80):
49
  try:
50
  file_extension = os.path.splitext(PDF.name)[1].lower()
51
 
@@ -55,13 +55,13 @@ def pdf_to_text(text, PDF, min_length=80):
55
  elif file_extension == '.pdf' and text == "":
56
  text = extract_text(PDF.name)
57
 
 
58
  chunks = chunk_text(text)
59
  summarized_text = ""
60
 
61
- # Parallelize summarization using ThreadPoolExecutor
62
- with ThreadPoolExecutor() as executor:
63
- summaries = list(executor.map(lambda chunk: summarize_chunk(chunk, min_length), chunks))
64
- summarized_text = "\n\n".join(summaries)
65
 
66
  # Save summarized text to PDF
67
  pdf = FPDF()
@@ -81,7 +81,8 @@ def pdf_to_text(text, PDF, min_length=80):
81
  except Exception as e:
82
  return None, f"An error occurred: {str(e)}", None
83
 
84
- def process_sample_document(min_length=80):
 
85
  sample_document_path = "Marbury v. Madison.pdf"
86
 
87
  with open(sample_document_path, "rb") as f:
@@ -90,11 +91,11 @@ def process_sample_document(min_length=80):
90
  # Gradio interface
91
  with gr.Blocks() as iface:
92
  with gr.Row():
93
- process_sample_button = gr.Button("Summarize Pre-Uploaded Marbury v. Madison Case Document")
94
 
95
  text_input = gr.Textbox(label="Input Text")
96
  file_input = gr.File(label="Upload PDF or DOCX")
97
- slider = gr.Slider(minimum=10, maximum=400, step=10, value=80, label="Summary Minimum Length")
98
 
99
  audio_output = gr.Audio(label="Generated Audio")
100
  summary_output = gr.Textbox(label="Generated Summary")
 
1
  import gradio as gr
2
  import os
3
  import re
 
4
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
5
  from fpdf import FPDF
6
  from gtts import gTTS
 
8
  from docx import Document
9
  from reportlab.lib.pagesizes import letter
10
  from reportlab.pdfgen import canvas
 
11
 
12
+ # Switch to a more lightweight model like DistilBART for faster processing
13
+ tokenizer = AutoTokenizer.from_pretrained("sshleifer/distilbart-cnn-12-6")
14
+ model = AutoModelForSeq2SeqLM.from_pretrained("sshleifer/distilbart-cnn-12-6")
15
 
16
+ # Function to chunk text based on token length
17
+ def chunk_text(text, max_token_len=512):
18
+ tokens = tokenizer(text, return_tensors="pt", truncation=False, padding=False)["input_ids"].squeeze()
19
+ total_length = len(tokens)
20
+ # Split text into manageable token chunks
21
+ chunks = [tokens[i:i+max_token_len] for i in range(0, total_length, max_token_len)]
22
+ return chunks
23
+
24
+ def docx_to_pdf(docx_file, output_pdf="converted_doc.pdf"):
25
+ doc = Document(docx_file)
26
+ full_text = []
27
+ for para in doc.paragraphs:
28
+ full_text.append(para.text)
29
 
30
+ pdf = canvas.Canvas(output_pdf, pagesize=letter)
31
+ pdf.setFont("Helvetica", 12)
 
 
 
 
 
 
32
 
33
+ text = pdf.beginText(40, 750)
34
+ for line in full_text:
35
+ text.textLine(line)
36
 
37
+ pdf.drawText(text)
38
+ pdf.save()
39
+ return output_pdf
40
 
41
+ # Summarize each chunk of tokens
42
+ def summarize_chunk(chunk, min_length=50, max_length=150):
43
+ inputs = {"input_ids": chunk.unsqueeze(0)} # Add batch dimension
44
+ summary_ids = model.generate(inputs["input_ids"], num_beams=1, min_length=min_length, max_length=max_length)
45
+ return tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=True)
46
 
47
+ # Main processing function
48
+ def pdf_to_text(text, PDF, min_length=50):
49
  try:
50
  file_extension = os.path.splitext(PDF.name)[1].lower()
51
 
 
55
  elif file_extension == '.pdf' and text == "":
56
  text = extract_text(PDF.name)
57
 
58
+ # Split text into token-based chunks
59
  chunks = chunk_text(text)
60
  summarized_text = ""
61
 
62
+ # Summarize each chunk
63
+ for chunk in chunks:
64
+ summarized_text += summarize_chunk(chunk, min_length=min_length, max_length=min_length + 100) + "\n\n"
 
65
 
66
  # Save summarized text to PDF
67
  pdf = FPDF()
 
81
  except Exception as e:
82
  return None, f"An error occurred: {str(e)}", None
83
 
84
+ # Preloaded document processor
85
+ def process_sample_document(min_length=50):
86
  sample_document_path = "Marbury v. Madison.pdf"
87
 
88
  with open(sample_document_path, "rb") as f:
 
91
  # Gradio interface
92
  with gr.Blocks() as iface:
93
  with gr.Row():
94
+ process_sample_button = gr.Button("Summarize Marbury v. Madison Case Pre-Uploaded")
95
 
96
  text_input = gr.Textbox(label="Input Text")
97
  file_input = gr.File(label="Upload PDF or DOCX")
98
+ slider = gr.Slider(minimum=10, maximum=300, step=10, value=50, label="Summary Minimum Length")
99
 
100
  audio_output = gr.Audio(label="Generated Audio")
101
  summary_output = gr.Textbox(label="Generated Summary")