Alioth86 commited on
Commit
4b2ecdc
1 Parent(s): afb084e

Delete app.py

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