Spaces:
Sleeping
Sleeping
AlexanderBenady
commited on
Commit
•
907840f
1
Parent(s):
e6e6ad5
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
import warnings
|
4 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForSpeechSeq2Seq, MarianMTModel, MarianTokenizer, AutoModelForSequenceClassification, AutoProcessor, pipeline
|
5 |
+
import torch
|
6 |
+
from pydub import AudioSegment
|
7 |
+
import gradio as gr
|
8 |
+
|
9 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
10 |
+
warnings.filterwarnings("ignore", message="Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.")
|
11 |
+
warnings.filterwarnings("ignore", message="Due to a bug fix in https://github.com/huggingface/transformers/pull/28687 transcription using a multilingual Whisper will default to language detection followed by transcription instead of translation to English.This might be a breaking change for your use case. If you want to instead always translate your audio to English, make sure to pass `language='en'.")
|
12 |
+
|
13 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
14 |
+
|
15 |
+
# Preload models globally
|
16 |
+
|
17 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
18 |
+
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
19 |
+
|
20 |
+
# Load all necessary models and tokenizers
|
21 |
+
summarizer_tokenizer = AutoTokenizer.from_pretrained('cranonieu2021/pegasus-on-lectures')
|
22 |
+
summarizer_model = AutoModelForSeq2SeqLM.from_pretrained("cranonieu2021/pegasus-on-lectures", torch_dtype=torch_dtype).to(device)
|
23 |
+
|
24 |
+
translator_tokenizer = MarianTokenizer.from_pretrained("sfarjebespalaia/enestranslatorforsummaries")
|
25 |
+
translator_model = MarianMTModel.from_pretrained("sfarjebespalaia/enestranslatorforsummaries", torch_dtype=torch_dtype).to(device)
|
26 |
+
|
27 |
+
classifier_tokenizer = AutoTokenizer.from_pretrained("gserafico/roberta-base-finetuned-classifier-roberta1")
|
28 |
+
classifier_model = AutoModelForSequenceClassification.from_pretrained("gserafico/roberta-base-finetuned-classifier-roberta1", torch_dtype=torch_dtype).to(device)
|
29 |
+
|
30 |
+
|
31 |
+
def transcribe_audio(audio_file_path):
|
32 |
+
try:
|
33 |
+
model_id = "openai/whisper-large-v3"
|
34 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype, use_safetensors=True)
|
35 |
+
model.to(device)
|
36 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
37 |
+
pipe = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor, device=device)
|
38 |
+
result = pipe(audio_file_path)
|
39 |
+
logging.info("Audio transcription completed successfully.")
|
40 |
+
return result['text']
|
41 |
+
except Exception as e:
|
42 |
+
logging.error(f"Error transcribing audio: {e}")
|
43 |
+
raise
|
44 |
+
|
45 |
+
def load_and_process_input(file_info):
|
46 |
+
file_path = file_info # Assuming it's just the path
|
47 |
+
original_filename = os.path.basename(file_path) # Extract filename from path if needed
|
48 |
+
|
49 |
+
extension = os.path.splitext(original_filename)[-1].lower()
|
50 |
+
try:
|
51 |
+
if extension == ".txt":
|
52 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
53 |
+
text = file.read()
|
54 |
+
elif extension in [".mp3", ".wav"]:
|
55 |
+
if extension == ".mp3":
|
56 |
+
file_path = convert_mp3_to_wav(file_path)
|
57 |
+
text = transcribe_audio(file_path)
|
58 |
+
else:
|
59 |
+
raise ValueError("Unsupported file type provided.")
|
60 |
+
except Exception as e:
|
61 |
+
logging.error(f"Error processing input file: {e}")
|
62 |
+
raise
|
63 |
+
return text
|
64 |
+
|
65 |
+
|
66 |
+
|
67 |
+
# Ensure the convert_mp3_to_wav accepts and handles a file path correctly
|
68 |
+
def convert_mp3_to_wav(file_path):
|
69 |
+
try:
|
70 |
+
wav_file_path = file_path.replace(".mp3", ".wav")
|
71 |
+
audio = AudioSegment.from_file(file_path, format='mp3')
|
72 |
+
audio.export(wav_file_path, format="wav")
|
73 |
+
logging.info("MP3 file converted to WAV.")
|
74 |
+
return wav_file_path
|
75 |
+
except Exception as e:
|
76 |
+
logging.error(f"Error converting MP3 to WAV: {e}")
|
77 |
+
raise
|
78 |
+
|
79 |
+
def process_text(text, summarization=False, translation=False, classification=False):
|
80 |
+
results = {}
|
81 |
+
intermediate_text = text # This will hold either the original text or the summary
|
82 |
+
|
83 |
+
if summarization:
|
84 |
+
# Perform summarization
|
85 |
+
inputs = summarizer_tokenizer(intermediate_text, max_length=1024, return_tensors="pt", truncation=True)
|
86 |
+
summary_ids = summarizer_model.generate(inputs.input_ids, max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True)
|
87 |
+
summary_text = summarizer_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
|
88 |
+
results['summarized_text'] = summary_text
|
89 |
+
intermediate_text = summary_text # Update intermediate text to be the summary for further processing
|
90 |
+
|
91 |
+
if translation:
|
92 |
+
# Translate the intermediate text (which could be either the original text or the summary)
|
93 |
+
tokenized_text = translator_tokenizer.prepare_seq2seq_batch([intermediate_text], return_tensors="pt")
|
94 |
+
translated = translator_model.generate(**tokenized_text)
|
95 |
+
translated_text = ' '.join(translator_tokenizer.decode(t, skip_special_tokens=True) for t in translated)
|
96 |
+
results['translated_text'] = translated_text.strip()
|
97 |
+
|
98 |
+
if classification:
|
99 |
+
# Classify the intermediate text (which could be either the original text or the summary)
|
100 |
+
inputs = classifier_tokenizer(intermediate_text, return_tensors="pt", truncation=True, padding=True)
|
101 |
+
with torch.no_grad():
|
102 |
+
outputs = classifier_model(**inputs)
|
103 |
+
predicted_class_idx = torch.argmax(outputs.logits, dim=1).item()
|
104 |
+
labels = {
|
105 |
+
0: 'Social Sciences',
|
106 |
+
1: 'Arts',
|
107 |
+
2: 'Natural Sciences',
|
108 |
+
3: 'Business and Law',
|
109 |
+
4: 'Engineering and Technology'
|
110 |
+
}
|
111 |
+
results['classification_result'] = labels[predicted_class_idx]
|
112 |
+
|
113 |
+
return results
|
114 |
+
|
115 |
+
def display_results(results):
|
116 |
+
if 'summarized_text' in results:
|
117 |
+
print("Summarized Text:")
|
118 |
+
print(results['summarized_text'])
|
119 |
+
if 'translated_text' in results:
|
120 |
+
print("Translated Text:")
|
121 |
+
print(results['translated_text'])
|
122 |
+
if 'classification_result' in results:
|
123 |
+
print('Classification Result:')
|
124 |
+
print(f"This text is classified under: {results['classification_result']}")
|
125 |
+
|
126 |
+
def main():
|
127 |
+
print("Loading models, please wait...")
|
128 |
+
|
129 |
+
file_path = input("Enter the path to your text, mp3, or wav file: ")
|
130 |
+
if not os.path.isfile(file_path):
|
131 |
+
print("File does not exist. Please enter a valid file path.")
|
132 |
+
return
|
133 |
+
|
134 |
+
text = load_and_process_input(file_path)
|
135 |
+
|
136 |
+
print("Choose the tasks to perform:")
|
137 |
+
print("1. Summarization")
|
138 |
+
print("2. Translation")
|
139 |
+
print("3. Classification")
|
140 |
+
print("4. Summarization + Translation")
|
141 |
+
print("5. Summarization + Classification")
|
142 |
+
print("6. Translation + Classification")
|
143 |
+
print("7. Summarization + Translation + Classification")
|
144 |
+
|
145 |
+
while True:
|
146 |
+
try:
|
147 |
+
choice = int(input("Please choose your option -> "))
|
148 |
+
if choice not in range(1, 8):
|
149 |
+
raise ValueError("Please select a valid option from 1 to 7.")
|
150 |
+
break
|
151 |
+
except ValueError as e:
|
152 |
+
print(f"Invalid input: {e}. Please try again.")
|
153 |
+
|
154 |
+
summarization = choice in [1, 4, 5, 7]
|
155 |
+
translation = choice in [2, 4, 6, 7]
|
156 |
+
classification = choice in [3, 5, 6, 7]
|
157 |
+
|
158 |
+
results = process_text(text, summarization=summarization, translation=translation, classification=classification)
|
159 |
+
display_results(results)
|
160 |
+
|
161 |
+
def wrap_process_file(file_obj, tasks):
|
162 |
+
if file_obj is None:
|
163 |
+
return "Please upload a file to proceed.", "", "", ""
|
164 |
+
|
165 |
+
# Assuming file_obj is a tuple containing (temp file path, original file name)
|
166 |
+
text = load_and_process_input(file_obj)
|
167 |
+
results = process_text(text, 'Summarization' in tasks, 'Translation' in tasks, 'Classification' in tasks)
|
168 |
+
|
169 |
+
return (results.get('summarized_text', ''),
|
170 |
+
results.get('translated_text', ''),
|
171 |
+
results.get('classification_result', ''))
|
172 |
+
|
173 |
+
css = """
|
174 |
+
body { font-family: 'Arial'; }
|
175 |
+
.gradio-container { max-width: 800px; margin: auto; padding: 20px; }
|
176 |
+
.input, .output { border-radius: 10px; box-shadow: 0 4px 14px 0 rgba(0,0,0,0.10); }
|
177 |
+
.label { color: #4A4A4A; font-weight: bold; font-size: 14px; }
|
178 |
+
button { background-color: #1a73e8; color: white; border: none; border-radius: 4px; padding: 10px 20px; cursor: pointer; }
|
179 |
+
"""
|
180 |
+
|
181 |
+
def create_gradio_interface():
|
182 |
+
with gr.Blocks(css=css) as demo:
|
183 |
+
gr.Markdown("# LectorSync 1.0")
|
184 |
+
gr.Markdown("## Upload your file and select the tasks:")
|
185 |
+
with gr.Row():
|
186 |
+
file_input = gr.File(label="Upload your text, mp3, or wav file")
|
187 |
+
task_choice = gr.CheckboxGroup(["Summarization", "Translation", "Classification"], label="Select Tasks")
|
188 |
+
submit_button = gr.Button("Process")
|
189 |
+
output_summary = gr.Text(label="Summarized Text")
|
190 |
+
output_translation = gr.Text(label="Translated Text")
|
191 |
+
output_classification = gr.Text(label="Classification Result")
|
192 |
+
|
193 |
+
submit_button.click(
|
194 |
+
fn=wrap_process_file,
|
195 |
+
inputs=[file_input, task_choice],
|
196 |
+
outputs=[output_summary, output_translation, output_classification]
|
197 |
+
)
|
198 |
+
|
199 |
+
return demo
|
200 |
+
|
201 |
+
if __name__ == "__main__":
|
202 |
+
demo = create_gradio_interface()
|
203 |
+
demo.launch()
|