PDF_Analytics / app.py
robertselvam's picture
Update app.py
7bc7501 verified
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()