Spaces:
Runtime error
Runtime error
File size: 19,262 Bytes
4c634f2 ee0d33f 1ee9ade 0f467e3 b5e77db 4c634f2 0f467e3 ebf0b29 ee0d33f 4c634f2 1ee9ade 4c634f2 1ee9ade 4c634f2 1ee9ade 4c634f2 1ee9ade 4c634f2 1ee9ade 4c634f2 1ee9ade 4c634f2 221de09 b397f13 4c634f2 f7ea072 4c634f2 f7ea072 bb850d5 6100c94 bb850d5 221de09 07bed83 0f467e3 8cae8bc 0ec0587 8cae8bc 0f467e3 5b575aa 4c634f2 5b575aa 1ee9ade 4c634f2 1ee9ade ee0d33f 1ee9ade ee0d33f 1ee9ade 4c634f2 5b575aa 221de09 4c634f2 1ee9ade 4c634f2 bba2975 221de09 1ee9ade 4c634f2 daa5ff3 4c634f2 1ee9ade 0f467e3 09c3b82 0f467e3 09c3b82 0f467e3 09c3b82 0f467e3 5b575aa 221de09 f7ea072 038645c f7ea072 4c634f2 f7ea072 4c634f2 6100c94 bb850d5 bba2975 e41cc61 ffee274 5b575aa e41cc61 5b575aa 221de09 4c634f2 9e1df22 4c634f2 d57300e 4c634f2 5463224 daa5ff3 6100c94 e41cc61 daa5ff3 6100c94 e41cc61 daa5ff3 1ee9ade 4c634f2 3dd2c60 e07287a 3dd2c60 1ee9ade 65b4025 4c634f2 65b4025 221de09 79513d7 4c634f2 79513d7 65b4025 221de09 79513d7 65b4025 221de09 79513d7 8cae8bc 79513d7 efa520c 8cae8bc 425594a 8cae8bc cad33a9 8cae8bc b45bcf7 8cae8bc b45bcf7 8cae8bc b45bcf7 8cae8bc b45bcf7 8cae8bc efa520c 425594a 0f467e3 8cae8bc 0f467e3 8cae8bc 0f467e3 8cae8bc 0f467e3 8cae8bc 0f467e3 65b4025 221de09 79513d7 4c634f2 79513d7 4c634f2 6100c94 79513d7 65b4025 b6bf8ab 4c634f2 ffee274 65b4025 b6bf8ab 65b4025 4c634f2 9e1df22 4c634f2 d57300e 4c634f2 5463224 daa5ff3 8cae8bc 6100c94 b6bf8ab daa5ff3 8cae8bc 6100c94 b6bf8ab daa5ff3 f7ea072 1ee9ade 69a21ba f7ea072 1ee9ade 221de09 f7ea072 1ee9ade 7c285ca 1ee9ade 7c285ca bba2975 69a21ba 1ee9ade bba2975 f7ea072 221de09 f7ea072 4c634f2 587e518 4c634f2 3a0b0c9 221de09 f7ea072 a263611 4c634f2 221de09 f7ea072 4c634f2 bb850d5 fb09c72 221de09 f7ea072 4c634f2 a263611 4c634f2 a263611 4c634f2 69a21ba f7ea072 bba2975 f7ea072 221de09 f7ea072 4c634f2 f7ea072 221de09 f7ea072 4c634f2 221de09 b397f13 4c634f2 79513d7 fb09c72 221de09 f7ea072 a263611 4c634f2 a263611 4c634f2 1ee9ade 3a0b0c9 4c634f2 5958011 4c634f2 ebf0b29 e07287a ebf0b29 69a21ba 4c634f2 9db221b 4c634f2 d0a463e 4c634f2 d0a463e 4c634f2 d0a463e 4c634f2 6518c39 d0a463e 4c634f2 65070b3 221de09 e6419e2 65070b3 4c634f2 6518c39 4c634f2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
# Imports
import gradio as gr
import whisper
from pytube import YouTube
from transformers import pipeline, T5Tokenizer, T5ForConditionalGeneration, AutoTokenizer, AutoModelForSeq2SeqLM
import torch
from wordcloud import WordCloud
import re
import os
class GradioInference:
def __init__(self):
# OpenAI's Whisper model sizes
self.sizes = list(whisper._MODELS.keys())
# Whisper's available languages for ASR
self.langs = ["none"] + sorted(list(whisper.tokenizer.LANGUAGES.values()))
# Default size
self.current_size = "base"
# Default model size
self.loaded_model = whisper.load_model(self.current_size)
# Initialize Pytube Object
self.yt = None
# Initialize summary model for English
self.summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
# Initialize VoiceLabT5 model and tokenizer
self.keyword_model = T5ForConditionalGeneration.from_pretrained(
"Voicelab/vlt5-base-keywords"
)
self.keyword_tokenizer = T5Tokenizer.from_pretrained(
"Voicelab/vlt5-base-keywords"
)
# Sentiment Classifier
self.classifier = pipeline("text-classification", model="lxyuan/distilbert-base-multilingual-cased-sentiments-student", return_all_scores=False)
# Initialize Multilingual summary model
self.tokenizer = AutoTokenizer.from_pretrained("csebuetnlp/mT5_multilingual_XLSum")
self.model = AutoModelForSeq2SeqLM.from_pretrained("csebuetnlp/mT5_multilingual_XLSum")
# self.llm_tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-7b-instruct")
# self.pipeline = pipeline(
# "text-generation", #task
# model="tiiuae/falcon-7b-instruct",
# tokenizer=self.llm_tokenizer,
# trust_remote_code=True,
# do_sample=True,
# top_k=10,
# num_return_sequences=1,
# eos_token_id=self.tokenizer.eos_token_id
# )
def __call__(self, link, lang, size, progress=gr.Progress()):
"""
Call the Gradio Inference python class.
This class gets access to a YouTube video using python's library Pytube and downloads its audio.
Then it uses the Whisper model to perform Automatic Speech Recognition (i.e Speech-to-Text).
Once the function has the transcription of the video it proccess it to obtain:
- Summary: using Facebook's BART transformer.
- KeyWords: using VoiceLabT5 keyword extractor.
- Sentiment Analysis: using Hugging Face's default sentiment classifier
- WordCloud: using the wordcloud python library.
"""
progress(0, desc="Starting analysis")
if self.yt is None:
self.yt = YouTube(link)
# Pytube library to access to YouTube audio stream
path = self.yt.streams.filter(only_audio=True)[0].download(filename="tmp.mp4")
if lang == "none":
lang = None
if size != self.current_size:
self.loaded_model = whisper.load_model(size)
self.current_size = size
progress(0.20, desc="Transcribing")
# Transcribe the audio extracted from pytube
results = self.loaded_model.transcribe(path, language=lang)
progress(0.40, desc="Summarizing")
# Perform summarization on the transcription
transcription_summary = self.summarizer(
results["text"], max_length=150, min_length=30, do_sample=False
)
#### Prueba
WHITESPACE_HANDLER = lambda k: re.sub('\s+', ' ', re.sub('\n+', ' ', k.strip()))
input_ids_sum = self.tokenizer(
[WHITESPACE_HANDLER(results["text"])],
return_tensors="pt",
padding="max_length",
truncation=True,
max_length=512
)["input_ids"]
output_ids_sum = self.model.generate(
input_ids=input_ids_sum,
max_length=130,
no_repeat_ngram_size=2,
num_beams=4
)[0]
summary = self.tokenizer.decode(
output_ids_sum,
skip_special_tokens=True,
clean_up_tokenization_spaces=False
)
#### Fin prueba
progress(0.50, desc="Extracting Keywords")
# Extract keywords using VoiceLabT5
task_prefix = "Keywords: "
input_sequence = task_prefix + results["text"]
input_ids = self.keyword_tokenizer(
input_sequence, return_tensors="pt", truncation=False
).input_ids
output = self.keyword_model.generate(
input_ids, no_repeat_ngram_size=3, num_beams=4
)
predicted = self.keyword_tokenizer.decode(output[0], skip_special_tokens=True)
keywords = [x.strip() for x in predicted.split(",") if x.strip()]
formatted_keywords = "\n".join([f"β’ {keyword}" for keyword in keywords])
progress(0.80, desc="Extracting Sentiment")
# Define a dictionary to map labels to emojis
sentiment_emojis = {
"positive": "Positive ππΌ",
"negative": "Negative ππΌ",
"neutral": "Neutral πΆ",
}
# Sentiment label
label = self.classifier(summary)[0]["label"]
# Format the label with emojis
formatted_sentiment = sentiment_emojis.get(label, label)
progress(0.90, desc="Generating Wordcloud")
# Generate WordCloud object
wordcloud = WordCloud(colormap = "Oranges").generate(results["text"])
# WordCloud image to display
wordcloud_image = wordcloud.to_image()
if lang == "english":
return (
results["text"],
transcription_summary[0]["summary_text"],
formatted_keywords,
formatted_sentiment,
wordcloud_image,
)
else:
return (
results["text"],
summary,
formatted_keywords,
formatted_sentiment,
wordcloud_image,
)
def populate_metadata(self, link):
"""
Access to the YouTube video title and thumbnail image to further display it
params:
- link: a YouTube URL.
"""
if not link:
return None, None
self.yt = YouTube(link)
return self.yt.thumbnail_url, self.yt.title
def from_audio_input(self, lang, size, audio_file, progress=gr.Progress()):
"""
Call the Gradio Inference python class.
Uses it directly the Whisper model to perform Automatic Speech Recognition (i.e Speech-to-Text).
Once the function has the transcription of the video it proccess it to obtain:
- Summary: using Facebook's BART transformer.
- KeyWords: using VoiceLabT5 keyword extractor.
- Sentiment Analysis: using Hugging Face's default sentiment classifier
- WordCloud: using the wordcloud python library.
"""
progress(0, desc="Starting analysis")
if lang == "none":
lang = None
if size != self.current_size:
self.loaded_model = whisper.load_model(size)
self.current_size = size
progress(0.20, desc="Transcribing")
results = self.loaded_model.transcribe(audio_file, language=lang)
progress(0.40, desc="Summarizing")
# Perform summarization on the transcription
transcription_summary = self.summarizer(
results["text"], max_length=150, min_length=30, do_sample=False
)
########################## PRUEBA LLM #################################
# from langchain import HuggingFacePipeline, PromptTemplate, LLMChain
# llm = HuggingFacePipeline(pipeline = self.pipeline, model_kwargs = {'temperature':0})
# template = """
# Write a concise summary of the following text delimited by triple backquotes.
# ```{text}```
# CONCISE SUMMARY:
# """
# prompt = PromptTemplate(template=template, input_variables=["text"])
# llm_chain = LLMChain(prompt=prompt, llm=llm)
# text = results["text"]
# summ = llm_chain.run(text)
########################## FIN PRUEBA LLM #################################
#### Prueba
WHITESPACE_HANDLER = lambda k: re.sub('\s+', ' ', re.sub('\n+', ' ', k.strip()))
input_ids_sum = self.tokenizer(
[WHITESPACE_HANDLER(results["text"])],
return_tensors="pt",
padding="max_length",
truncation=True,
max_length=512
)["input_ids"]
output_ids_sum = self.model.generate(
input_ids=input_ids_sum,
max_length=130,
no_repeat_ngram_size=2,
num_beams=4
)[0]
summary = self.tokenizer.decode(
output_ids_sum,
skip_special_tokens=True,
clean_up_tokenization_spaces=False
)
#### Fin prueba
progress(0.50, desc="Extracting Keywords")
# Extract keywords using VoiceLabT5
task_prefix = "Keywords: "
input_sequence = task_prefix + results["text"]
input_ids = self.keyword_tokenizer(
input_sequence, return_tensors="pt", truncation=False
).input_ids
output = self.keyword_model.generate(
input_ids, no_repeat_ngram_size=3, num_beams=4
)
predicted = self.keyword_tokenizer.decode(output[0], skip_special_tokens=True)
keywords = [x.strip() for x in predicted.split(",") if x.strip()]
formatted_keywords = "\n".join([f"β’ {keyword}" for keyword in keywords])
progress(0.80, desc="Extracting Sentiment")
# Define a dictionary to map labels to emojis
sentiment_emojis = {
"positive": "Positive ππΌ",
"negative": "Negative ππΌ",
"neutral": "Neutral πΆ",
}
# Sentiment label
label = self.classifier(summary)[0]["label"]
# Format the label with emojis
formatted_sentiment = sentiment_emojis.get(label, label)
progress(0.90, desc="Generating Wordcloud")
# WordCloud object
wordcloud = WordCloud(colormap = "Oranges").generate(
results["text"]
)
wordcloud_image = wordcloud.to_image()
if lang == "english":
return (
results["text"],
# summ,
transcription_summary[0]["summary_text"],
formatted_keywords,
formatted_sentiment,
wordcloud_image,
)
else:
return (
results["text"],
# summ,
summary,
formatted_keywords,
formatted_sentiment,
wordcloud_image,
)
gio = GradioInference()
title = "YouTube Insights"
description = "Your AI-powered video analytics tool"
block = gr.Blocks()
with block as demo:
gr.HTML(
"""
<div style="text-align: center; max-width: 500px; margin: 0 auto;">
<div>
<h1>YouTube <span style="color: #FFA500;">Insights</span> π‘</h1>
</div>
<h4 style="margin-bottom: 10px; font-size: 95%">
Your AI-powered video analytics tool β¨
</h4>
</div>
"""
)
with gr.Group():
with gr.Tab("From YouTube πΉ"):
with gr.Box():
with gr.Row().style(equal_height=True):
size = gr.Dropdown(
label="Speech-to-text Model Size", choices=gio.sizes, value="base"
)
lang = gr.Dropdown(
label="Language (Optional)", choices=gio.langs, value="none"
)
link = gr.Textbox(
label="YouTube Link", placeholder="Enter YouTube link..."
)
title = gr.Label(label="Video Title")
with gr.Row().style(equal_height=True):
img = gr.Image(label="Thumbnail")
text = gr.Textbox(
label="Transcription",
placeholder="Transcription Output...",
lines=10,
).style(show_copy_button=True, container=True)
with gr.Row().style(equal_height=True):
summary = gr.Textbox(
label="Summary", placeholder="Summary Output...", lines=5
).style(show_copy_button=True, container=True)
keywords = gr.Textbox(
label="Keywords", placeholder="Keywords Output...", lines=5
).style(show_copy_button=True, container=True)
label = gr.Label(label="Sentiment Analysis")
wordcloud_image = gr.Image(label="WordCloud")
with gr.Row().style(equal_height=True):
clear = gr.ClearButton(
[link, title, img, text, summary, keywords, label, wordcloud_image], scale=1, value="Clear ποΈ"
)
btn = gr.Button("Get video insights π", variant="primary", scale=1)
btn.click(
gio,
inputs=[link, lang, size],
outputs=[text, summary, keywords, label, wordcloud_image],
)
link.change(gio.populate_metadata, inputs=[link], outputs=[img, title])
with gr.Tab("From Audio file ποΈ"):
with gr.Box():
with gr.Row().style(equal_height=True):
size = gr.Dropdown(
label="Model Size", choices=gio.sizes, value="base"
)
lang = gr.Dropdown(
label="Language (Optional)", choices=gio.langs, value="none"
)
audio_file = gr.Audio(type="filepath")
with gr.Row().style(equal_height=True):
text = gr.Textbox(
label="Transcription",
placeholder="Transcription Output...",
lines=10,
).style(show_copy_button=True, container=False)
with gr.Row().style(equal_height=True):
summary = gr.Textbox(
label="Summary", placeholder="Summary Output", lines=5
)
keywords = gr.Textbox(
label="Keywords", placeholder="Keywords Output", lines=5
)
label = gr.Label(label="Sentiment Analysis")
wordcloud_image = gr.Image(label="WordCloud")
with gr.Row().style(equal_height=True):
clear = gr.ClearButton([audio_file,text, summary, keywords, label, wordcloud_image], scale=1, value="Clear ποΈ")
btn = gr.Button(
"Get audio insights π", variant="primary", scale=1
)
btn.click(
gio.from_audio_input,
inputs=[lang, size, audio_file],
outputs=[text, summary, keywords, label, wordcloud_image],
)
with block:
gr.Markdown("### Video Examples")
gr.Examples(["https://www.youtube.com/shorts/xDNzz8yAH7I","https://www.youtube.com/watch?v=kib6uXQsxBA&pp=ygURc3RldmUgam9icyBzcGVlY2g%3D"], inputs=link)
gr.Markdown("### Audio Examples")
gr.Examples(
[[os.path.join(os.path.dirname(__file__),"audios/TED_lagrange_point.wav")],[os.path.join(os.path.dirname(__file__),"audios/TED_platon.wav")]],
inputs=audio_file)
gr.Markdown("### About the app:")
with gr.Accordion("What is YouTube Insights?", open=False):
gr.Markdown(
"YouTube Insights is a tool developed for academic purposes that allows you to analyze YouTube videos or audio files. It provides features like transcription, summarization, keyword extraction, sentiment analysis, and word cloud generation for multimedia content."
)
with gr.Accordion("How does YouTube Insights work?", open=False):
gr.Markdown(
"YouTube Insights leverages several powerful AI models and libraries. It uses OpenAI's Whisper for Automatic Speech Recognition (ASR) to transcribe audio content. It summarizes the transcribed text using Facebook's BART model, extracts keywords with VoiceLabT5, performs sentiment analysis with DistilBERT, and generates word clouds."
)
with gr.Accordion("What languages are supported for the analysis?", open=False):
gr.Markdown(
"YouTube Insights supports multiple languages for transcription and analysis. You can select your preferred language from the available options when using the app."
)
with gr.Accordion("Can I analyze audio files instead of YouTube videos?", open=False):
gr.Markdown(
"Yes, you can analyze audio files directly. Simply upload your audio file to the app, and it will provide the same transcription, summarization, keyword extraction, sentiment analysis, and word cloud generation features."
)
with gr.Accordion("What are the different model sizes available for transcription?", open=False):
gr.Markdown(
"The app uses a Speech-to-text model that has different training sizes, from tiny to large. Hence, the bigger the model the accurate the transcription."
)
with gr.Accordion("How long does it take to analyze a video or audio file?", open=False):
gr.Markdown(
"The time taken for analysis may vary based on the duration of the video or audio file and the selected model size. Shorter content will be processed more quickly."
)
with gr.Accordion("Who developed YouTube Insights?" ,open=False):
gr.Markdown(
"YouTube Insights was developed by students as part of the 2022/23 Master's in Big Data & Data Science program at Universidad Complutense de Madrid for academic purposes (Trabajo de Fin de Master)."
)
gr.HTML(
"""
<div style="text-align: center; max-width: 500px; margin: 0 auto;">
<p style="margin-bottom: 10px; font-size: 96%">
Trabajo de Fin de MΓ‘ster - Grupo 3
</p>
<p style="margin-bottom: 10px; font-size: 90%">
2023 Master in Big Data & Data Science - Universidad Complutense de Madrid
</p>
</div>
"""
)
demo.launch()
|