vikenkd commited on
Commit
024ec0b
·
1 Parent(s): f87758d

fix: update and complete app

Browse files
Files changed (4) hide show
  1. README.md +1 -1
  2. requirements.txt +11 -10
  3. src/app.py +61 -24
  4. src/infer.py +90 -0
README.md CHANGED
@@ -6,7 +6,7 @@ colorTo: indigo
6
  sdk: streamlit
7
  app_file: src/app.py
8
  python_version: 3.9
9
- models: [OpenGVLab/Mini-InternVL-Chat-2B-V1-5]
10
  pinned: false
11
  ---
12
 
 
6
  sdk: streamlit
7
  app_file: src/app.py
8
  python_version: 3.9
9
+ models: ["google/vit-base-patch16-224-in21k", "bert-base-uncased", "vikenkd/vqa-llm"]
10
  pinned: false
11
  ---
12
 
requirements.txt CHANGED
@@ -1,15 +1,16 @@
1
  torch==2.3.1
2
  torchvision
3
- cython
4
- matplotlib
5
- numpy
6
- scipy
7
- pyyaml
8
- packaging
9
- pycocotools
10
- tensorboardx
11
- h5py
 
12
  opencv-python
13
-
14
  streamlit
15
  pillow # for PIL
 
1
  torch==2.3.1
2
  torchvision
3
+ transformers
4
+ sentence_transformers
5
+ # cython
6
+ # matplotlib
7
+ # scipy
8
+ # pyyaml
9
+ # packaging
10
+ # pycocotools
11
+ # tensorboardx
12
+ # h5py
13
  opencv-python
14
+ numpy
15
  streamlit
16
  pillow # for PIL
src/app.py CHANGED
@@ -1,9 +1,53 @@
1
  import streamlit as st
 
 
 
 
2
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
 
4
 
 
 
5
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  st.title("📝 Visual Question Answering Project", )
8
 
9
  width_head = """
@@ -67,32 +111,25 @@ if image != None:
67
  with col1:
68
  question = st.text_area("Enter text:", placeholder="What is your question?")
69
  with col2:
70
- st.image(image, caption="Uploaded Image.", use_column_width=True)
 
 
 
 
 
 
71
  submitted = st.form_submit_button("Submit")
72
 
73
  st.markdown('</div>', unsafe_allow_html=True)
74
 
 
75
 
76
- # if not openai_api_key:
77
- # st.info("Please add your OpenAI API key to continue.")
78
- # elif submitted:
79
- # generate_response(text)
80
-
81
-
82
- # if uploaded_file and question and not anthropic_api_key:
83
- # st.info("Please add your Anthropic API key to continue.")
84
-
85
- # if uploaded_file and question and anthropic_api_key:
86
- # article = uploaded_file.read().decode()
87
- # prompt = f"""{anthropic.HUMAN_PROMPT} Here's an article:\n\n
88
- # {article}\n\n\n\n{question}{anthropic.AI_PROMPT}"""
89
-
90
- # client = anthropic.Client(api_key=anthropic_api_key)
91
- # response = client.completions.create(
92
- # prompt=prompt,
93
- # stop_sequences=[anthropic.HUMAN_PROMPT],
94
- # model="claude-v1", #"claude-2" for Claude 2 model
95
- # max_tokens_to_sample=100,
96
- # )
97
- # st.write("### Answer")
98
- # st.write(response.completion)
 
1
  import streamlit as st
2
+ import numpy as np
3
+ import pandas as pd
4
+ import torch
5
+
6
  from PIL import Image
7
+ from transformers import AutoTokenizer, AutoFeatureExtractor, AutoModel
8
+ from infer import InfenceTest
9
+
10
+ ## Read file all of class
11
+
12
+
13
+
14
+ # Inititalize model
15
+ model_name = "vikenkd/vqa-llm"
16
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
17
+ # Load the model and tokenizer
18
+ model = AutoModel.from_pretrained(model_name)
19
+ model = model.to(device)
20
+
21
+ # Load tokenize
22
+ visual_feature_extractor_name = "google/vit-base-patch16-224-in21k"
23
+ textual_feature_extractor_name = "bert-base-uncased"
24
+
25
+ ## Text
26
+ tokenizer = AutoTokenizer.from_pretrained(textual_feature_extractor_name)
27
+ text_encoder = AutoModel.from_pretrained(textual_feature_extractor_name)
28
+ for p in text_encoder.parameters():
29
+ p.requires_grad = False
30
 
31
+ ## Image processor
32
+ image_processor = AutoFeatureExtractor.from_pretrained(visual_feature_extractor_name)
33
+ image_encoder = AutoModel.from_pretrained(visual_feature_extractor_name)
34
 
35
+ for p in image_encoder.parameters():
36
+ p.requires_grad = False
37
 
38
 
39
+ image_encoder = image_encoder.to(device)
40
+ text_encoder = text_encoder.to(device)
41
+
42
+ ## Initialize class
43
+ infer_encoding = InfenceTest(image_encoder,
44
+ text_encoder,
45
+ tokenizer,
46
+ image_encoder,
47
+ device)
48
+
49
+ # Custom Website App for deploying that model
50
+
51
  st.title("📝 Visual Question Answering Project", )
52
 
53
  width_head = """
 
111
  with col1:
112
  question = st.text_area("Enter text:", placeholder="What is your question?")
113
  with col2:
114
+ image = st.image(image, caption="Uploaded Image.", use_column_width=True)
115
+ if not image or not question:
116
+ if not image:
117
+ st.info("Please upload your image.")
118
+ elif not question:
119
+ st.info("Please add your question.")
120
+
121
  submitted = st.form_submit_button("Submit")
122
 
123
  st.markdown('</div>', unsafe_allow_html=True)
124
 
125
+ inverse_labels = None
126
 
127
+ if submitted:
128
+ encoding_status = infer_encoding.encoding(quesiton = quesiton, image = image)
129
+ answer = infer_encoding.infer(model= model,
130
+ inputs_require= encoding_status,
131
+ top_k= 10)
132
+ st.write("### Answer")
133
+ st.write(inverse_labels[answer["answer"]])
134
+ st.write(" - With answer's probability is ")
135
+ st.write(answer["probs"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/infer.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from PIL import Image
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ # def infer():
8
+ # pass
9
+
10
+ class InfenceTest:
11
+
12
+ def __init__(self,
13
+ image_encoder,
14
+ text_encoder,
15
+ tokenizer,
16
+ image_processor,
17
+ # batch_size,
18
+ device):
19
+
20
+ self.image_encoder = image_encoder
21
+ self.text_encoder = text_encoder
22
+ self.image_processor = image_processor
23
+ self.tokenizer = tokenizer
24
+ # self.batch_size = batch_size
25
+
26
+ self.device = device
27
+
28
+
29
+ def __len__(self):
30
+ return len(self.df)
31
+
32
+ def encoding(self, question, image):
33
+
34
+ image_file = image
35
+ question = question
36
+ # full_path = self.type_data + "/images/" + image_file
37
+ # source_image = os.path.join(os.getcwd(), full_path)
38
+ image = Image.open(image_file).convert("RGB")
39
+
40
+ image_inputs = self.image_processor(image, return_tensors="pt")
41
+ image_inputs = {k:v.to(self.device) for k,v in image_inputs.items()}
42
+ image_outputs = self.image_encoder(**image_inputs)
43
+ image_embedding = image_outputs.pooler_output
44
+ image_embedding = image_embedding.view(-1)
45
+ image_embedding = image_embedding.detach()
46
+
47
+ text_inputs = self.tokenizer(question, return_tensors="pt")
48
+ text_inputs = {k:v.to(self.device) for k,v in text_inputs.items()}
49
+ text_outputs = self.text_encoder(**text_inputs)
50
+ text_embedding = text_outputs.pooler_output # You can experiment with this or raw CLS embedding below
51
+ text_embedding = text_embedding.view(-1)
52
+ text_embedding = text_embedding.detach()
53
+
54
+ encoding={}
55
+ encoding["image_emb"] = image_embedding
56
+ encoding["question_emb"] = text_embedding
57
+
58
+ return encoding
59
+
60
+ def infer(self, model, inputs_require, top_k: int = 10):
61
+
62
+ inputs = {
63
+ 'image_emb': inputs_require[0],
64
+ 'question_emb': inputs_require[1]
65
+ }
66
+
67
+ with torch.no_grad():
68
+ outputs = model(**inputs)
69
+
70
+ # Apply softmax to get probabilities
71
+ probabilities = F.softmax(outputs, dim=1)
72
+ # Get top 10 probabilities and their indices for each example in the batch
73
+
74
+ top_probabilities, top_indices = torch.topk(probabilities, k=top_k, dim=1)
75
+ # print(top_indices.shape)
76
+ top_indices = top_indices.detach().cpu().numpy()
77
+
78
+ probs = torch.max(outputs.softmax(dim=1), dim=-1)[0].detach().cpu().numpy()
79
+ outputs = outputs.argmax(-1)
80
+ logits = outputs.detach().cpu().numpy()
81
+
82
+ return {
83
+ "answer": logits,
84
+ "probs": probs,
85
+ "topk" : top_indices,
86
+ "topk_probs" : top_probabilities
87
+ }
88
+
89
+
90
+