Alioth86 commited on
Commit
89a88be
·
1 Parent(s): 80b578f

Add application file

Browse files
Files changed (1) hide show
  1. app.py +191 -0
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import transformers
3
+ from transformers import pipeline
4
+ import PyPDF2
5
+ import pdfplumber
6
+ from pdfminer.high_level import extract_pages, extract_text
7
+ from pdfminer.layout import LTTextContainer, LTChar, LTRect, LTFigure
8
+ import re
9
+ import torch
10
+ from datasets import load_dataset
11
+ import soundfile as sf
12
+ from IPython.display import Audio
13
+ import numpy as np
14
+ from datasets import load_dataset
15
+ import sentencepiece as spm
16
+
17
+
18
+
19
+ def text_extraction(element):
20
+ # Extracting the text from the in-line text element
21
+ line_text = element.get_text()
22
+
23
+ # Find the formats of the text
24
+ # Initialize the list with all the formats that appeared in the line of text
25
+ line_formats = []
26
+ for text_line in element:
27
+ if isinstance(text_line, LTTextContainer):
28
+ # Iterating through each character in the line of text
29
+ for character in text_line:
30
+ if isinstance(character, LTChar):
31
+ # Append the font name of the character
32
+ line_formats.append(character.fontname)
33
+ # Append the font size of the character
34
+ line_formats.append(character.size)
35
+ # Find the unique font sizes and names in the line
36
+ format_per_line = list(set(line_formats))
37
+
38
+ # Return a tuple with the text in each line along with its format
39
+ return (line_text, format_per_line)
40
+
41
+ def read_pdf(pdf_pathy):
42
+ # create a PDF file object
43
+ pdfFileObj = open(pdf_pathy, 'rb')
44
+ # create a PDF reader object
45
+ pdfReaded = PyPDF2.PdfReader(pdfFileObj)
46
+
47
+ # Create the dictionary to extract text from each image
48
+ text_per_pagy = {}
49
+ # We extract the pages from the PDF
50
+ for pagenum, page in enumerate(extract_pages(pdf_pathy)):
51
+ print("Elaborating Page_" +str(pagenum))
52
+ # Initialize the variables needed for the text extraction from the page
53
+ pageObj = pdfReaded.pages[pagenum]
54
+ page_text = []
55
+ line_format = []
56
+ page_content = []
57
+
58
+ # Open the pdf file
59
+ pdf = pdfplumber.open(pdf_pathy)
60
+
61
+
62
+ # Find all the elements
63
+ page_elements = [(element.y1, element) for element in page._objs]
64
+ # Sort all the elements as they appear in the page
65
+ page_elements.sort(key=lambda a: a[0], reverse=True)
66
+
67
+ # Find the elements that composed a page
68
+ for i,component in enumerate(page_elements):
69
+ # Extract the position of the top side of the element in the PDF
70
+ pos= component[0]
71
+ # Extract the element of the page layout
72
+ element = component[1]
73
+
74
+ # Check if the element is a text element
75
+ if isinstance(element, LTTextContainer):
76
+ # Check if the text appeared in a table
77
+ # Use the function to extract the text and format for each text element
78
+ (line_text, format_per_line) = text_extraction(element)
79
+ # Append the text of each line to the page text
80
+ page_text.append(line_text)
81
+ # Append the format for each line containing text
82
+ line_format.append(format_per_line)
83
+ page_content.append(line_text)
84
+
85
+
86
+ # Create the key of the dictionary
87
+ dctkey = 'Page_'+str(pagenum)
88
+ # Add the list of list as the value of the page key
89
+ text_per_pagy[dctkey]= [page_text, line_format, page_content]
90
+
91
+ # Closing the pdf file object
92
+ pdfFileObj.close()
93
+
94
+
95
+ return text_per_pagy
96
+
97
+ #performing a cleaning of the contents
98
+ import re
99
+
100
+ def clean_text(text):
101
+ # remove extra spaces
102
+ text = re.sub(r'\s+', ' ', text)
103
+
104
+ return text.strip()
105
+
106
+ # using the function on the text_per_page_1 dictionary
107
+ for key, value in text_per_pagy.items():
108
+ cleaned_text = clean_text(' '.join(value[0])) # value[0] contains the text
109
+ text_per_pagy[key] = cleaned_text
110
+
111
+ # Now text_per_pagy is clean
112
+
113
+ def extract_abstract(text_per_pagy):
114
+ abstract_text = ""
115
+
116
+ #iterate through each page in the extracted text dictionary
117
+ for page_num, page_text in text_per_pagy.items():
118
+ if page_text:
119
+ # Replace hyphens used for line breaks
120
+ page_text = page_text.replace("- ", "")
121
+
122
+ # Looking for the start of the abstract
123
+ start_index = page_text.find("Abstract")
124
+ if start_index != -1:
125
+ # Adjust the start index to exclude the word "Abstract" itself
126
+ # The length of "Abstract" is 8 characters; we also add 1 to skip the space after it
127
+ start_index += len("Abstract") + 1
128
+
129
+ # Searching the possible end markers of the abstract
130
+ end_markers = ["Introduction", "Summary", "Overview", "Background"]
131
+ end_index = -1
132
+
133
+ for marker in end_markers:
134
+ temp_index = page_text.find(marker, start_index)
135
+ if temp_index != -1:
136
+ end_index = temp_index
137
+ break
138
+
139
+ # If no end marker found, take entire text after "Abstract"
140
+ if end_index == -1:
141
+ end_index = len(page_text)
142
+
143
+ # Extract the abstract text
144
+ abstract = page_text[start_index:end_index].strip()
145
+
146
+ # Add the abstract to the complete text
147
+ abstract_text += " " + abstract
148
+
149
+ break
150
+
151
+ return abstract_text
152
+
153
+
154
+
155
+ def main_function(pdf_file):
156
+ # Converti il PDF in testo
157
+ text_per_pagy = read_pdf(pdf_file.name)
158
+
159
+ # Pulisci e estrai l'abstract
160
+ for key, value in text_per_pagy.items():
161
+ cleaned_text = clean_text(' '.join(value[0]))
162
+ text_per_pagy[key] = cleaned_text
163
+ abstract_text = extract_abstract(text_per_pagy)
164
+
165
+ # Riassumi l'abstract
166
+ summarizer = pipeline("summarization", model="pszemraj/long-t5-tglobal-base-sci-simplify-elife")
167
+ summary = summarizer(abstract_text, max_length=50, min_length=30, do_sample=False)[0]['summary_text']
168
+
169
+ # Genera l'audio dal riassunto
170
+ synthesiser = pipeline("text-to-speech", model="microsoft/speecht5_tts")
171
+ embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
172
+ speaker_embedding = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
173
+ speech = synthesiser(summary, forward_params={"speaker_embeddings": speaker_embedding})
174
+
175
+ # Salva l'audio in un file temporaneo
176
+ audio_file_path = "summary.wav"
177
+ sf.write(audio_file_path, speech["audio"], samplerate=speech["sampling_rate"])
178
+
179
+ # Restituisci testo e audio
180
+ return summary, audio_file_path
181
+
182
+ # Crea l'interfaccia Gradio
183
+ iface = gr.Interface(
184
+ fn=main_function,
185
+ inputs=gr.inputs.File(type="pdf"),
186
+ outputs=[gr.outputs.Textbox(label="Summary Text"), gr.outputs.Audio(label="Summary Audio", type="file")]
187
+ )
188
+
189
+ # Avvia l'app
190
+ if __name__ == "__main__":
191
+ iface.launch()