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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import AzureOpenAI
2
+ from langchain_openai import AzureChatOpenAI
3
+ import os
4
+ import ffmpeg
5
+ from typing import List
6
+ from moviepy.editor import VideoFileClip
7
+ import nltk
8
+ from sklearn.feature_extraction.text import TfidfVectorizer
9
+ from langchain import HuggingFaceHub, PromptTemplate, LLMChain
10
+ from huggingface_hub import InferenceClient
11
+ import gradio as gr
12
+ import requests
13
+ from gtts import gTTS
14
+ import logging
15
+ from langchain.document_loaders import UnstructuredFileLoader
16
+ import os
17
+ import PyPDF2
18
+ nltk.download('punkt')
19
+ nltk.download('stopwords')
20
+
21
+
22
+ class PDFAnalytics:
23
+ """
24
+ Class for performing analytics on videos including transcription, summarization, topic generation,
25
+ and extraction of important sentences.
26
+ """
27
+
28
+ def __init__(self):
29
+ """
30
+ Initialize the VideoAnalytics object.
31
+
32
+ Args:
33
+ hf_token (str): Hugging Face API token.
34
+ """
35
+ # Initialize AzureOpenAI client
36
+ self.client = AzureOpenAI()
37
+
38
+ hf_token = os.getenv("HF_TOKEN")
39
+
40
+ self.mistral_client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1",token=hf_token)
41
+
42
+ # Initialize extracted_text variable
43
+ self.extracted_text = ""
44
+
45
+ self.openai_llm = AzureChatOpenAI(
46
+ deployment_name="ChatGPT",
47
+ )
48
+
49
+
50
+ # Configure logging settings
51
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
52
+
53
+ def _extract_text_from_pdfs(self, file_path: str) -> List[str]:
54
+ """Extract text content from PDF files.
55
+ Args:
56
+ file_paths (List[str]): List of file paths.
57
+ Returns:
58
+ List[str]: Extracted text from the PDFs.
59
+ """
60
+ try:
61
+
62
+ loader = UnstructuredFileLoader(file_path)
63
+ pages = loader.load()
64
+
65
+ self.extracted_text = pages[0].page_content
66
+ return pages[0].page_content
67
+ except Exception as e:
68
+ logging.error(f"Error pdf extraction: {e}")
69
+ return ""
70
+
71
+ def generate_summary(self,model) -> str:
72
+ """
73
+ Generate a summary of the pdf.
74
+
75
+ Returns:
76
+ str: Generated summary.
77
+ """
78
+ try:
79
+ if model == "OpenAI":
80
+ # Define a conversation between system and user
81
+ conversation = [
82
+ {"role": "system", "content": "You are a Summarizer"},
83
+ {"role": "user", "content": f"""summarize the following text delimited by triple backticks.Output must in english.within 100 words in detailed summary.
84
+ In two format of Outputs given below:
85
+ Abstractive Summary:
86
+ Extractive Summary:
87
+ ```{self.extracted_text}```
88
+ """}
89
+ ]
90
+ # Generate completion using ChatGPT model
91
+ response = self.client.chat.completions.create(
92
+ model="ChatGPT",
93
+ messages=conversation,
94
+ temperature=0,
95
+ max_tokens=1000
96
+ )
97
+ # Get the generated summary message
98
+ message = response.choices[0].message.content
99
+ return message
100
+
101
+ elif model == "Mixtral":
102
+ task = "summary"
103
+ # Generate answer using Mixtral model
104
+ prompt = f"""<s>[INST] summarize the following text delimited by triple backticks.Output must in english.within 100 words in detailed summary.
105
+ In two format of Outputs given below:
106
+ Abstractive Summary:
107
+ Extractive Summary:
108
+ ```data:{self.extracted_text}```[/INST]"""
109
+ result = self.generate(prompt)
110
+ return result
111
+
112
+ except Exception as e:
113
+ logging.error(f"Error generating video summary: {e}")
114
+ return ""
115
+
116
+
117
+ def generate_topics(self,model) -> str:
118
+ """
119
+ Generate topics from the pdf.
120
+
121
+ Returns:
122
+ str: Generated topics.
123
+ """
124
+ try:
125
+ if model == "OpenAI":
126
+ # Define a conversation between system and user
127
+ conversation = [
128
+ {"role": "system", "content": "You are a Topic Generator"},
129
+ {"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.
130
+ list out the topics:
131
+ Topics:
132
+ ```{self.extracted_text}```
133
+ """}
134
+ ]
135
+ # Generate completion using ChatGPT model
136
+ response = self.client.chat.completions.create(
137
+ model="ChatGPT",
138
+ messages=conversation,
139
+ temperature=0,
140
+ max_tokens=1000
141
+ )
142
+ # Get the generated topics message
143
+ message = response.choices[0].message.content
144
+ return message
145
+ elif model == "Mixtral":
146
+ task = "topics"
147
+ # Generate answer using Mixtral model
148
+ 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.
149
+ list out the topics:
150
+ Topics:
151
+ ```data:{self.extracted_text}```[/INST]"""
152
+ result = self.generate(prompt)
153
+ return result
154
+
155
+ except Exception as e:
156
+ logging.error(f"Error generating topics: {e}")
157
+ return ""
158
+
159
+ def generate_important_sentences(self,model) -> str:
160
+ """
161
+ Extract important sentences from the pdf.
162
+
163
+ Returns:
164
+ str: Extracted important sentences.
165
+ """
166
+ try:
167
+ if model == "OpenAI":
168
+ # Define a conversation between system and user
169
+ conversation = [
170
+ {"role": "system", "content": "You are a Sentence Extracter"},
171
+ {"role": "user", "content": f""" Extract Most important of the sentences from text.the text is given in triple backtics.
172
+ listout the sentences:
173
+
174
+ ```{self.extracted_text}```
175
+ """}
176
+ ]
177
+ # Generate completion using ChatGPT model
178
+ response = self.client.chat.completions.create(
179
+ model="ChatGPT",
180
+ messages=conversation,
181
+ temperature=0,
182
+ max_tokens=1000
183
+ )
184
+ # Get the generated topics message
185
+ message = response.choices[0].message.content
186
+ return message
187
+ elif model == "Mixtral":
188
+ task = "topics"
189
+ # Generate answer using Mixtral model
190
+ prompt = f"""<s>[INST] Extract Most important of the sentences from text.the text is given in triple backtics.
191
+ listout the sentences:
192
+
193
+ ```{self.extracted_text}```[/INST]"""
194
+ result = self.generate(prompt)
195
+ return result
196
+
197
+ except Exception as e:
198
+ logging.error(f"Error Extracting Important Sentence: {e}")
199
+ return ""
200
+
201
+
202
+
203
+ def get_token_size(self,text, characters_per_token=4):
204
+ token_size = len(text) // characters_per_token
205
+ if len(text) % characters_per_token != 0:
206
+ token_size += 1
207
+ return token_size
208
+
209
+
210
+ def generate(self, task: str, temperature=0.9, top_p=0.95,
211
+ repetition_penalty=1.0) -> str:
212
+ """
213
+ Generates text based on the prompt and pdf text.
214
+
215
+ Args:
216
+ prompt (str): The prompt for generating text.
217
+ transcribed_text (str): The pdf text for analysis.
218
+ temperature (float): Controls the randomness of the sampling. Default is 0.9.
219
+ max_new_tokens (int): Maximum number of tokens to generate. Default is 5000.
220
+ top_p (float): Nucleus sampling parameter. Default is 0.95.
221
+ repetition_penalty (float): Penalty for repeating the same token. Default is 1.0.
222
+
223
+ Returns:
224
+ str: Generated text.
225
+ """
226
+ try:
227
+ temperature = float(temperature)
228
+ if temperature < 1e-2:
229
+ temperature = 1e-2
230
+ top_p = float(top_p)
231
+ characters_per_token = 2
232
+ token_size = self.get_token_size(self.extracted_text, characters_per_token)
233
+ # print("input_token",token_size)
234
+
235
+ output_token_size = 32768 - token_size
236
+ # print("output_token",output_token_size)
237
+
238
+ if token_size < 17000:
239
+ generate_kwargs = dict(
240
+ temperature=temperature,
241
+ max_new_tokens=output_token_size,
242
+ top_p=top_p,
243
+ repetition_penalty=repetition_penalty,
244
+ do_sample=True,
245
+ seed=42,
246
+ )
247
+
248
+
249
+
250
+ # Generate text using the mistral client
251
+ stream = self.mistral_client.text_generation(task, **generate_kwargs, stream=True, details=True, return_full_text=False)
252
+ output = ""
253
+ # Concatenate generated text
254
+ for response in stream:
255
+ output += response.token.text
256
+ return output.replace("</s>","")
257
+ else:
258
+ return "Out of token size limit"
259
+ except Exception as e:
260
+ logging.error(f"Error in text generation: {e}")
261
+ return "An error occurred during text generation."
262
+
263
+ def pdf_qa(self, question: str, model: str) -> str:
264
+ """
265
+ Performs pdf question answering.
266
+
267
+ Args:
268
+ question (str): The question asked by the user.
269
+ model (str): The language model to be used ("OpenAI" or "Mixtral").
270
+
271
+ Returns:
272
+ str: Answer to the user's question.
273
+ """
274
+ try:
275
+ if model == "OpenAI":
276
+ 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.
277
+ extracted_text:{text}
278
+ user_question:{question}"""
279
+
280
+ prompt = PromptTemplate(template=template, input_variables=["text","question"])
281
+ llm_chain = LLMChain(prompt=prompt, verbose=True, llm=self.openai_llm)
282
+
283
+ # Run the language model chain
284
+ result = llm_chain.run({"text":self.extracted_text,"question":question})
285
+ return result
286
+
287
+ elif model == "Mixtral":
288
+ task = "pdf_qa"
289
+ # Generate answer using Mixtral model
290
+ prompt = "<s>"
291
+ 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.
292
+ data:{self.extracted_text}
293
+ question:{question}[/INST]"""
294
+
295
+ prompt1 = f"[INST] {question} [/INST]"
296
+ pdfqa_prompt = prompt+prompt1
297
+ result = self.generate(pdfqa_prompt)
298
+ return result
299
+ except Exception as e:
300
+ logging.error(f"Error in video question answering: {e}")
301
+ return "An error occurred during video question answering."
302
+
303
+
304
+ def write_text_files(self, text: str, filename: str) -> None:
305
+ """
306
+ Write text to a file.
307
+
308
+ Args:
309
+ text (str): Text to be written to the file.
310
+ filename (str): Name of the file.
311
+ """
312
+ try:
313
+ file_path = f"{filename}.txt"
314
+ with open(file_path, 'w') as file:
315
+ # Write content to the file
316
+ file.write(text)
317
+ except Exception as e:
318
+ logging.error(f"Error writing text to file: {e}")
319
+
320
+ def save_audio_with_gtts(self, text: str, filename: str) -> str:
321
+ """
322
+ Save audio file using Google Text-to-Speech (gTTS).
323
+
324
+ Args:
325
+ text (str): The text to be converted to speech.
326
+ filename (str): The name of the file to save.
327
+
328
+ Returns:
329
+ str: The filename of the saved audio file.
330
+ """
331
+ try:
332
+ tts = gTTS(text=text, lang='en')
333
+ tts.save(filename)
334
+ logging.info(f"Audio saved successfully as {filename}")
335
+ return filename
336
+ except Exception as e:
337
+ logging.error(f"An error occurred while saving audio: {e}")
338
+ return None
339
+
340
+ def split_20_pages(self, pdf_path: str) -> int:
341
+ """
342
+ Split a PDF into parts, with each part containing 20 pages or less.
343
+
344
+ Args:
345
+ pdf_path (str): The path to the PDF file.
346
+
347
+ Returns:
348
+ int: The number of parts created.
349
+ """
350
+ def extract_text_from_pdf(pdf_path: str, start_page: int, end_page: int) -> str:
351
+ """
352
+ Extract text from a range of pages in a PDF file.
353
+
354
+ Args:
355
+ pdf_path (str): The path to the PDF file.
356
+ start_page (int): The starting page number.
357
+ end_page (int): The ending page number.
358
+
359
+ Returns:
360
+ str: The extracted text.
361
+ """
362
+ text = ""
363
+ with open(pdf_path, 'rb') as file:
364
+ reader = PyPDF2.PdfReader(file)
365
+ for page_num in range(start_page, end_page):
366
+ page = reader.pages[page_num]
367
+ text += page.extract_text()
368
+ return text
369
+ try:
370
+ # Assuming your PDF file is named 'your_pdf_file.pdf'
371
+ pdf_reader = PyPDF2.PdfReader(pdf_path)
372
+ num_pages = len(pdf_reader.pages)
373
+ total_pages = num_pages
374
+ desired_pages = 20
375
+
376
+ # Determine how many loops you need
377
+ num_loops = total_pages // desired_pages
378
+ remainder_pages = total_pages % desired_pages
379
+
380
+ for i in range(num_loops):
381
+ start_page = i * desired_pages
382
+ end_page = (i + 1) * desired_pages
383
+ text = extract_text_from_pdf(pdf_path, start_page, end_page)
384
+ # Do something with the extracted text, like saving to a file
385
+ with open(f'extracted_text_part_{i}.txt', 'w', encoding='utf-8') as text_file:
386
+ text_file.write(text)
387
+
388
+ # For the remaining pages
389
+ if remainder_pages > 0:
390
+ start_page = num_loops * desired_pages
391
+ end_page = total_pages
392
+ text = extract_text_from_pdf(pdf_path, start_page, end_page)
393
+ # Do something with the extracted text, like saving to a file
394
+ with open(f'extracted_text_part_{num_loops}.txt', 'w', encoding='utf-8') as text_file:
395
+ text_file.write(text)
396
+ return num_loops
397
+ except Exception as e:
398
+ logging.error(f"An error occurred while splitting PDF: {e}")
399
+ return 0
400
+
401
+ def main(self,input_path: str = None,model: str = None) -> tuple:
402
+ """
403
+ Perform PDF analytics.
404
+
405
+ Args:
406
+ input_path (str): Input path for the File.
407
+
408
+ Returns:
409
+ tuple: Summary, important sentences, and topics.
410
+ """
411
+ try:
412
+ # Download the video if input_path is provided, otherwise use the provided video path
413
+ pdf_reader = PyPDF2.PdfReader(input_path.name)
414
+ num_pages = len(pdf_reader.pages)
415
+ if input_path and num_pages > 20:
416
+ num_loops = self.split_20_pages(input_path.name)
417
+ elif num_pages < 20:
418
+ num_loops = 1
419
+ overall_summary = "\n"
420
+ overall_important_sentences = "\n"
421
+ overall_topics = "\n"
422
+ for i in range(num_loops):
423
+ self._extract_text_from_pdfs(f"/content/extracted_text_part_{i}.txt")
424
+ text = f"{i+1} 20 pages Summary:\n\n"
425
+ summary = self.generate_summary(model)
426
+ overall_summary += text + summary +"\n\n"
427
+ important_sentences = self.generate_important_sentences(model)
428
+ important_sent_text = f"{i+1} 20 pages Important Sentence:\n\n"
429
+ overall_important_sentences += important_sent_text + important_sentences + "\n\n"
430
+ topics_text = f"{i+1} 20 pages Topics:\n\n"
431
+ topics = self.generate_topics(model)
432
+ overall_topics += topics_text + topics + "\n\n"
433
+
434
+ self.write_text_files(overall_summary,"Summary")
435
+ summary_voice = self.save_audio_with_gtts(overall_summary,"summary.mp3")
436
+ self.write_text_files(overall_important_sentences,"Important_Sentence")
437
+ important_sentences_voice = self.save_audio_with_gtts(overall_important_sentences,"important_sentences.mp3")
438
+ self.write_text_files(overall_topics,"Topics")
439
+ topics_voice = self.save_audio_with_gtts(overall_topics,"topics.mp3")
440
+
441
+ # Return the generated summary, important sentences, and topics
442
+ return overall_summary,overall_important_sentences,overall_topics,summary_voice,important_sentences_voice,topics_voice
443
+ except Exception as e:
444
+ # Log any errors that occur during video analytics
445
+ logging.error(f"Error in main function: {e}")
446
+ return "", "", ""
447
+
448
+ def file_show_status(self,filepath):
449
+ return filepath.name
450
+
451
+ def gradio_interface(self):
452
+ with gr.Blocks(css="style.css",theme=gr.themes.Soft()) as demo:
453
+ gr.HTML("""<center><h1>Video Analytics</h1></center>""")
454
+ with gr.Row():
455
+ with gr.Column(scale=0.70):
456
+ file_output = gr.Textbox(label="File Status")
457
+ with gr.Column(scale=0.30):
458
+ model_selection = gr.Dropdown(["OpenAI", "Mixtral"],label="Model",value="model")
459
+ with gr.Row():
460
+ upload_button = gr.UploadButton(
461
+ "Browse File",
462
+ file_types=[".pdf"]
463
+ )
464
+ with gr.Row():
465
+ submit_btn = gr.Button(value="Submit")
466
+ with gr.Tab("Summary"):
467
+ with gr.Row():
468
+ summary = gr.Textbox(show_label=False,lines=10)
469
+ with gr.Row():
470
+ summary_download = gr.DownloadButton(label="Download",value="Summary.txt",visible=True,size='lg',elem_classes="download_button")
471
+ with gr.Row():
472
+ summary_audio = gr.Audio(show_label= False,elem_classes='audio_class')
473
+ with gr.Tab("Important Sentences"):
474
+ with gr.Row():
475
+ Important_Sentences = gr.Textbox(show_label=False,lines=10)
476
+ with gr.Row():
477
+ sentence_download = gr.DownloadButton(label="Download",value="Important_Sentence.txt",visible=True,size='lg',elem_classes="download_button")
478
+ with gr.Row():
479
+ important_sentence_audio = gr.Audio(show_label = False,elem_classes='audio_class')
480
+ with gr.Tab("Topics"):
481
+ with gr.Row():
482
+ Topics = gr.Textbox(show_label=False,lines=10)
483
+ with gr.Row():
484
+ topics_download = gr.DownloadButton(label="Download",value="Topics.txt",visible=True,size='lg',elem_classes="download_button")
485
+ with gr.Row():
486
+ topics_audio = gr.Audio(show_label=False,elem_classes='audio_class')
487
+ with gr.Tab("PDF QA"):
488
+ with gr.Row():
489
+ with gr.Column(scale=0.70):
490
+ question = gr.Textbox(show_label=False,placeholder="Ask Your Questions...")
491
+ with gr.Column(scale=0.30):
492
+ model = gr.Dropdown(["OpenAI", "Mixtral"],show_label=False,value="model")
493
+ with gr.Row():
494
+ result = gr.Textbox(label='Answer',lines=10)
495
+ upload_button.upload(self.file_show_status,upload_button,file_output)
496
+ submit_btn.click(self.main,[upload_button,model_selection],[summary,Important_Sentences,Topics,summary_audio,important_sentence_audio,topics_audio])
497
+ question.submit(self.pdf_qa,[question,model],result)
498
+ demo.launch()
499
+
500
+ if __name__ == "__main__":
501
+ pdf_analytics = PDFAnalytics()
502
+ pdf_analytics.gradio_interface()