petchutney commited on
Commit
c34f72a
·
verified ·
1 Parent(s): 81bf298

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import PyPDF2
4
+
5
+ # Load the explainer model
6
+ explainer = pipeline("text2text-generation", model="google/flan-t5-base")
7
+
8
+ def extract_text_from_pdf(pdf_file):
9
+ text = ""
10
+ try:
11
+ with open(pdf_file.name, 'rb') as pdfFileObj:
12
+ pdfReader = PyPDF2.PdfReader(pdfFileObj)
13
+ for pageNum in range(len(pdfReader.pages)):
14
+ pageObj = pdfReader.pages[pageNum]
15
+ text += pageObj.extract_text()
16
+ except Exception as e:
17
+ return f"Error reading PDF: {e}"
18
+ return text
19
+
20
+ def process_and_explain(pdf_file, concept_to_explain):
21
+ if pdf_file is not None:
22
+ extracted_text = extract_text_from_pdf(pdf_file)
23
+ if "Error reading PDF" in extracted_text or not extracted_text.strip():
24
+ return "Could not extract text from the PDF. Please try another file."
25
+
26
+ prompt = f"Explain the concept of '{concept_to_explain}' based on this text: '{extracted_text[:1500]}...' in simple terms." # Limiting text for the model
27
+ explanation_result = explainer(prompt, max_length=300, do_sample=False)
28
+ explanation = explanation_result[0]["generated_text"]
29
+ return f"**Extracted Text Snippet:**\n{extracted_text[:500]}...\n\n**Explanation of '{concept_to_explain}':**\n{explanation}"
30
+ else:
31
+ return "Please upload a PDF file."
32
+
33
+ with gr.Blocks() as demo:
34
+ gr.Markdown("## Explain Concepts from Uploaded PDFs")
35
+ gr.Markdown("Upload a PDF, and then specify a concept you'd like explained based on its content.")
36
+
37
+ pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])
38
+ concept_input = gr.Textbox(label="Concept to Explain", placeholder="E.g., Climate Change")
39
+ explain_button = gr.Button("Explain Concept")
40
+ output_text = gr.Markdown(label="Explanation")
41
+
42
+ explain_button.click(
43
+ fn=process_and_explain,
44
+ inputs=[pdf_input, concept_input],
45
+ outputs=output_text
46
+ )
47
+
48
+ demo.launch()