Spaces:
Sleeping
Sleeping
swamisharan
commited on
Commit
•
b5e0972
1
Parent(s):
9858bef
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import torch
|
4 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
5 |
+
from langchain.embeddings import SentenceTransformerEmbeddings
|
6 |
+
from langchain.vectorstores import Chroma
|
7 |
+
from langchain.llms.huggingface_pipeline import HuggingFacePipeline
|
8 |
+
from langchain.chains import RetrievalQA
|
9 |
+
from langchain.document_loaders import PDFMinerLoader
|
10 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
11 |
+
from chromadb.config import Settings
|
12 |
+
|
13 |
+
# Initialize Chroma settings once
|
14 |
+
CHROMA_SETTINGS = Settings(
|
15 |
+
chroma_db_impl='duckdb+parquet',
|
16 |
+
persist_directory="db",
|
17 |
+
anonymized_telemetry=False
|
18 |
+
)
|
19 |
+
|
20 |
+
# Initialize the Chroma database on app start (assuming the database will be initialized only once)
|
21 |
+
def init_db_if_not_exists(pdf_path):
|
22 |
+
try:
|
23 |
+
# Check if the database exists and load it
|
24 |
+
db = Chroma(persist_directory=CHROMA_SETTINGS.persist_directory, client_settings=CHROMA_SETTINGS)
|
25 |
+
db.get_collection() # This line will raise an error if the collection doesn't exist
|
26 |
+
except Exception:
|
27 |
+
# If not, initialize the database
|
28 |
+
loader = PDFMinerLoader(pdf_path)
|
29 |
+
documents = loader.load()
|
30 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
31 |
+
texts = text_splitter.split_documents(documents)
|
32 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
33 |
+
db = Chroma.from_documents(texts, embeddings, persist_directory=CHROMA_SETTINGS.persist_directory)
|
34 |
+
db.persist()
|
35 |
+
|
36 |
+
# Load model and create pipeline once
|
37 |
+
checkpoint = "MBZUAI/LaMini-Flan-T5-783M"
|
38 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
39 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint, device_map="auto", torch_dtype=torch.float32)
|
40 |
+
llm_pipeline = HuggingFacePipeline(pipeline=pipeline("text2text-generation", model=base_model, tokenizer=tokenizer))
|
41 |
+
|
42 |
+
def process_answer(instruction):
|
43 |
+
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
44 |
+
vectordb = Chroma(persist_directory=CHROMA_SETTINGS.persist_directory, embedding_function=embeddings)
|
45 |
+
retriever = vectordb.as_retriever()
|
46 |
+
qa = RetrievalQA.from_chain_type(llm=llm_pipeline, chain_type="stuff", retriever=retriever)
|
47 |
+
generated_text = qa(instruction)
|
48 |
+
return generated_text["result"]
|
49 |
+
|
50 |
+
def chatbot(pdf_file, user_question):
|
51 |
+
if pdf_file: # Only initialize if a new PDF is uploaded
|
52 |
+
init_db_if_not_exists(pdf_file.name)
|
53 |
+
try:
|
54 |
+
answer = process_answer(user_question)
|
55 |
+
return answer
|
56 |
+
except Exception as e:
|
57 |
+
return f"An error occurred: {str(e)}"
|
58 |
+
|
59 |
+
# Create Gradio Interface
|
60 |
+
iface = gr.Interface(
|
61 |
+
fn=chatbot,
|
62 |
+
inputs=[gr.inputs.File(type="file", label="Upload your PDF"), gr.inputs.Textbox(lines=1, label="Ask a Question")],
|
63 |
+
outputs="text",
|
64 |
+
title="PDF Chatbot",
|
65 |
+
description="Upload a PDF and ask questions about its content.",
|
66 |
+
)
|
67 |
+
|
68 |
+
# Run the Gradio interface
|
69 |
+
iface.launch()
|