import os import gradio as gr import torch from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline from langchain_core.prompts import PromptTemplate from langchain_community.document_loaders import PyPDFLoader from langchain.chains.question_answering import load_qa_chain from langchain.llms import HuggingFacePipeline # Load Mistral model model_path = "nvidia/Mistral-NeMo-Minitron-8B-Base" mistral_tokenizer = AutoTokenizer.from_pretrained(model_path) device = 'cuda' if torch.cuda.is_available() else 'cpu' dtype = torch.bfloat16 mistral_model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=dtype, device_map=device) # Create a pipeline for text generation text_generation = pipeline( "text-generation", model=mistral_model, tokenizer=mistral_tokenizer, max_length=512, do_sample=True, temperature=0.7, ) # Create a HuggingFacePipeline to use with langchain mistral_pipeline = HuggingFacePipeline(pipeline=text_generation) def initialize(file_path, question): try: if os.path.exists(file_path): # Load and split the PDF pdf_loader = PyPDFLoader(file_path) pages = pdf_loader.load_and_split() # Extract context from the first 30 pages (or all if less than 30) context = "\n".join(str(page.page_content) for page in pages[:30]) # Create a prompt template prompt_template = """Answer the question as precisely 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"]) # Create a QA chain using the Mistral model qa_chain = load_qa_chain(mistral_pipeline, chain_type="stuff", prompt=prompt) # Run the chain result = qa_chain({"input_documents": pages, "question": question}, return_only_outputs=True) return result['output_text'] else: return "Error: Unable to process the document. Please ensure the PDF file is valid." except Exception as e: return f"An error occurred: {str(e)}" # 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 from Mistral") def pdf_qa(file, question): if file is None: return "Please upload a PDF file first." return initialize(file.name, question) # Create Gradio Interface gr.Interface( fn=pdf_qa, inputs=[input_file, input_question], outputs=output_text, title="PDF Question Answering using Mistral Model", description="Upload a PDF file and ask questions about its content." ).launch(share=True) # Added share=True here