Ari commited on
Commit
94bf427
·
verified ·
1 Parent(s): a52e8bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -48
app.py CHANGED
@@ -1,63 +1,65 @@
1
- import os
2
  import gradio as gr
3
- from docx import Document
 
 
 
4
  from gtts import gTTS
5
- from fpdf import FPDF # Pure Python library for PDF generation
6
- from pdfminer.high_level import extract_text as extract_pdf_text
7
 
8
- # Function to extract text from PDF
9
- def extract_text_from_pdf(pdf_file):
10
- return extract_pdf_text(pdf_file.name)
11
 
12
- # Function to extract text from DOCX
13
- def extract_text_from_docx(docx_file):
14
- doc = Document(docx_file.name)
15
- full_text = []
16
- for para in doc.paragraphs:
17
- full_text.append(para.text)
18
- return '\n'.join(full_text)
19
 
20
- # Function to generate PDF using FPDF
21
- def generate_pdf(text, output_path="output.pdf"):
22
- pdf = FPDF()
23
- pdf.add_page()
24
- pdf.set_font("Arial", size=12)
25
- pdf.multi_cell(0, 10, text)
26
- pdf.output(output_path)
27
 
28
- # Function to process files (PDF or DOCX), convert to text, audio, and PDF
29
- def process_file(file):
30
  try:
31
- # Check file extension
32
- file_extension = os.path.splitext(file.name)[1].lower()
33
-
34
- # Extract text based on file type
35
- if file_extension == '.pdf':
36
- extracted_text = extract_text_from_pdf(file)
37
- elif file_extension in ['.doc', '.docx']:
38
- extracted_text = extract_text_from_docx(file)
39
- else:
40
- return None, "Unsupported file type", None
41
-
42
- # Generate the PDF using FPDF
43
- pdf_output_path = "document_output.pdf"
44
- generate_pdf(extracted_text, pdf_output_path)
45
-
46
- # Convert the text to audio using gTTS
47
- tts = gTTS(text=extracted_text, lang='en', slow=False)
48
- audio_output_path = "document_audio.wav"
 
 
 
 
 
 
 
 
 
49
  tts.save(audio_output_path)
50
-
51
- return audio_output_path, extracted_text, pdf_output_path
52
-
53
  except Exception as e:
54
  return None, f"An error occurred: {str(e)}", None
55
 
56
- # Gradio interface for file upload (PDF or DOC/DOCX)
57
  iface = gr.Interface(
58
- fn=process_file,
59
- inputs=gr.File(label="Upload PDF or DOC/DOCX File"),
60
- outputs=[gr.Audio(label="Generated Audio"), gr.Textbox(label="Extracted Text"), gr.File(label="Generated PDF")]
61
  )
62
 
63
  if __name__ == "__main__":
 
 
1
  import gradio as gr
2
+ import os
3
+ import nltk
4
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
5
+ from fpdf import FPDF
6
  from gtts import gTTS
7
+ from pdfminer.high_level import extract_text
 
8
 
9
+ nltk.download('punkt')
 
 
10
 
11
+ # Load the models and tokenizers once, not every time the function is called
12
+ tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
13
+ model = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn")
 
 
 
 
14
 
15
+ # Function to split the text into smaller chunks
16
+ def split_text(text, chunk_size=1024):
17
+ words = text.split()
18
+ for i in range(0, len(words), chunk_size):
19
+ yield ' '.join(words[i:i + chunk_size])
 
 
20
 
21
+ # Main processing function
22
+ def pdf_to_text(text, PDF, min_length=20):
23
  try:
24
+ # Extract text from PDF if no input text provided
25
+ if text == "":
26
+ text = extract_text(PDF.name)
27
+
28
+ # Split the text into chunks for summarization
29
+ summarized_text = ""
30
+ for chunk in split_text(text):
31
+ # Tokenize chunked text
32
+ inputs = tokenizer([chunk], max_length=1024, return_tensors="pt")
33
+ min_length = int(min_length)
34
+
35
+ # Generate summary for each chunk
36
+ summary_ids = model.generate(inputs["input_ids"], num_beams=2, min_length=min_length, max_length=min_length+1000)
37
+ output_text = tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)[0]
38
+ summarized_text += output_text + " " # Append each chunk summary
39
+
40
+ # Save summarized text to PDF
41
+ pdf = FPDF()
42
+ pdf.add_page()
43
+ pdf.set_font("Times", size=12)
44
+ pdf.multi_cell(190, 10, txt=summarized_text, align='C')
45
+ pdf_output_path = "legal.pdf"
46
+ pdf.output(pdf_output_path)
47
+
48
+ # Convert summarized text to audio
49
+ audio_output_path = "legal.wav"
50
+ tts = gTTS(text=summarized_text, lang='en', slow=False)
51
  tts.save(audio_output_path)
52
+
53
+ return audio_output_path, summarized_text, pdf_output_path
54
+
55
  except Exception as e:
56
  return None, f"An error occurred: {str(e)}", None
57
 
58
+ # Gradio interface
59
  iface = gr.Interface(
60
+ fn=pdf_to_text,
61
+ inputs=[gr.Textbox(label="Input Text"), gr.File(label="Upload PDF"), gr.Slider(minimum=10, maximum=100, step=10, value=20, label="Summary Minimum Length")],
62
+ outputs=[gr.Audio(label="Generated Audio"), gr.Textbox(label="Generated Summary"), gr.File(label="Summary PDF")]
63
  )
64
 
65
  if __name__ == "__main__":