Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from io import BytesIO
|
3 |
+
from PIL import Image
|
4 |
+
from transformers import ViltProcessor, ViltForQuestionAnswering
|
5 |
+
import requests
|
6 |
+
import torch
|
7 |
+
import torchvision
|
8 |
+
|
9 |
+
from langchain.prompts import PromptTemplate
|
10 |
+
from langchain.chains import LLMChain
|
11 |
+
from langchain.chat_models import ChatOpenAI
|
12 |
+
|
13 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
14 |
+
from huggingface_hub import hf_hub_download
|
15 |
+
|
16 |
+
from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor
|
17 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
18 |
+
import os
|
19 |
+
|
20 |
+
os.environ["OPENAI_API_KEY"] = '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'
|
21 |
+
llm = ChatOpenAI(temperature=0.2, model_name="gpt-3.5-turbo")
|
22 |
+
prompt = PromptTemplate(
|
23 |
+
input_variables=["question", "elements"],
|
24 |
+
template="""You are a helpful assistant that can answer question related to an image. You have the ability to see the image and answer questions about it.
|
25 |
+
I will give you a question and element about the image and you will answer the question.
|
26 |
+
\n\n
|
27 |
+
#Question: {question}
|
28 |
+
#Elements: {elements}
|
29 |
+
\n\n
|
30 |
+
Your structured response:""",
|
31 |
+
)
|
32 |
+
|
33 |
+
def convert_png_to_jpg(image):
|
34 |
+
rgb_image = image.convert('RGB')
|
35 |
+
byte_arr = BytesIO()
|
36 |
+
rgb_image.save(byte_arr, format='JPEG')
|
37 |
+
byte_arr.seek(0)
|
38 |
+
return Image.open(byte_arr)
|
39 |
+
|
40 |
+
def vilt(image, query):
|
41 |
+
processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
|
42 |
+
model = ViltForQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
|
43 |
+
encoding = processor(image, query, return_tensors="pt")
|
44 |
+
outputs = model(**encoding)
|
45 |
+
logits = outputs.logits
|
46 |
+
idx = logits.argmax(-1).item()
|
47 |
+
sol = model.config.id2label[idx]
|
48 |
+
return sol
|
49 |
+
|
50 |
+
def blip(image, query):
|
51 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
52 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large")
|
53 |
+
# unconditional image captioning
|
54 |
+
inputs = processor(image, return_tensors="pt")
|
55 |
+
|
56 |
+
out = model.generate(**inputs)
|
57 |
+
sol = processor.decode(out[0], skip_special_tokens=True)
|
58 |
+
return sol
|
59 |
+
|
60 |
+
def GIT(image, query):
|
61 |
+
processor = AutoProcessor.from_pretrained("microsoft/git-base-textvqa")
|
62 |
+
model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-textvqa")
|
63 |
+
|
64 |
+
# file_path = hf_hub_download(repo_id="nielsr/textvqa-sample", filename="bus.png", repo_type="dataset")
|
65 |
+
# image = Image.open(file_path).convert("RGB")
|
66 |
+
|
67 |
+
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
68 |
+
|
69 |
+
question = query
|
70 |
+
|
71 |
+
input_ids = processor(text=question, add_special_tokens=False).input_ids
|
72 |
+
input_ids = [processor.tokenizer.cls_token_id] + input_ids
|
73 |
+
input_ids = torch.tensor(input_ids).unsqueeze(0)
|
74 |
+
|
75 |
+
generated_ids = model.generate(pixel_values=pixel_values, input_ids=input_ids, max_length=50)
|
76 |
+
response = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
77 |
+
|
78 |
+
generated_ids_1 = model.generate(pixel_values=pixel_values, max_length=50)
|
79 |
+
generated_caption = processor.batch_decode(generated_ids_1, skip_special_tokens=True)[0]
|
80 |
+
|
81 |
+
return response[0] + " " + generated_caption
|
82 |
+
|
83 |
+
@st.cache_data(show_spinner="Processing image...")
|
84 |
+
def generate_table(uploaded_file):
|
85 |
+
image = Image.open(uploaded_file)
|
86 |
+
print("graph start")
|
87 |
+
model = Pix2StructForConditionalGeneration.from_pretrained('google/deplot')
|
88 |
+
processor = Pix2StructProcessor.from_pretrained('google/deplot')
|
89 |
+
print("graph start 1")
|
90 |
+
inputs = processor(images=image, text="Generate underlying data table of the figure below and give the text as well:", return_tensors="pt")
|
91 |
+
predictions = model.generate(**inputs, max_new_tokens=512)
|
92 |
+
print("end")
|
93 |
+
table = processor.decode(predictions[0], skip_special_tokens=True)
|
94 |
+
print(table)
|
95 |
+
return table
|
96 |
+
|
97 |
+
def process_query(image, query):
|
98 |
+
blip_sol = blip(image, query)
|
99 |
+
vilt_sol = vilt(image, query)
|
100 |
+
GIT_sol = GIT(image, query)
|
101 |
+
llm_sol = blip_sol + " " + vilt_sol + " " + GIT_sol
|
102 |
+
print(llm_sol)
|
103 |
+
chain = LLMChain(llm=llm, prompt=prompt)
|
104 |
+
response = chain.run(question=query, elements=llm_sol)
|
105 |
+
return response
|
106 |
+
|
107 |
+
def process_query_graph(data_table, query):
|
108 |
+
prompt = PromptTemplate(
|
109 |
+
input_variables=["question", "elements"],
|
110 |
+
template="""You are a helpful assistant capable of answering questions related to graph images.
|
111 |
+
You possess the ability to view the graph image and respond to inquiries about it.
|
112 |
+
I will provide you with a question and the associated data table of the graph, and you will answer the question
|
113 |
+
\n\n
|
114 |
+
#Question: {question}
|
115 |
+
#Elements: {elements}
|
116 |
+
\n\n
|
117 |
+
Your structured response:""",
|
118 |
+
)
|
119 |
+
chain = LLMChain(llm=llm, prompt=prompt)
|
120 |
+
response = chain.run(question=query, elements=data_table)
|
121 |
+
return response
|
122 |
+
|
123 |
+
def chart_with_Image():
|
124 |
+
st.header("Chat with Image", divider='rainbow')
|
125 |
+
uploaded_file = st.file_uploader('Upload your IMAGE', type=['png', 'jpeg', 'jpg'], key="imageUploader")
|
126 |
+
if uploaded_file is not None:
|
127 |
+
image = Image.open(uploaded_file)
|
128 |
+
|
129 |
+
# ViLT model only supports JPG images
|
130 |
+
if image.format == 'PNG':
|
131 |
+
image = convert_png_to_jpg(image)
|
132 |
+
|
133 |
+
st.image(image, caption='Uploaded Image.', width=300)
|
134 |
+
|
135 |
+
cancel_button = st.button('Cancel')
|
136 |
+
query = st.text_input('Ask a question to the IMAGE')
|
137 |
+
|
138 |
+
if query:
|
139 |
+
with st.spinner('Processing...'):
|
140 |
+
answer = process_query(image, query)
|
141 |
+
st.write(answer)
|
142 |
+
|
143 |
+
if cancel_button:
|
144 |
+
st.stop()
|
145 |
+
|
146 |
+
def chat_with_graph():
|
147 |
+
st.header("Chat with Graph", divider='rainbow')
|
148 |
+
uploaded_file = st.file_uploader('Upload your GRAPH', type=['png', 'jpeg', 'jpg'], key="graphUploader")
|
149 |
+
|
150 |
+
if uploaded_file is not None:
|
151 |
+
image = Image.open(uploaded_file)
|
152 |
+
|
153 |
+
# if image.format == 'PNG':
|
154 |
+
# image = convert_png_to_jpg(image)
|
155 |
+
|
156 |
+
# data_table = generate_table(uploaded_file)
|
157 |
+
|
158 |
+
st.image(image, caption='Uploaded Image.')
|
159 |
+
data_table = generate_table(uploaded_file)
|
160 |
+
cancel_button = st.button('Cancel')
|
161 |
+
query = st.text_input('Ask a question to the IMAGE')
|
162 |
+
if query:
|
163 |
+
with st.spinner('Processing...'):
|
164 |
+
answer = process_query_graph(data_table, query)
|
165 |
+
st.write(answer)
|
166 |
+
|
167 |
+
if cancel_button:
|
168 |
+
st.stop()
|
169 |
+
|
170 |
+
st.title("Image Querying App ")
|
171 |
+
option = st.selectbox(
|
172 |
+
"Who would you like to chart with?",
|
173 |
+
("Image", "Graph"),
|
174 |
+
index=None,
|
175 |
+
placeholder="Select contact method...",
|
176 |
+
)
|
177 |
+
|
178 |
+
st.write('You selected:', option)
|
179 |
+
if option == "Image":
|
180 |
+
chart_with_Image()
|
181 |
+
elif option == "Graph":
|
182 |
+
chat_with_graph()
|