wfranco commited on
Commit
4b35058
β€’
1 Parent(s): d65ea56

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ from PyPDF2 import PdfReader
4
+ import numpy as np
5
+ from bark import generate_audio, preload_models
6
+ from scipy.io.wavfile import write as write_wav
7
+ import torch
8
+ import tempfile
9
+ import os
10
+
11
+ # Preload models if needed
12
+ preload_models()
13
+
14
+ def summarize_abstract_from_pdf(pdf_file):
15
+ # Function to extract and summarize the abstract from a PDF
16
+ abstract_string = 'abstract'
17
+ found_abstract = False
18
+ intro_string = 'introduction'
19
+ extracted_text_string = ""
20
+
21
+ # Read the PDF and extract text from the first page
22
+ reader = PdfReader(pdf_file)
23
+ text = reader.pages[0].extract_text()
24
+
25
+ for line in text.splitlines():
26
+ lower_line = line.lower()
27
+ if lower_line.strip() == abstract_string:
28
+ found_abstract = True
29
+ elif "1" in lower_line.strip() and intro_string in lower_line.strip():
30
+ found_abstract = False
31
+
32
+ if found_abstract:
33
+ extracted_text_string += line + " "
34
+
35
+ extracted_text_string = extracted_text_string.replace("Abstract", "")
36
+
37
+ # Use Hugging Face summarization pipeline
38
+ summarizer = pipeline("summarization", "pszemraj/led-base-book-summary", device=0 if torch.cuda.is_available() else -1)
39
+ summarized_abstract = summarizer(extracted_text_string, min_length=16, max_length=150, no_repeat_ngram_size=3, encoder_no_repeat_ngram_size=3, repetition_penalty=3.5, num_beams=4, early_stopping=True)
40
+ return summarized_abstract[0]['summary_text']
41
+
42
+ def generate_audio_func(pdf_file):
43
+ text_prompt = summarize_abstract_from_pdf(pdf_file)
44
+ audio_array = generate_audio(text_prompt)
45
+
46
+ # Create a temporary WAV file to save the audio
47
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_wav_file:
48
+ write_wav(temp_wav_file.name, 22050, (audio_array * 32767).astype(np.int16))
49
+ return temp_wav_file.name
50
+
51
+ # Define the Gradio interface
52
+ demo = gr.Interface(
53
+ fn=generate_audio_func,
54
+ inputs=gr.inputs.File(file_types=["pdf"]),
55
+ outputs=gr.outputs.Audio(type="file"),
56
+ title="PDF to Audio Converter",
57
+ description="Convert text from a PDF file to audio. Upload a PDF file with an abstract to get started."
58
+ )
59
+
60
+ if __name__ == "__main__":
61
+ demo.launch()