dhanush1601 commited on
Commit
305f201
·
verified ·
1 Parent(s): e066a40

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -64
app.py CHANGED
@@ -1,69 +1,82 @@
1
- # Install dependencies (run once in Colab)
2
- # !pip install PyPDF2 langchain faiss-cpu sentence-transformers transformers accelerate gradio
3
-
4
- import gradio as gr
5
  from PyPDF2 import PdfReader
 
 
 
6
  from langchain.text_splitter import RecursiveCharacterTextSplitter
7
  from langchain.embeddings import HuggingFaceEmbeddings
8
  from langchain.vectorstores import FAISS
9
- from langchain.chains import ConversationalRetrievalChain
10
  from langchain.llms import HuggingFacePipeline
11
- from transformers import pipeline
12
-
13
- # ---------- Upload PDF and process ----------
14
- def process_pdf(file):
15
- pdf_reader = PdfReader(file.name)
16
- text = ""
17
- for page in pdf_reader.pages:
18
- page_text = page.extract_text()
19
- if page_text:
20
- text += page_text
21
-
22
- # Split text into smaller chunks
23
- splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50)
24
- chunks = splitter.split_text(text)
25
-
26
- # Create embeddings
27
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
28
- vectorstore = FAISS.from_texts(chunks, embeddings)
29
-
30
- # Setup HuggingFace LLM
31
- generator = pipeline(
32
- "text-generation",
33
- model="bigscience/bloom-560m", # public, free
34
- max_new_tokens=256,
35
- temperature=0.7
36
- )
37
- llm = HuggingFacePipeline(pipeline=generator)
38
-
39
- # Build conversational retrieval chain
40
- chatbot = ConversationalRetrievalChain.from_llm(
41
- llm,
42
- retriever=vectorstore.as_retriever()
43
- )
44
-
45
- return chatbot
46
-
47
- # ---------- Chat function ----------
48
- def ask_pdf(chatbot, question):
49
- result = chatbot({"question": question, "chat_history": []})
50
- return result["answer"]
51
-
52
- # ---------- Gradio Interface ----------
53
- chatbot_instance = None # global to store loaded PDF
54
-
55
- def gradio_interface(file, question):
56
- global chatbot_instance
57
- if chatbot_instance is None:
58
- chatbot_instance = process_pdf(file)
59
- return ask_pdf(chatbot_instance, question)
60
-
61
- iface = gr.Interface(
62
- fn=gradio_interface,
63
- inputs=[gr.File(label="Upload PDF"), gr.Textbox(label="Ask a question")],
64
- outputs=gr.Textbox(label="Assistant Answer"),
65
- title="🤖 PDF Chat Assistant",
66
- description="Upload a PDF and ask questions from it."
67
- )
68
-
69
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # rag_upload_app_local.py
2
+ import os
 
 
3
  from PyPDF2 import PdfReader
4
+ import gradio as gr
5
+
6
+ # LangChain imports
7
  from langchain.text_splitter import RecursiveCharacterTextSplitter
8
  from langchain.embeddings import HuggingFaceEmbeddings
9
  from langchain.vectorstores import FAISS
 
10
  from langchain.llms import HuggingFacePipeline
11
+ from langchain.chains import RetrievalQA
12
+
13
+ # Transformers imports
14
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
15
+
16
+ # --- CONFIG ---
17
+ EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
18
+ LOCAL_MODEL = "google/flan-t5-base" # lightweight model
19
+
20
+ # Load local HuggingFace model
21
+ tokenizer = AutoTokenizer.from_pretrained(LOCAL_MODEL)
22
+ model = AutoModelForSeq2SeqLM.from_pretrained(LOCAL_MODEL)
23
+ pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer, max_length=512)
24
+ llm = HuggingFacePipeline(pipeline=pipe)
25
+
26
+ def process_document(file):
27
+ try:
28
+ if file is None:
29
+ return None, "⚠️ Please upload a document."
30
+
31
+ # Extract text from PDF
32
+ text = ""
33
+ reader = PdfReader(file)
34
+ for page in reader.pages:
35
+ page_text = page.extract_text()
36
+ if page_text:
37
+ text += page_text + "\n"
38
+
39
+ if not text.strip():
40
+ return None, "⚠️ No text could be extracted. Try another PDF."
41
+
42
+ # Split text into chunks
43
+ splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
44
+ chunks = splitter.split_text(text)
45
+
46
+ # Create embeddings + FAISS index
47
+ embedder = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
48
+ db = FAISS.from_texts(chunks, embedder)
49
+
50
+ # Create retriever + QA chain
51
+ retriever = db.as_retriever(search_kwargs={"k": 4})
52
+ qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever)
53
+
54
+ return qa, f"✅ Document processed successfully with {len(chunks)} chunks!"
55
+
56
+ except Exception as e:
57
+ return None, f"❌ Error: {str(e)}"
58
+
59
+ def answer_question(qa, question):
60
+ if qa is None:
61
+ return "Please upload and process a document first."
62
+ return qa.run(question)
63
+
64
+ with gr.Blocks() as demo:
65
+ gr.Markdown("## 📄 PDF CHAT ASSISSTANT")
66
+
67
+ with gr.Row():
68
+ file_input = gr.File(label="Upload PDF Document", type="filepath")
69
+ status = gr.Textbox(label="Status", interactive=False, lines=6) # 🔹 bigger
70
+
71
+ process_btn = gr.Button("Process Document")
72
+
73
+ with gr.Row():
74
+ question = gr.Textbox(label="Ask a Question", lines=3, placeholder="Type your question here...") # 🔹 taller
75
+ answer = gr.Textbox(label="Answer", lines=8) # 🔹 taller answer box
76
+
77
+ qa_state = gr.State()
78
+
79
+ process_btn.click(fn=process_document, inputs=file_input, outputs=[qa_state, status])
80
+ question.submit(fn=answer_question, inputs=[qa_state, question], outputs=answer)
81
+
82
+ demo.launch()