MHayden commited on
Commit
c21b272
·
1 Parent(s): 5f637b8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PyPDF2 import PdfReader
2
+ from transformers import pipeline, SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
3
+ import torch
4
+ import soundfile as sf
5
+ from IPython.display import Audio
6
+ from datasets import load_dataset
7
+ import gradio as gr
8
+ import os, re
9
+ import shutil
10
+
11
+
12
+ first_model = pipeline(task='summarization',model='pszemraj/long-t5-tglobal-base-16384-book-summary')
13
+ processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
14
+ model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
15
+
16
+ def readAbstract(pdf):
17
+ # Extract text from PDF
18
+ reader = PdfReader(pdf)
19
+ # Extract each page to variable.
20
+ abstract = reader.pages[0]
21
+ abstract = abstract.extract_text()
22
+ # Removing all before 'abstract' for cleaning
23
+ abstract = abstract[abstract.find('Abstract'):]
24
+ abstract = abstract.split('Introduction', 1)[0]
25
+ return abstract
26
+
27
+ title = 'PDF Abstracter'
28
+ description = 'The model takes a PDF with an abstract as input and summarises it in one sentence that can be read and listened to. Please note that only PDFs with an abstract will work, otherwise there will be an error'
29
+ def abstract_summary(file):
30
+ # Set file path for uploaded file
31
+ file_path = "/content/" + os.path.basename(file)
32
+ shutil.copyfile(file.name, file_path)
33
+ # Extract Abstract from PDF
34
+ pdf = readAbstract(file_path)
35
+ # Run Summarisation Model
36
+ abstract = first_model(pdf)
37
+
38
+ # Text cleaning
39
+ abstract = str(abstract)
40
+ abstract = abstract.replace("[","").replace("]","").replace("{","").replace("}","").replace("'","").replace("summary_text: ","")
41
+
42
+ inputs = processor(text=str(abstract), return_tensors="pt")
43
+ embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
44
+ speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
45
+ spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
46
+ vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
47
+
48
+ with torch.no_grad():
49
+ speech = vocoder(spectrogram)
50
+ speech = model.generate_speech(inputs["input_ids"], speaker_embeddings, vocoder=vocoder)
51
+ audio = Audio(speech, rate=16000)
52
+ with open('/content/abstract.wav', 'wb') as f:
53
+ f.write(audio.data)
54
+ audio = os.path.join('/content/abstract.wav')
55
+ return abstract, audio
56
+
57
+ gui = gr.Interface(fn=abstract_summary,inputs=["file",],outputs=["text","audio"],title=title,description=description)
58
+ gui.launch(debug=True)