sidcww commited on
Commit
7fef3dc
1 Parent(s): 838d77d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import gradio as gr
4
+ from langchain_core.prompts import PromptTemplate
5
+ from langchain_community.document_loaders import PyPDFLoader
6
+ from langchain_google_genai import ChatGoogleGenerativeAI
7
+ import google.generativeai as genai
8
+ from langchain.chains.question_answering import load_qa_chain
9
+ import torch
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ from PIL import Image
12
+ import io
13
+
14
+ # Configure Gemini API
15
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
16
+
17
+ # Load Mistral model
18
+ model_path = "nvidia/Mistral-NeMo-Minitron-8B-Base"
19
+ mistral_tokenizer = AutoTokenizer.from_pretrained(model_path)
20
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
21
+ dtype = torch.bfloat16
22
+ mistral_model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=dtype, device_map=device)
23
+
24
+ def process_pdf(file_path, question):
25
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
26
+ 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: """
27
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
28
+
29
+ pdf_loader = PyPDFLoader(file_path)
30
+ pages = pdf_loader.load_and_split()
31
+ context = "\n".join(str(page.page_content) for page in pages[:30])
32
+ stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
33
+ stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
34
+ return stuff_answer['output_text']
35
+
36
+ def process_image(image, question):
37
+ model = genai.GenerativeModel('gemini-pro-vision')
38
+ response = model.generate_content([image, question])
39
+ return response.text
40
+
41
+ def generate_mistral_followup(answer):
42
+ mistral_prompt = f"Based on this answer: {answer}\nGenerate a follow-up question:"
43
+ mistral_inputs = mistral_tokenizer.encode(mistral_prompt, return_tensors='pt').to(device)
44
+ with torch.no_grad():
45
+ mistral_outputs = mistral_model.generate(mistral_inputs, max_length=50)
46
+ mistral_output = mistral_tokenizer.decode(mistral_outputs[0], skip_special_tokens=True)
47
+ return mistral_output
48
+
49
+ def process_input(file, image, question):
50
+ try:
51
+ if file is not None:
52
+ gemini_answer = process_pdf(file.name, question)
53
+ elif image is not None:
54
+ gemini_answer = process_image(image, question)
55
+ else:
56
+ return "Please upload a PDF file or an image."
57
+
58
+ mistral_followup = generate_mistral_followup(gemini_answer)
59
+ combined_output = f"Gemini Answer: {gemini_answer}\n\nMistral Follow-up: {mistral_followup}"
60
+ return combined_output
61
+ except Exception as e:
62
+ return f"An error occurred: {str(e)}"
63
+
64
+ # Define Gradio Interface
65
+ with gr.Blocks() as demo:
66
+ gr.Markdown("# Multi-modal RAG Knowledge Retrieval using Gemini API and Mistral Model")
67
+
68
+ with gr.Row():
69
+ with gr.Column():
70
+ input_file = gr.File(label="Upload PDF File")
71
+ input_image = gr.Image(type="pil", label="Upload Image")
72
+ input_question = gr.Textbox(label="Ask about the document or image")
73
+
74
+ output_text = gr.Textbox(label="Answer - Combined Gemini and Mistral")
75
+
76
+ submit_button = gr.Button("Submit")
77
+ submit_button.click(fn=process_input, inputs=[input_file, input_image, input_question], outputs=output_text)
78
+
79
+ demo.launch()