Spaces:
Sleeping
Sleeping
File size: 20,857 Bytes
7805c1f 7bc7501 58579f9 7805c1f 808db63 7805c1f 58579f9 7805c1f 9c24cde 7805c1f 808db63 7805c1f 9c24cde 7805c1f 808db63 7805c1f 808db63 7805c1f b1be939 7805c1f 43d9ba9 9c24cde 7805c1f 9c24cde 7805c1f 9c24cde 7805c1f 9c24cde 7805c1f a038763 7805c1f |
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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 |
from openai import AzureOpenAI
from langchain_openai import AzureChatOpenAI
import os
import ffmpeg
from typing import List
from moviepy.editor import VideoFileClip
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer
from langchain import HuggingFaceHub, PromptTemplate, LLMChain
from huggingface_hub import InferenceClient
import gradio as gr
import requests
from gtts import gTTS
import logging
# from langchain.document_loaders import UnstructuredFileLoader
from langchain_community.document_loaders import PyPDFLoader
import os
import PyPDF2
nltk.download('punkt')
nltk.download('stopwords')
class PDFAnalytics:
"""
Class for performing analytics on videos including transcription, summarization, topic generation,
and extraction of important sentences.
"""
def __init__(self):
"""
Initialize the VideoAnalytics object.
Args:
hf_token (str): Hugging Face API token.
"""
# Initialize AzureOpenAI client
self.client = AzureOpenAI()
hf_token = os.getenv("HF_TOKEN")
self.mistral_client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1",token=hf_token)
# Initialize extracted_text variable
self.extracted_text = ""
self.openai_llm = AzureChatOpenAI(
deployment_name="GPT-3",
)
# Configure logging settings
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def _extract_text_from_pdfs(self, file_path: str) -> List[str]:
"""Extract text content from PDF files.
Args:
file_paths (List[str]): List of file paths.
Returns:
List[str]: Extracted text from the PDFs.
"""
try:
loader = PyPDFLoader(file_path)
pages = loader.load()
self.extracted_text = pages[0].page_content
return pages[0].page_content
except Exception as e:
logging.error(f"Error pdf extraction: {e}")
return ""
def generate_summary(self,model) -> str:
"""
Generate a summary of the pdf.
Returns:
str: Generated summary.
"""
try:
if model == "OpenAI":
# Define a conversation between system and user
conversation = [
{"role": "system", "content": "You are a Summarizer"},
{"role": "user", "content": f"""summarize the following text delimited by triple backticks.Output must in english.give me a detailed summary.extractive summary working br like extract sentences from given text to return as summary,abstractive summary working be like summary of what about the given text.don't make bullet points write like a passage.
In two format of Outputs given below:
Abstractive Summary:
Extractive Summary:
```{self.extracted_text}```
"""}
]
# Generate completion using ChatGPT model
response = self.client.chat.completions.create(
model="GPT-3",
messages=conversation,
temperature=0,
max_tokens=1000
)
# Get the generated summary message
message = response.choices[0].message.content
return message
elif model == "Mixtral":
task = "summary"
# Generate answer using Mixtral model
prompt = f"""<s>[INST] summarize the following text delimited by triple backticks.Output must in english.give me a detailed summary.extractive summary working br like extract sentences from given text to return as summary,abstractive summary working be like summary of what about the given text.don't make bullet points write like a passage.
In two format of Outputs given below:
Abstractive Summary:
Extractive Summary:
```data:{self.extracted_text}```[/INST]"""
result = self.generate(prompt)
return result
except Exception as e:
logging.error(f"Error generating video summary: {e}")
return ""
def generate_topics(self,model) -> str:
"""
Generate topics from the pdf.
Returns:
str: Generated topics.
"""
try:
if model == "OpenAI":
# Define a conversation between system and user
conversation = [
{"role": "system", "content": "You are a Topic Generator"},
{"role": "user", "content": f"""generate single Topics from the following text don't make sentence for topic generation,delimited by triple backticks.Output must in english.
list out the topics:
Topics:
```{self.extracted_text}```
"""}
]
# Generate completion using ChatGPT model
response = self.client.chat.completions.create(
model="GPT-3",
messages=conversation,
temperature=0,
max_tokens=1000
)
# Get the generated topics message
message = response.choices[0].message.content
return message
elif model == "Mixtral":
task = "topics"
# Generate answer using Mixtral model
prompt = f"""<s>[INST]generate single Topics from the following text don't make sentence for topic generation,delimited by triple backticks.Output must in english.
list out the topics:
Topics:
```data:{self.extracted_text}```[/INST]"""
result = self.generate(prompt)
return result
except Exception as e:
logging.error(f"Error generating topics: {e}")
return ""
def generate_important_sentences(self,model) -> str:
"""
Extract important sentences from the pdf.
Returns:
str: Extracted important sentences.
"""
try:
if model == "OpenAI":
# Define a conversation between system and user
conversation = [
{"role": "system", "content": "You are a Sentence Extracter"},
{"role": "user", "content": f""" Extract Most important of the sentences from text.the text is given in triple backtics.
listout the sentences:
```{self.extracted_text}```
"""}
]
# Generate completion using ChatGPT model
response = self.client.chat.completions.create(
model="GPT-3",
messages=conversation,
temperature=0,
max_tokens=1000
)
# Get the generated topics message
message = response.choices[0].message.content
return message
elif model == "Mixtral":
task = "topics"
# Generate answer using Mixtral model
prompt = f"""<s>[INST] Extract Most important of the sentences from text.the text is given in triple backtics.
listout the sentences:
```{self.extracted_text}```[/INST]"""
result = self.generate(prompt)
return result
except Exception as e:
logging.error(f"Error Extracting Important Sentence: {e}")
return ""
def get_token_size(self,text, characters_per_token=4):
token_size = len(text) // characters_per_token
if len(text) % characters_per_token != 0:
token_size += 1
return token_size
def generate(self, task: str, temperature=0.9, top_p=0.95,
repetition_penalty=1.0) -> str:
"""
Generates text based on the prompt and pdf text.
Args:
prompt (str): The prompt for generating text.
transcribed_text (str): The pdf text for analysis.
temperature (float): Controls the randomness of the sampling. Default is 0.9.
max_new_tokens (int): Maximum number of tokens to generate. Default is 5000.
top_p (float): Nucleus sampling parameter. Default is 0.95.
repetition_penalty (float): Penalty for repeating the same token. Default is 1.0.
Returns:
str: Generated text.
"""
try:
temperature = float(temperature)
if temperature < 1e-2:
temperature = 1e-2
top_p = float(top_p)
characters_per_token = 2
token_size = self.get_token_size(self.extracted_text, characters_per_token)
# print("input_token",token_size)
output_token_size = 32768 - token_size
# print("output_token",output_token_size)
if token_size < 17000:
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=output_token_size,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
# Generate text using the mistral client
stream = self.mistral_client.text_generation(task, **generate_kwargs, stream=True, details=True, return_full_text=False)
output = ""
# Concatenate generated text
for response in stream:
output += response.token.text
return output.replace("</s>","")
else:
return "Out of token size limit"
except Exception as e:
logging.error(f"Error in text generation: {e}")
return "An error occurred during text generation."
def pdf_qa(self, question: str, model: str) -> str:
"""
Performs pdf question answering.
Args:
question (str): The question asked by the user.
model (str): The language model to be used ("OpenAI" or "Mixtral").
Returns:
str: Answer to the user's question.
"""
try:
if model == "OpenAI":
template = """you are the universal language expert .your task is analyze the given text and user ask any question about given text answer to the user question.otherwise reply i don't know.
extracted_text:{text}
user_question:{question}"""
prompt = PromptTemplate(template=template, input_variables=["text","question"])
llm_chain = LLMChain(prompt=prompt, verbose=True, llm=self.openai_llm)
# Run the language model chain
result = llm_chain.run({"text":self.extracted_text,"question":question})
return result
elif model == "Mixtral":
task = "pdf_qa"
# Generate answer using Mixtral model
prompt = "<s>"
prompt = f"""[INST] you are the german language and universal language expert .your task is analyze the given data and user ask any question about given data answer to the user question.your returning answer must in user's language.otherwise reply i don't know.
data:{self.extracted_text}
question:{question}[/INST]"""
prompt1 = f"[INST] {question} [/INST]"
pdfqa_prompt = prompt+prompt1
result = self.generate(pdfqa_prompt)
return result
except Exception as e:
logging.error(f"Error in video question answering: {e}")
return "An error occurred during video question answering."
def write_text_files(self, text: str, filename: str) -> None:
"""
Write text to a file.
Args:
text (str): Text to be written to the file.
filename (str): Name of the file.
"""
try:
file_path = f"{filename}.txt"
with open(file_path, 'w') as file:
# Write content to the file
file.write(text)
except Exception as e:
logging.error(f"Error writing text to file: {e}")
def save_audio_with_gtts(self, text: str, filename: str) -> str:
"""
Save audio file using Google Text-to-Speech (gTTS).
Args:
text (str): The text to be converted to speech.
filename (str): The name of the file to save.
Returns:
str: The filename of the saved audio file.
"""
try:
tts = gTTS(text=text, lang='en')
tts.save(filename)
logging.info(f"Audio saved successfully as {filename}")
return filename
except Exception as e:
logging.error(f"An error occurred while saving audio: {e}")
return None
def split_20_pages(self, pdf_path: str) -> int:
"""
Split a PDF into parts, with each part containing 20 pages or less.
Args:
pdf_path (str): The path to the PDF file.
Returns:
int: The number of parts created.
"""
def extract_text_from_pdf(pdf_path: str, start_page: int, end_page: int) -> str:
"""
Extract text from a range of pages in a PDF file.
Args:
pdf_path (str): The path to the PDF file.
start_page (int): The starting page number.
end_page (int): The ending page number.
Returns:
str: The extracted text.
"""
text = ""
with open(pdf_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
for page_num in range(start_page, end_page):
page = reader.pages[page_num]
text += page.extract_text()
return text
try:
# Assuming your PDF file is named 'your_pdf_file.pdf'
pdf_reader = PyPDF2.PdfReader(pdf_path)
num_pages = len(pdf_reader.pages)
total_pages = num_pages
desired_pages = 20
# Determine how many loops you need
num_loops = total_pages // desired_pages
remainder_pages = total_pages % desired_pages
for i in range(num_loops):
start_page = i * desired_pages
end_page = (i + 1) * desired_pages
text = extract_text_from_pdf(pdf_path, start_page, end_page)
# Do something with the extracted text, like saving to a file
with open(f'extracted_text_part_{i}.txt', 'w', encoding='utf-8') as text_file:
text_file.write(text)
# For the remaining pages
if remainder_pages > 0:
start_page = num_loops * desired_pages
end_page = total_pages
text = extract_text_from_pdf(pdf_path, start_page, end_page)
# Do something with the extracted text, like saving to a file
with open(f'extracted_text_part_{num_loops}.txt', 'w', encoding='utf-8') as text_file:
text_file.write(text)
return num_loops
except Exception as e:
logging.error(f"An error occurred while splitting PDF: {e}")
return 0
def main(self,input_path: str = None,model: str = None) -> tuple:
"""
Perform PDF analytics.
Args:
input_path (str): Input path for the File.
Returns:
tuple: Summary, important sentences, and topics.
"""
try:
# Download the video if input_path is provided, otherwise use the provided video path
pdf_reader = PyPDF2.PdfReader(input_path.name)
num_pages = len(pdf_reader.pages)
if input_path and num_pages > 20:
num_loops = self.split_20_pages(input_path.name)
elif num_pages < 20:
self._extract_text_from_pdfs(input_path.name)
num_loops = 1
overall_summary = "\n"
overall_important_sentences = "\n"
overall_topics = "\n"
for i in range(num_loops):
self._extract_text_from_pdfs(f"extracted_text_part_{i}.txt")
ordinal_suffix = "th" if 11 <= (i+1) % 100 <= 13 else {1: "st", 2: "nd", 3: "rd"}.get((i+1) % 10, "th")
text = f"{i+1}{ordinal_suffix} 20 pages Summary:\n\n"
summary = self.generate_summary(model)
overall_summary += text + summary +"\n\n"
important_sentences = self.generate_important_sentences(model)
important_sent_text = f"{i+1}{ordinal_suffix} 20 pages Important Sentence:\n\n"
overall_important_sentences += important_sent_text + important_sentences + "\n\n"
topics_text = f"{i+1}{ordinal_suffix} 20 pages Topics:\n\n"
topics = self.generate_topics(model)
overall_topics += topics_text + topics + "\n\n"
self.write_text_files(overall_summary,"Summary")
summary_voice = self.save_audio_with_gtts(overall_summary,"summary.mp3")
self.write_text_files(overall_important_sentences,"Important_Sentence")
important_sentences_voice = self.save_audio_with_gtts(overall_important_sentences,"important_sentences.mp3")
self.write_text_files(overall_topics,"Topics")
topics_voice = self.save_audio_with_gtts(overall_topics,"topics.mp3")
# Return the generated summary, important sentences, and topics
return overall_summary,overall_important_sentences,overall_topics,summary_voice,important_sentences_voice,topics_voice
except Exception as e:
# Log any errors that occur during video analytics
logging.error(f"Error in main function: {e}")
return "", "", ""
def file_show_status(self,filepath):
return "File Uploaded Successfully"
def gradio_interface(self):
with gr.Blocks(css="style.css",theme=gr.themes.Soft()) as demo:
gr.HTML("""<center><h1>PDF Analytics</h1></center>""")
with gr.Row():
with gr.Column(scale=0.70):
file_output = gr.Textbox(label="File Status")
with gr.Column(scale=0.30):
model_selection = gr.Dropdown(["OpenAI", "Mixtral"],label="Model",value="model")
with gr.Row():
upload_button = gr.UploadButton(
"Browse File",
file_types=[".pdf"]
)
with gr.Row():
submit_btn = gr.Button(value="Submit")
with gr.Tab("Summary"):
with gr.Row():
summary = gr.Textbox(show_label=False,lines=10)
with gr.Row():
summary_download = gr.DownloadButton(label="Download",value="Summary.txt",visible=True,size='lg',elem_classes="download_button")
with gr.Row():
summary_audio = gr.Audio(show_label= False,elem_classes='audio_class')
with gr.Tab("Important Sentences"):
with gr.Row():
Important_Sentences = gr.Textbox(show_label=False,lines=10)
with gr.Row():
sentence_download = gr.DownloadButton(label="Download",value="Important_Sentence.txt",visible=True,size='lg',elem_classes="download_button")
with gr.Row():
important_sentence_audio = gr.Audio(show_label = False,elem_classes='audio_class')
with gr.Tab("Topics"):
with gr.Row():
Topics = gr.Textbox(show_label=False,lines=10)
with gr.Row():
topics_download = gr.DownloadButton(label="Download",value="Topics.txt",visible=True,size='lg',elem_classes="download_button")
with gr.Row():
topics_audio = gr.Audio(show_label=False,elem_classes='audio_class')
with gr.Tab("PDF QA"):
with gr.Row():
with gr.Column(scale=0.70):
question = gr.Textbox(show_label=False,placeholder="Ask Your Questions...")
with gr.Column(scale=0.30):
model = gr.Dropdown(["OpenAI", "Mixtral"],show_label=False,value="model")
with gr.Row():
result = gr.Textbox(label='Answer',lines=10)
upload_button.upload(self.file_show_status,upload_button,file_output)
submit_btn.click(self.main,[upload_button,model_selection],[summary,Important_Sentences,Topics,summary_audio,important_sentence_audio,topics_audio])
question.submit(self.pdf_qa,[question,model],result)
demo.launch()
if __name__ == "__main__":
pdf_analytics = PDFAnalytics()
pdf_analytics.gradio_interface() |