Roberta2024 commited on
Commit
524a1b4
·
verified ·
1 Parent(s): a482575

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
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
+ from functools import lru_cache
14
+ import concurrent.futures
15
+ import pymupdf
16
+
17
+ # Configure Gemini API
18
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
19
+
20
+ # Load Mistral model (lazy loading)
21
+ model_path = "nvidia/Mistral-NeMo-Minitron-8B-Base"
22
+ mistral_tokenizer = None
23
+ mistral_model = None
24
+
25
+ def load_mistral_model():
26
+ global mistral_tokenizer, mistral_model
27
+ if mistral_tokenizer is None or mistral_model is None:
28
+ mistral_tokenizer = AutoTokenizer.from_pretrained(model_path)
29
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
30
+ dtype = torch.bfloat16
31
+ mistral_model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=dtype, device_map=device)
32
+
33
+ @lru_cache(maxsize=100)
34
+ def get_pdf_context(file_path):
35
+ doc = pymupdf.open(file_path)
36
+ text = ""
37
+ for page in doc:
38
+ text += page.get_text()
39
+ return text[:10000] # Limit context to first 10000 characters
40
+
41
+ async def process_pdf(file_path, question):
42
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
43
+ 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: """
44
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
45
+
46
+ context = get_pdf_context(file_path)
47
+ stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
48
+ stuff_answer = await stuff_chain.arun({"input_documents": [context], "question": question, "context": context})
49
+ return stuff_answer
50
+
51
+ async def process_image(image, question):
52
+ model = genai.GenerativeModel('gemini-pro-vision')
53
+ response = await model.generate_content_async([image, question])
54
+ return response.text
55
+
56
+ async def generate_mistral_followup(answer):
57
+ load_mistral_model()
58
+ mistral_prompt = f"Based on this answer: {answer}\nGenerate a follow-up question:"
59
+ mistral_inputs = mistral_tokenizer.encode(mistral_prompt, return_tensors='pt').to(mistral_model.device)
60
+ with torch.no_grad():
61
+ mistral_outputs = mistral_model.generate(mistral_inputs, max_length=50)
62
+ mistral_output = mistral_tokenizer.decode(mistral_outputs[0], skip_special_tokens=True)
63
+ return mistral_output
64
+
65
+ async def process_input(file, image, question):
66
+ try:
67
+ if file is not None:
68
+ gemini_answer = await process_pdf(file.name, question)
69
+ elif image is not None:
70
+ gemini_answer = await process_image(image, question)
71
+ else:
72
+ return "Please upload a PDF file or an image."
73
+
74
+ mistral_followup = await generate_mistral_followup(gemini_answer)
75
+ combined_output = f"Gemini Answer: {gemini_answer}\n\nMistral Follow-up: {mistral_followup}"
76
+ return combined_output
77
+ except Exception as e:
78
+ return f"An error occurred: {str(e)}"
79
+
80
+ # Gradio Interface
81
+ with gr.Blocks() as demo:
82
+ gr.Markdown("# Optimized Multi-modal RAG Knowledge Retrieval using Gemini API and Mistral Model")
83
+
84
+ with gr.Row():
85
+ with gr.Column():
86
+ input_file = gr.File(label="Upload PDF File")
87
+ input_image = gr.Image(type="pil", label="Upload Image")
88
+ input_question = gr.Textbox(label="Ask about the document or image")
89
+
90
+ output_text = gr.Textbox(label="Answer - Combined Gemini and Mistral")
91
+
92
+ submit_button = gr.Button("Submit")
93
+ submit_button.click(fn=lambda file, image, question: asyncio.run(process_input(file, image, question)),
94
+ inputs=[input_file, input_image, input_question],
95
+ outputs=output_text)
96
+
97
+ if __name__ == "__main__":
98
+ demo.launch()