m7mdal7aj commited on
Commit
c183786
1 Parent(s): 125214f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -223
app.py CHANGED
@@ -13,236 +13,23 @@ from my_model.object_detection import detect_and_draw_objects
13
  from my_model.captioner.image_captioning import get_caption
14
  from my_model.gen_utilities import free_gpu_resources
15
  from my_model.KBVQA import KBVQA, prepare_kbvqa_model
 
16
 
17
 
18
 
19
- def answer_question(caption, detected_objects_str, question, model):
20
 
21
- answer = model.generate_answer(question, caption, detected_objects_str)
22
- return answer
23
-
24
-
25
- # Sample images (assuming these are paths to your sample images)
26
- sample_images = ["Files/sample1.jpg", "Files/sample2.jpg", "Files/sample3.jpg",
27
- "Files/sample4.jpg", "Files/sample5.jpg", "Files/sample6.jpg",
28
- "Files/sample7.jpg"]
29
-
30
-
31
-
32
- def analyze_image(image, model):
33
-
34
- img = copy.deepcopy(image) # we dont wanna apply changes to the original image
35
- caption = model.get_caption(img)
36
- image_with_boxes, detected_objects_str = model.detect_objects(img)
37
- st.text("I am ready, let's talk!")
38
- free_gpu_resources()
39
-
40
- return caption, detected_objects_str, image_with_boxes
41
-
42
-
43
- def image_qa_app(kbvqa):
44
- if 'images_data' not in st.session_state:
45
- st.session_state['images_data'] = {}
46
-
47
- # Display sample images as clickable thumbnails
48
- st.write("Choose from sample images:")
49
- cols = st.columns(len(sample_images))
50
- for idx, sample_image_path in enumerate(sample_images):
51
- with cols[idx]:
52
- image = Image.open(sample_image_path)
53
- st.image(image, use_column_width=True)
54
- if st.button(f'Select Sample Image {idx + 1}', key=f'sample_{idx}'):
55
- process_new_image(sample_image_path, image, kbvqa)
56
-
57
- # Image uploader
58
- uploaded_image = st.file_uploader("Or upload an Image", type=["png", "jpg", "jpeg"])
59
- if uploaded_image is not None:
60
- process_new_image(uploaded_image.name, Image.open(uploaded_image), kbvqa)
61
-
62
- # Display and interact with each uploaded/selected image
63
- for image_key, image_data in st.session_state['images_data'].items():
64
- st.image(image_data['image'], caption=f'Uploaded Image: {image_key[-11:]}', use_column_width=True)
65
- if not image_data['analysis_done']:
66
- st.text("Cool image, please click 'Analyze Image'..")
67
- if st.button('Analyze Image', key=f'analyze_{image_key}'):
68
- caption, detected_objects_str, image_with_boxes = analyze_image(image_data['image'], kbvqa) # we can use the image_with_boxes later if we want to show it.
69
- image_data['caption'] = caption
70
- image_data['detected_objects_str'] = detected_objects_str
71
- image_data['analysis_done'] = True
72
-
73
- # Initialize qa_history for each image
74
- qa_history = image_data.get('qa_history', [])
75
-
76
- if image_data['analysis_done']:
77
- question = st.text_input(f"Ask a question about this image ({image_key[-11:]}):", key=f'question_{image_key}')
78
- if st.button('Get Answer', key=f'answer_{image_key}'):
79
- if question not in [q for q, _ in qa_history]:
80
- answer = answer_question(image_data['caption'], image_data['detected_objects_str'], question, kbvqa)
81
- qa_history.append((question, answer))
82
- image_data['qa_history'] = qa_history
83
- else:
84
- st.info("This question has already been asked.")
85
-
86
- # Display Q&A history for each image
87
- for q, a in qa_history:
88
- st.text(f"Q: {q}\nA: {a}\n")
89
-
90
-
91
- def process_new_image(image_key, image, kbvqa):
92
- """Process a new image and update the session state."""
93
- if image_key not in st.session_state['images_data']:
94
- st.session_state['images_data'][image_key] = {
95
- 'image': image,
96
- 'caption': '',
97
- 'detected_objects_str': '',
98
- 'qa_history': [],
99
- 'analysis_done': False
100
- }
101
-
102
- def run_inference():
103
- st.title("Run Inference")
104
- st.write("Please note that this is not a general purpose model, it is specifically trained on OK-VQA dataset and is designed to give direct and short answers to the given questions.")
105
-
106
- method = st.selectbox(
107
- "Choose a method:",
108
- ["Fine-Tuned Model", "In-Context Learning (n-shots)"],
109
- index=0
110
- )
111
-
112
- detection_model = st.selectbox(
113
- "Choose a model for objects detection:",
114
- ["yolov5", "detic"],
115
- index=1 # "detic" is selected by default
116
- )
117
-
118
- default_confidence = 0.2 if detection_model == "yolov5" else 0.4
119
- confidence_level = st.slider(
120
- "Select minimum detection confidence level",
121
- min_value=0.1,
122
- max_value=0.9,
123
- value=default_confidence,
124
- step=0.1
125
- )
126
-
127
- if 'model_settings' not in st.session_state:
128
- st.session_state['model_settings'] = {'detection_model': detection_model, 'confidence_level': confidence_level}
129
-
130
- settings_changed = (st.session_state['model_settings']['detection_model'] != detection_model or
131
- st.session_state['model_settings']['confidence_level'] != confidence_level)
132
-
133
- need_model_reload = settings_changed and 'kbvqa' in st.session_state and st.session_state['kbvqa'] is not None
134
-
135
- if need_model_reload:
136
- st.text("Model Settings have changed, please reload the model, this will take no time :)")
137
-
138
- button_label = "Reload Model" if need_model_reload else "Load Model"
139
-
140
- if method == "Fine-Tuned Model":
141
- if 'kbvqa' not in st.session_state:
142
- st.session_state['kbvqa'] = None
143
-
144
- if st.button(button_label):
145
-
146
- free_gpu_resources()
147
- if st.session_state['kbvqa'] is not None:
148
- if not settings_changed:
149
- st.write("Model already loaded.")
150
- else:
151
- free_gpu_resources()
152
- detection_model = st.session_state['model_settings']['detection_model']
153
- confidence_level = st.session_state['model_settings']['confidence_level']
154
- prepare_kbvqa_model(detection_model, only_reload_detection_model=True) # only reload detection model with new settings
155
- st.session_state['kbvqa'].detection_confidence = confidence_level
156
- free_gpu_resources()
157
- else:
158
- st.text("Loading the model will take no more than a few minutes . .")
159
- st.session_state['kbvqa'] = prepare_kbvqa_model(detection_model)
160
- st.session_state['kbvqa'].detection_confidence = confidence_level
161
- st.session_state['model_settings'] = {'detection_model': detection_model, 'confidence_level': confidence_level}
162
- st.write("Model is ready for inference.")
163
- free_gpu_resources()
164
-
165
-
166
-
167
- if st.session_state['kbvqa']:
168
- display_model_settings()
169
- display_session_state()
170
- image_qa_app(st.session_state['kbvqa'])
171
-
172
- else:
173
- st.write('Model is not ready yet, will be updated later.')
174
-
175
-
176
- def display_model_settings():
177
- st.write("### Current Model Settings:")
178
- st.table(pd.DataFrame(st.session_state['model_settings'], index=[0]))
179
-
180
- def display_session_state():
181
- st.write("### Current Session State:")
182
- # Convert session state to a list of dictionaries, each representing a row
183
- data = [{'Key': key, 'Value': str(value)} for key, value in st.session_state.items()]
184
- # Create a DataFrame from the list
185
- df = pd.DataFrame(data)
186
- st.table(df)
187
-
188
-
189
-
190
-
191
-
192
- # Main function
193
  def main():
194
 
195
-
196
- st.sidebar.title("Navigation")
197
- selection = st.sidebar.radio("Go to", ["Home", "Dataset Analysis", "Finetuning and Evaluation Results", "Run Inference", "Dissertation Report", "Code"])
198
- st.sidebar.write("More Pages will follow .. ")
199
-
200
- if selection == "Home":
201
- st.title("MultiModal Learning for Knowledg-Based Visual Question Answering")
202
- st.write("""This application is an interactive element of the project and prepared by Mohammed Alhaj as part of the dissertation for Masters degree in Artificial Intelligence at the University of Bath.
203
- Further details will be updated later""")
204
-
205
- elif selection == "Dissertation Report":
206
- st.title("Dissertation Report")
207
- st.write("Click the link below to view the PDF.")
208
- # Example to display a link to a PDF
209
- st.download_button(
210
- label="Download PDF",
211
- data=open("Files/Dissertation Report.pdf", "rb"),
212
- file_name="example.pdf",
213
- mime="application/octet-stream"
214
- )
215
-
216
-
217
- elif selection == "Evaluation Results":
218
- st.title("Evaluation Results")
219
- st.write("This is a Place Holder until the contents are uploaded.")
220
-
221
-
222
- elif selection == "Dataset Analysis":
223
- st.title("OK-VQA Dataset Analysis")
224
- st.write("This is a Place Holder until the contents are uploaded.")
225
-
226
- elif selection == "Finetuning and Evaluation Results":
227
- st.title("Finetuning and Evaluation Results")
228
- st.write("This is a Place Holder until the contents are uploaded.")
229
-
230
-
231
- elif selection == "Run Inference":
232
- run_inference()
233
-
234
- elif selection == "Code":
235
- st.title("Code")
236
- st.markdown("You can view the code for this project on the Hugging Face Space file page.")
237
- st.markdown("[View Code](https://huggingface.co/spaces/m7mdal7aj/Mohammed_Alhaj_PlayGround/tree/main)", unsafe_allow_html=True)
238
-
239
- elif selection == "More Pages will follow .. ":
240
- st.title("Staye Tuned")
241
- st.write("This is a Place Holder until the contents are uploaded.")
242
-
243
-
244
-
245
 
 
246
 
247
  if __name__ == "__main__":
248
  main()
 
13
  from my_model.captioner.image_captioning import get_caption
14
  from my_model.gen_utilities import free_gpu_resources
15
  from my_model.KBVQA import KBVQA, prepare_kbvqa_model
16
+ from my_model.utilities.st_utils import UIManager, StateManager
17
 
18
 
19
 
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def main():
22
 
23
+ ui_manager = UIManager()
24
+ selection = ui_manager.display_sidebar()
25
+ ui_manager.display_selected_page("Home")
26
+ ui_manager.display_selected_page("Dataset Analysis")
27
+ ui_manager.display_selected_page("Finetuning and Evaluation Results")
28
+ ui_manager.display_selected_page("Run Inference")
29
+ ui_manager.display_selected_page("Code")
30
+ ui_manager.display_selected_page("More Pages will follow .. ")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+
33
 
34
  if __name__ == "__main__":
35
  main()