Spencer525 commited on
Commit
0d99f80
·
verified ·
1 Parent(s): 3ecf4d0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -0
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import base64
4
+ import torch
5
+ import gradio as gr
6
+ import google.generativeai as genai
7
+ from PIL import Image
8
+ from langchain_core.prompts import PromptTemplate
9
+ from langchain_community.document_loaders import PyPDFLoader
10
+ from langchain_google_genai import ChatGoogleGenerativeAI
11
+ from langchain.chains.question_answering import load_qa_chain
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM, LlavaNextForConditionalGeneration, LlavaNextProcessor
13
+ from pypdf import PdfReader
14
+ from doctr.io import DocumentFile
15
+ from doctr.models import ocr_predictor
16
+ import chromadb
17
+ from chromadb.utils import embedding_functions
18
+ from chromadb.utils.data_loaders import ImageLoader
19
+
20
+ # Configure Gemini API
21
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
22
+
23
+ # Load Mistral model
24
+ model_path = "nvidia/Mistral-NeMo-Minitron-8B-Base"
25
+ mistral_tokenizer = AutoTokenizer.from_pretrained(model_path)
26
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
27
+ dtype = torch.bfloat16
28
+ mistral_model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=dtype, device_map=device)
29
+
30
+ # Load OCR model
31
+ ocr_model = ocr_predictor(
32
+ "db_resnet50",
33
+ "crnn_mobilenet_v3_large",
34
+ pretrained=True,
35
+ assume_straight_pages=True,
36
+ )
37
+
38
+ # Load Llava model for image description
39
+ if torch.cuda.is_available():
40
+ processor = LlavaNextProcessor.from_pretrained("llava-hf/llava-v1.6-mistral-7b-hf")
41
+ vision_model = LlavaNextForConditionalGeneration.from_pretrained(
42
+ "llava-hf/llava-v1.6-mistral-7b-hf",
43
+ torch_dtype=torch.float16,
44
+ low_cpu_mem_usage=True,
45
+ load_in_4bit=True,
46
+ )
47
+
48
+ def extract_images(pdf_path):
49
+ images = []
50
+ pdf_document = DocumentFile.from_pdf(pdf_path)
51
+ for page in range(len(pdf_document)):
52
+ page_images = pdf_document.get_page_images(page)
53
+ images.extend(page_images)
54
+ return images
55
+
56
+ def get_image_description(image):
57
+ torch.cuda.empty_cache()
58
+ prompt = "[INST] <image>\nDescribe the image in a sentence [/INST]"
59
+ inputs = processor(prompt, image, return_tensors="pt").to(device)
60
+ output = vision_model.generate(**inputs, max_new_tokens=100)
61
+ return processor.decode(output[0], skip_special_tokens=True)
62
+
63
+ def extract_text_with_ocr(pdf_path):
64
+ pdf_doc = DocumentFile.from_pdf(pdf_path)
65
+ result = ocr_model(pdf_doc)
66
+ return "\n".join([block.text for page in result.pages for block in page.blocks])
67
+
68
+ def get_vectordb(text, images):
69
+ client = chromadb.EphemeralClient()
70
+ loader = ImageLoader()
71
+ sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(
72
+ model_name="multi-qa-mpnet-base-dot-v1"
73
+ )
74
+
75
+ text_collection = client.get_or_create_collection(
76
+ name="text_db",
77
+ embedding_function=sentence_transformer_ef,
78
+ )
79
+ image_collection = client.get_or_create_collection(
80
+ name="image_db",
81
+ embedding_function=sentence_transformer_ef,
82
+ data_loader=loader,
83
+ )
84
+
85
+ # Add text to vector database
86
+ text_collection.add(
87
+ ids=["1"],
88
+ documents=[text],
89
+ )
90
+
91
+ # Add images to vector database
92
+ for i, image in enumerate(images):
93
+ img_description = get_image_description(image)
94
+ image_collection.add(
95
+ ids=[f"img_{i}"],
96
+ documents=[img_description],
97
+ metadatas=[{"image": image_to_bytes(image)}],
98
+ )
99
+
100
+ return client
101
+
102
+ def image_to_bytes(image):
103
+ buffered = io.BytesIO()
104
+ image.save(buffered, format="PNG")
105
+ return base64.b64encode(buffered.getvalue()).decode()
106
+
107
+ def process_pdf(file_path):
108
+ # Extract text using OCR
109
+ text = extract_text_with_ocr(file_path)
110
+
111
+ # Extract images
112
+ images = extract_images(file_path)
113
+
114
+ # Create vector database
115
+ vectordb = get_vectordb(text, images)
116
+
117
+ return vectordb, text, images
118
+
119
+ def answer_question(vectordb, question):
120
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
121
+ prompt_template = """Answer the question as precisely as possible using the provided context. If the answer is
122
+ not contained in the context, say "answer not available in context" \n\n
123
+ Context: \n {context}?\n
124
+ Question: \n {question} \n
125
+ Answer:
126
+ """
127
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
128
+
129
+ # Query text database
130
+ text_collection = vectordb.get_collection("text_db")
131
+ text_results = text_collection.query(query_texts=[question], n_results=1)
132
+
133
+ # Query image database
134
+ image_collection = vectordb.get_collection("image_db")
135
+ image_results = image_collection.query(query_texts=[question], n_results=1)
136
+
137
+ context = f"Text: {text_results['documents'][0][0]}\nImage: {image_results['documents'][0][0]}"
138
+
139
+ stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
140
+ stuff_answer = stuff_chain({"input_documents": [context], "question": question}, return_only_outputs=True)
141
+ gemini_answer = stuff_answer['output_text']
142
+
143
+ # Use Mistral model for additional text generation
144
+ mistral_prompt = f"Based on this answer: {gemini_answer}\nGenerate a follow-up question:"
145
+ mistral_inputs = mistral_tokenizer.encode(mistral_prompt, return_tensors='pt').to(device)
146
+ with torch.no_grad():
147
+ mistral_outputs = mistral_model.generate(mistral_inputs, max_length=50)
148
+ mistral_output = mistral_tokenizer.decode(mistral_outputs[0], skip_special_tokens=True)
149
+
150
+ combined_output = f"Gemini Answer: {gemini_answer}\n\nMistral Follow-up: {mistral_output}"
151
+ return combined_output
152
+
153
+ def pdf_qa(file, question):
154
+ if file is None:
155
+ return "Please upload a PDF file first."
156
+
157
+ vectordb, text, images = process_pdf(file.name)
158
+ return answer_question(vectordb, question)
159
+
160
+ # Define Gradio Interface
161
+ input_file = gr.File(label="Upload PDF File")
162
+ input_question = gr.Textbox(label="Ask about the document")
163
+ output_text = gr.Textbox(label="Answer - Combined Gemini and Mistral")
164
+
165
+ # Create Gradio Interface
166
+ gr.Interface(
167
+ fn=pdf_qa,
168
+ inputs=[input_file, input_question],
169
+ outputs=output_text,
170
+ title="Advanced PDF Analysis and QA System",
171
+ description="Upload a PDF file and ask questions about the content, including text and images."
172
+ ).launch()