File size: 2,343 Bytes
ae38eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import os
import gradio as gr
import asyncio
from langchain_core.prompts import PromptTemplate
from langchain_community.document_loaders import PyPDFLoader
from langchain.chains.question_answering import load_qa_chain
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

# Load Mistral model
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, device_map=device)

async def initialize(file_path, question):
    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[:30])
        
        # Prepare input for Mistral model
        input_text = prompt.format(context=context, question=question)
        inputs = tokenizer.encode(input_text, return_tensors='pt').to(device)
        
        # Generate the output
        with torch.no_grad():
            outputs = model.generate(inputs, max_length=500)  # Adjust max_length as needed
        
        # Decode and return the output
        answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
        return answer
    else:
        return "Error: Unable to process the document. Please ensure the PDF file is valid."

# 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 - Mistral Model")

async def pdf_qa(file, question):
    answer = await initialize(file.name, question)
    return answer

# Create Gradio Interface
gr.Interface(
    fn=pdf_qa,
    inputs=[input_file, input_question],
    outputs=output_text,
    title="RAG Knowledge Retrieval using Mistral Model",
    description="Upload a PDF file and ask questions about the content."
).launch()