PDF8BRAG / app.py
Spencer525's picture
Update app.py
d211841 verified
import os
import gradio as gr
import asyncio
from langchain_core.prompts import PromptTemplate
from langchain_community.output_parsers.rail_parser import GuardrailsOutputParser
from langchain_community.document_loaders import PyPDFLoader
from langchain_google_genai import ChatGoogleGenerativeAI
import google.generativeai as genai
from langchain.chains.question_answering import load_qa_chain
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
# Gemini initialization and PDF QA function
async def initialize_gemini(file_path, question):
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
not contained in the context, say "answer not available in context" \n\n
Context: \n {context}?\n
Question: \n {question} \n
Answer:
"""
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
if os.path.exists(file_path):
pdf_loader = PyPDFLoader(file_path)
pages = pdf_loader.load_and_split()
context = "\n".join(str(page.page_content) for page in pages[:100])
stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
return stuff_answer['output_text']
else:
return "Error: Unable to process the document. Please ensure the PDF file is valid."
# Mistral model initialization
def initialize_mistral():
model_path = "nvidia/Mistral-NeMo-Minitron-8B-Base"
tokenizer = AutoTokenizer.from_pretrained(model_path)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
dtype = torch.bfloat16
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=dtype) # Removed device_map parameter
return tokenizer, model
# Mistral text generation function
def generate_mistral_text(prompt, tokenizer, model):
inputs = tokenizer.encode(prompt, return_tensors='pt').to(model.device)
outputs = model.generate(inputs, max_length=100)
return tokenizer.decode(outputs[0])
# Initialize Mistral model
mistral_tokenizer, mistral_model = initialize_mistral()
# Gradio interface function
async def pdf_qa(file, question):
gemini_answer = await initialize_gemini(file.name, question)
mistral_prompt = f"Based on this answer: '{gemini_answer}', provide a brief summary:"
mistral_summary = generate_mistral_text(mistral_prompt, mistral_tokenizer, mistral_model)
return f"Gemini Answer:\n{gemini_answer}\n\nMistral Summary:\n{mistral_summary}"
# Define Gradio Interface
input_file = gr.File(label="Upload PDF File")
input_question = gr.Textbox(label="Ask about the document")
output_text = gr.Textbox(label="Answer and Summary")
# Create Gradio Interface
gr.Interface(
fn=pdf_qa,
inputs=[input_file, input_question],
outputs=output_text,
title="PDF Question Answering System with Gemini and Mistral",
description="Upload a PDF file, ask questions about the content, and get answers from Gemini with a summary from Mistral."
).launch()