oke39 commited on
Commit
4710d1d
Β·
verified Β·
1 Parent(s): ce14da4

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ import torch
4
+ from transformers import AutoProcessor, LlavaForConditionalGeneration, BitsAndBytesConfig, CLIPProcessor, CLIPModel
5
+ from peft import PeftModel
6
+ from PIL import Image
7
+
8
+ st.set_page_config(page_title="Multimodal Risk Engine", page_icon="πŸ›‘οΈ", layout="wide")
9
+
10
+ # --- LOAD MODELS (Smart Caching) ---
11
+ @st.cache_resource
12
+ def load_models():
13
+ print("πŸ”„ Loading Models...")
14
+ device = "cuda" if torch.cuda.is_available() else "cpu"
15
+
16
+ # A. Stage 1 (CLIP)
17
+ clip_id = "openai/clip-vit-base-patch32"
18
+ clip_model = CLIPModel.from_pretrained(clip_id).to(device)
19
+ clip_processor = CLIPProcessor.from_pretrained(clip_id)
20
+
21
+ # B. Stage 2 (LLaVA)
22
+ model_id = "llava-hf/llava-1.5-7b-hf"
23
+
24
+ # CPU vs GPU Loading Logic
25
+ if device == "cuda":
26
+ bnb_config = BitsAndBytesConfig(
27
+ load_in_4bit=True, bnb_4bit_use_double_quant=True,
28
+ bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16
29
+ )
30
+ base_model = LlavaForConditionalGeneration.from_pretrained(
31
+ model_id, quantization_config=bnb_config, torch_dtype=torch.float16, device_map="auto"
32
+ )
33
+ else:
34
+ # Fallback for Free CPU Tier (Might be slow/crash but allows build verification)
35
+ base_model = LlavaForConditionalGeneration.from_pretrained(model_id)
36
+
37
+ adapter_id = "oke39/llava-v1.5-7b-hateful-memes-lora"
38
+ model = PeftModel.from_pretrained(base_model, adapter_id)
39
+ llava_processor = AutoProcessor.from_pretrained(model_id)
40
+
41
+ return clip_model, clip_processor, model, llava_processor
42
+
43
+ try:
44
+ clip_model, clip_processor, llava_model, llava_processor = load_models()
45
+ st.toast("βœ… System Ready", icon="πŸš€")
46
+ except Exception as e:
47
+ st.error(f"Hardware Error: {e}")
48
+ st.stop()
49
+
50
+ # --- PIPELINE ---
51
+ def stage_1_glance(image):
52
+ HATE_ANCHOR = ["hate speech, offensive content, racism, dangerous propaganda"]
53
+ inputs = clip_processor(text=HATE_ANCHOR, images=image, return_tensors="pt", padding=True).to(clip_model.device)
54
+ with torch.no_grad():
55
+ outputs = clip_model(**inputs)
56
+ probs = outputs.logits_per_image.softmax(dim=1)
57
+ return float(probs[0][0])
58
+
59
+ def stage_2_judge(image, text_context):
60
+ device = "cuda" if torch.cuda.is_available() else "cpu"
61
+ prompt = f"USER: <image>\nAnalyze this meme text: '{text_context}'. Is it hateful? Return JSON.\nASSISTANT:"
62
+ inputs = llava_processor(text=prompt, images=image, return_tensors="pt").to(device)
63
+
64
+ with torch.inference_mode():
65
+ output = llava_model.generate(**inputs, max_new_tokens=200)
66
+ response = llava_processor.decode(output[0], skip_special_tokens=True)
67
+ return response.split("ASSISTANT:")[-1].strip() if "ASSISTANT:" in response else response
68
+
69
+ # --- UI ---
70
+ st.title("πŸ›‘οΈ Multimodal Content Risk Engine")
71
+ st.markdown("### The 'Benign Confounder' Solver")
72
+
73
+ col1, col2 = st.columns([1, 1])
74
+
75
+ with col1:
76
+ uploaded_file = st.file_uploader("Upload Meme", type=["jpg", "png", "jpeg"])
77
+ text_input = st.text_input("Extracted Text", placeholder="Type visible text...")
78
+ if uploaded_file:
79
+ image = Image.open(uploaded_file).convert("RGB")
80
+ st.image(image, caption="User Upload", use_container_width=True)
81
+
82
+ with col2:
83
+ if uploaded_file and st.button("Analyze Risk", type="primary"):
84
+ with st.status("Running Pipeline...", expanded=True) as status:
85
+ st.write("πŸ‘οΈ **Stage 1: The 'Glance' (CLIP)**")
86
+ risk_score = stage_1_glance(image)
87
+ st.progress(min(risk_score, 1.0))
88
+
89
+ if risk_score < 0.22:
90
+ status.update(label="βœ… Auto-Approved", state="complete")
91
+ st.success("Verdict: BENIGN")
92
+ st.write(f"Risk Score: `{risk_score:.4f}`")
93
+ else:
94
+ st.warning(f"⚠️ Risk Detected ({risk_score:.4f})! Escalating...")
95
+ st.write("βš–οΈ **Stage 2: The 'Judge' (LLaVA)**")
96
+ verdict = stage_2_judge(image, text_input if text_input else "")
97
+ status.update(label="βœ… Done", state="complete")
98
+ st.json(verdict)