Spaces:
Runtime error
Runtime error
Spencer525
commited on
Commit
•
f9ea741
1
Parent(s):
2d08031
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
from langchain_core.prompts import PromptTemplate
|
4 |
+
from langchain_community.document_loaders import PyPDFLoader
|
5 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
6 |
+
import google.generativeai as genai
|
7 |
+
from langchain.chains.question_answering import load_qa_chain
|
8 |
+
import torch
|
9 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
10 |
+
from PIL import Image
|
11 |
+
import io
|
12 |
+
from threading import Thread
|
13 |
+
from transformers import TextIteratorStreamer
|
14 |
+
|
15 |
+
# Configure Gemini API
|
16 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
17 |
+
|
18 |
+
# Load OpenELM model
|
19 |
+
checkpoint = "apple/OpenELM-270M"
|
20 |
+
checkpoint_tok = "meta-llama/Llama-2-7b-hf"
|
21 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint_tok)
|
22 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
23 |
+
torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
|
24 |
+
low_cpu_mem_usage = True if torch.cuda.is_available() else False
|
25 |
+
|
26 |
+
model = AutoModelForCausalLM.from_pretrained(checkpoint, torch_dtype=torch_dtype, trust_remote_code=True, low_cpu_mem_usage=low_cpu_mem_usage)
|
27 |
+
model.to(device)
|
28 |
+
|
29 |
+
# Adjust tokenizer settings
|
30 |
+
if tokenizer.pad_token is None:
|
31 |
+
tokenizer.pad_token = tokenizer.eos_token
|
32 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
33 |
+
|
34 |
+
# Define other settings
|
35 |
+
max_new_tokens = 250
|
36 |
+
repetition_penalty = 1.4
|
37 |
+
rtl = False
|
38 |
+
|
39 |
+
# Function to process PDF using Gemini API
|
40 |
+
def process_pdf(file_path, question):
|
41 |
+
model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
|
42 |
+
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: """
|
43 |
+
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
44 |
+
|
45 |
+
pdf_loader = PyPDFLoader(file_path)
|
46 |
+
pages = pdf_loader.load_and_split()
|
47 |
+
context = "\n".join(str(page.page_content) for page in pages[:200])
|
48 |
+
stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
|
49 |
+
stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
|
50 |
+
return stuff_answer['output_text']
|
51 |
+
|
52 |
+
# Function to process images using Gemini API
|
53 |
+
def process_image(image, question):
|
54 |
+
model = genai.GenerativeModel('gemini-pro-vision')
|
55 |
+
response = model.generate_content([image, question])
|
56 |
+
return response.text
|
57 |
+
|
58 |
+
# Function to generate follow-up using OpenELM model
|
59 |
+
def generate_openelm_followup(answer):
|
60 |
+
prompt = f"Based on this answer: {answer}\nGenerate a follow-up question:"
|
61 |
+
inputs = tokenizer([prompt], return_tensors='pt').input_ids.to(model.device)
|
62 |
+
|
63 |
+
# Streaming output using TextIteratorStreamer
|
64 |
+
decode_kwargs = dict(skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
65 |
+
streamer = TextIteratorStreamer(tokenizer, timeout=5., decode_kwargs=decode_kwargs)
|
66 |
+
|
67 |
+
generation_kwargs = dict(input_ids=inputs, streamer=streamer, max_new_tokens=max_new_tokens, repetition_penalty=repetition_penalty)
|
68 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
69 |
+
thread.start()
|
70 |
+
|
71 |
+
followup = ""
|
72 |
+
for new_text in streamer:
|
73 |
+
if new_text:
|
74 |
+
followup += new_text.replace(tokenizer.pad_token, "").replace(tokenizer.bos_token, "")
|
75 |
+
|
76 |
+
return followup
|
77 |
+
|
78 |
+
# Function to process input and generate output
|
79 |
+
def process_input(file, image, question):
|
80 |
+
try:
|
81 |
+
if file is not None:
|
82 |
+
gemini_answer = process_pdf(file.name, question)
|
83 |
+
elif image is not None:
|
84 |
+
gemini_answer = process_image(image, question)
|
85 |
+
else:
|
86 |
+
return "Please upload a PDF file or an image."
|
87 |
+
|
88 |
+
openelm_followup = generate_openelm_followup(gemini_answer)
|
89 |
+
combined_output = f"Gemini Answer: {gemini_answer}\n\nOpenELM Follow-up: {openelm_followup}"
|
90 |
+
return combined_output
|
91 |
+
except Exception as e:
|
92 |
+
return f"An error occurred: {str(e)}"
|
93 |
+
|
94 |
+
# Define Gradio Interface
|
95 |
+
with gr.Blocks() as demo:
|
96 |
+
gr.Markdown("# Multi-modal RAG Knowledge Retrieval using Gemini API and OpenELM Model")
|
97 |
+
|
98 |
+
with gr.Row():
|
99 |
+
with gr.Column():
|
100 |
+
input_file = gr.File(label="Upload PDF File")
|
101 |
+
input_image = gr.Image(type="pil", label="Upload Image")
|
102 |
+
input_question = gr.Textbox(label="Ask about the document or image")
|
103 |
+
|
104 |
+
output_text = gr.Textbox(label="Answer - Combined Gemini and OpenELM")
|
105 |
+
|
106 |
+
submit_button = gr.Button("Submit")
|
107 |
+
submit_button.click(fn=process_input, inputs=[input_file, input_image, input_question], outputs=output_text)
|
108 |
+
|
109 |
+
demo.launch()
|