Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,121 +1,130 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
|
4 |
-
os.
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
# Load
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
# Avoid Streamlit file watcher issues in Docker
|
4 |
+
os.environ["STREAMLIT_WATCHED_MODULES"] = ""
|
5 |
+
|
6 |
+
# Set a writable cache directory for Hugging Face models
|
7 |
+
os.environ["TRANSFORMERS_CACHE"] = "./hf_cache"
|
8 |
+
os.makedirs("./hf_cache", exist_ok=True)
|
9 |
+
|
10 |
+
# Set Streamlit-specific options to prevent permission errors
|
11 |
+
os.environ["STREAMLIT_HOME"] = os.getcwd()
|
12 |
+
os.environ["STREAMLIT_RUNTIME_METRICS_ENABLED"] = "false"
|
13 |
+
os.makedirs(".streamlit", exist_ok=True)
|
14 |
+
|
15 |
+
import streamlit as st
|
16 |
+
import torch
|
17 |
+
import joblib
|
18 |
+
import numpy as np
|
19 |
+
import random
|
20 |
+
from PIL import Image
|
21 |
+
from transformers import AutoTokenizer, AutoModel, ViTModel, ViTImageProcessor
|
22 |
+
|
23 |
+
# CPU device only
|
24 |
+
device = torch.device("cpu")
|
25 |
+
|
26 |
+
# Define Swahili VQA Model
|
27 |
+
class SwahiliVQAModel(torch.nn.Module):
|
28 |
+
def __init__(self, num_answers):
|
29 |
+
super().__init__()
|
30 |
+
self.vision_encoder = ViTModel.from_pretrained('google/vit-base-patch16-224-in21k')
|
31 |
+
self.text_encoder = AutoModel.from_pretrained("benjamin/roberta-base-wechsel-swahili")
|
32 |
+
self.fusion = torch.nn.Sequential(
|
33 |
+
torch.nn.Linear(768 + 768, 512),
|
34 |
+
torch.nn.ReLU(),
|
35 |
+
torch.nn.Dropout(0.3),
|
36 |
+
torch.nn.LayerNorm(512)
|
37 |
+
)
|
38 |
+
self.classifier = torch.nn.Linear(512, num_answers)
|
39 |
+
|
40 |
+
def forward(self, image, input_ids, attention_mask):
|
41 |
+
vision_outputs = self.vision_encoder(pixel_values=image)
|
42 |
+
image_feats = vision_outputs.last_hidden_state[:, 0, :]
|
43 |
+
text_outputs = self.text_encoder(input_ids=input_ids, attention_mask=attention_mask)
|
44 |
+
text_feats = text_outputs.last_hidden_state[:, 0, :]
|
45 |
+
combined = torch.cat([image_feats, text_feats], dim=1)
|
46 |
+
fused = self.fusion(combined)
|
47 |
+
return self.classifier(fused)
|
48 |
+
|
49 |
+
# Load label encoder
|
50 |
+
le = joblib.load("Vit_3895_label_encoder_best.pkl")
|
51 |
+
|
52 |
+
# Load model weights normally β no override
|
53 |
+
model = SwahiliVQAModel(num_answers=len(le.classes_)).to(device)
|
54 |
+
state_dict = torch.load("Vit_3895_best_model_epoch25.pth", map_location=device)
|
55 |
+
model.load_state_dict(state_dict)
|
56 |
+
model.eval()
|
57 |
+
|
58 |
+
# Load tokenizer and processor
|
59 |
+
tokenizer = AutoTokenizer.from_pretrained("benjamin/roberta-base-wechsel-swahili")
|
60 |
+
vit_processor = ViTImageProcessor.from_pretrained('google/vit-base-patch16-224-in21k')
|
61 |
+
|
62 |
+
# Streamlit UI
|
63 |
+
st.set_page_config(page_title="Swahili VQA", layout="wide")
|
64 |
+
st.title("π¦ Swahili Visual Question Answering (VQA)")
|
65 |
+
|
66 |
+
uploaded_image = st.file_uploader("π Pakia picha hapa:", type=["jpg", "jpeg", "png"])
|
67 |
+
|
68 |
+
def generate_random_color():
|
69 |
+
return f"rgb({random.randint(150, 255)}, {random.randint(80, 200)}, {random.randint(80, 200)})"
|
70 |
+
|
71 |
+
col1, col2 = st.columns([1, 2], gap="large")
|
72 |
+
|
73 |
+
with col1:
|
74 |
+
if uploaded_image:
|
75 |
+
st.image(uploaded_image, caption="Picha Iliyopakiwa", use_container_width=True)
|
76 |
+
st.markdown("<div style='margin-bottom: 25px;'></div>", unsafe_allow_html=True)
|
77 |
+
|
78 |
+
with col2:
|
79 |
+
st.markdown("<div style='padding-top: 15px;'>", unsafe_allow_html=True)
|
80 |
+
question = st.text_input("π¬Andika swali lako hapa:", key="question_input")
|
81 |
+
submit_button = st.button("π©Tuma")
|
82 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
83 |
+
|
84 |
+
if submit_button and uploaded_image and question:
|
85 |
+
with st.spinner("π Inachakata jibu..."):
|
86 |
+
image = Image.open(uploaded_image).convert("RGB")
|
87 |
+
image_tensor = vit_processor(images=image, return_tensors="pt")["pixel_values"]
|
88 |
+
|
89 |
+
inputs = tokenizer(question, max_length=128, padding="max_length", truncation=True, return_tensors="pt")
|
90 |
+
input_ids = inputs["input_ids"]
|
91 |
+
attention_mask = inputs["attention_mask"]
|
92 |
+
|
93 |
+
with torch.no_grad():
|
94 |
+
logits = model(image_tensor, input_ids, attention_mask)
|
95 |
+
probs = torch.softmax(logits, dim=1)
|
96 |
+
|
97 |
+
top_probs, top_indices = torch.topk(probs, 5)
|
98 |
+
decoded_answers = le.inverse_transform(top_indices.cpu().numpy()[0])
|
99 |
+
|
100 |
+
results = [
|
101 |
+
{"answer": ans, "confidence": round(prob * 100, 2)}
|
102 |
+
for ans, prob in zip(decoded_answers, top_probs[0].tolist())
|
103 |
+
]
|
104 |
+
|
105 |
+
results = sorted(results, key=lambda x: x["confidence"], reverse=True)
|
106 |
+
|
107 |
+
st.subheader("Majibu Yanayowezekana:")
|
108 |
+
max_confidence = max(result["confidence"] for result in results)
|
109 |
+
|
110 |
+
for i, pred in enumerate(results):
|
111 |
+
bar_width = (pred["confidence"] / max_confidence) * 70
|
112 |
+
color = generate_random_color()
|
113 |
+
st.markdown(
|
114 |
+
f"""
|
115 |
+
<div style="margin: 4px 0; padding: 2px 0; {'border-bottom: 1px solid rgba(150, 150, 150, 0.1);' if i < len(results)-1 else ''}">
|
116 |
+
<div style="font-size: 14px; font-weight: bold; margin-bottom: 2px;">
|
117 |
+
{pred['answer']}
|
118 |
+
</div>
|
119 |
+
<div style="display: flex; align-items: center; gap: 6px;">
|
120 |
+
<div style="width: {bar_width}%; height: 8px; border-radius: 3px; background: {color};"></div>
|
121 |
+
<div style="font-size: 13px; min-width: 45px;">
|
122 |
+
{pred['confidence']}%
|
123 |
+
</div>
|
124 |
+
</div>
|
125 |
+
</div>
|
126 |
+
""",
|
127 |
+
unsafe_allow_html=True
|
128 |
+
)
|
129 |
+
else:
|
130 |
+
st.info("π₯ Pakia picha na andika swali kisha bonyeza Tuma ili kupata jibu.")
|