ritampatra commited on
Commit
5f0ff3b
·
verified ·
1 Parent(s): faff94d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from llama_index import SimpleDirectoryReader, GPTSimpleVectorIndex, ServiceContext
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ from PyPDF2 import PdfReader
5
+
6
+ # Load tokenizer and model from HuggingFace (StableLM)
7
+ tokenizer = AutoTokenizer.from_pretrained("StabilityAI/stablelm-tuned-alpha-3b")
8
+ model = AutoModelForCausalLM.from_pretrained("StabilityAI/stablelm-tuned-alpha-3b")
9
+
10
+ # Create service context for the LLM
11
+ service_context = ServiceContext.from_defaults(
12
+ llm_predictor=(model, tokenizer), # Attach the model and tokenizer
13
+ chunk_size=1024
14
+ )
15
+
16
+ # Function to load PDF
17
+ def load_pdf(file):
18
+ reader = PdfReader(file.name)
19
+ text = ""
20
+ for page in reader.pages:
21
+ text += page.extract_text()
22
+ return text
23
+
24
+ # Function to create an index and query it
25
+ def chat_with_pdf(pdf, query):
26
+ # Read the PDF content
27
+ pdf_text = load_pdf(pdf)
28
+
29
+ # Use llama-index to create a document index
30
+ documents = [pdf_text]
31
+ index = GPTSimpleVectorIndex.from_documents(documents, service_context=service_context)
32
+
33
+ # Query the index
34
+ response = index.query(query)
35
+ return response.response
36
+
37
+ # Gradio interface
38
+ def chatbot(pdf, query):
39
+ if not pdf or not query:
40
+ return "Please upload a PDF and enter a query."
41
+
42
+ response = chat_with_pdf(pdf, query)
43
+ return response
44
+
45
+ # Define Gradio inputs and interface
46
+ pdf_input = gr.inputs.File(label="Upload your PDF")
47
+ query_input = gr.inputs.Textbox(label="Ask a question about the PDF")
48
+ output = gr.outputs.Textbox(label="Chatbot Response")
49
+
50
+ gr.Interface(fn=chatbot, inputs=[pdf_input, query_input], outputs=output, title="PDF Chatbot").launch()