rocky250 commited on
Commit
dceedff
Β·
verified Β·
1 Parent(s): 201c11b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +440 -0
app.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MHMisinfo β€” Mental Health Misinformation Detector
3
+ Gradio Space: paste a YouTube URL β†’ fetch metadata + transcripts β†’ run 4-stream SeTa-Attention model β†’ show verdict
4
+ """
5
+
6
+ import os, re, json, sys, warnings
7
+ warnings.filterwarnings("ignore")
8
+
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import gradio as gr
14
+ from dataclasses import dataclass
15
+ from typing import Dict, List, Optional
16
+ from huggingface_hub import hf_hub_download
17
+
18
+ # ── YouTube helpers ────────────────────────────────────────────────────────────
19
+ from googleapiclient.discovery import build as yt_build
20
+ from youtube_transcript_api import YouTubeTranscriptApi, NoTranscriptFound, TranscriptsDisabled
21
+
22
+ # ── Model + Data (inline, no src/ import needed) ──────────────────────────────
23
+ import re as _re
24
+
25
+ TAG_SPLIT_RE = _re.compile(r"[\s,]+")
26
+ TEXT_RE = _re.compile(r"[A-Za-z0-9']+")
27
+
28
+ @dataclass
29
+ class Vocab:
30
+ token_to_idx: Dict[str, int]
31
+ idx_to_token: List[str]
32
+ pad_token: str = "<pad>"
33
+ unk_token: str = "<unk>"
34
+
35
+ @property
36
+ def pad_idx(self): return self.token_to_idx[self.pad_token]
37
+ @property
38
+ def unk_idx(self): return self.token_to_idx[self.unk_token]
39
+
40
+ def encode(self, tokens, max_len):
41
+ ids = [self.token_to_idx.get(t, self.unk_idx) for t in tokens]
42
+ if len(ids) >= max_len: return ids[:max_len]
43
+ return ids + [self.pad_idx] * (max_len - len(ids))
44
+
45
+ @staticmethod
46
+ def from_serializable(obj):
47
+ return Vocab(token_to_idx=obj["token_to_idx"],
48
+ idx_to_token=obj["idx_to_token"],
49
+ pad_token=obj.get("pad_token","<pad>"),
50
+ unk_token=obj.get("unk_token","<unk>"))
51
+
52
+ def tokenize_tags(text):
53
+ if not isinstance(text, str): return []
54
+ cleaned = text.replace("#"," ")
55
+ return [t for t in TAG_SPLIT_RE.split(cleaned.lower()) if t]
56
+
57
+ def tokenize_text(text):
58
+ if not isinstance(text, str): return []
59
+ return [t.lower() for t in TEXT_RE.findall(text)]
60
+
61
+
62
+ # ── Model Architecture (identical to src/model.py) ────────────────────────────
63
+ class SeTaAttention(nn.Module):
64
+ def __init__(self, input_dim, attn_dim, dropout=0.1):
65
+ super().__init__()
66
+ self.proj = nn.Linear(input_dim, attn_dim)
67
+ self.sem_query = nn.Parameter(torch.randn(attn_dim))
68
+ self.task_query = nn.Parameter(torch.randn(attn_dim))
69
+ self.out = nn.Linear(input_dim * 2, input_dim)
70
+ self.dropout = nn.Dropout(dropout)
71
+
72
+ def _attend(self, h, query, mask):
73
+ proj = torch.tanh(self.proj(h))
74
+ scores = torch.matmul(proj, query)
75
+ scores = scores.masked_fill(~mask, -1e9)
76
+ weights = torch.softmax(scores, dim=1)
77
+ return torch.sum(h * weights.unsqueeze(-1), dim=1)
78
+
79
+ def forward(self, h, mask):
80
+ sem = self._attend(h, self.sem_query, mask)
81
+ task = self._attend(h, self.task_query, mask)
82
+ return self.dropout(torch.tanh(self.out(torch.cat([sem, task], dim=-1))))
83
+
84
+
85
+ class StreamEncoder(nn.Module):
86
+ def __init__(self, vocab_size, emb_dim, hidden_dim, attn_dim, proj_dim, mlp_dim, dropout=0.2):
87
+ super().__init__()
88
+ self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
89
+ self.gru = nn.GRU(emb_dim, hidden_dim, batch_first=True, bidirectional=True)
90
+ self.attn = SeTaAttention(hidden_dim*2, attn_dim, dropout=dropout)
91
+ self.proj = nn.Sequential(
92
+ nn.Linear(hidden_dim*2, mlp_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(mlp_dim, proj_dim)
93
+ )
94
+ self.dropout = nn.Dropout(dropout)
95
+
96
+ def forward(self, x):
97
+ mask = x != 0
98
+ emb = self.dropout(self.embedding(x))
99
+ h, _ = self.gru(emb)
100
+ attn_vec = self.attn(h, mask)
101
+ proj = self.dropout(torch.tanh(self.proj(attn_vec)))
102
+ return attn_vec, proj
103
+
104
+
105
+ class MultiStreamModel(nn.Module):
106
+ def __init__(self, vocab_sizes, num_classes, emb_dim=128, hidden_dim=128, attn_dim=128,
107
+ proj_dim=128, mlp_dim=256, dropout=0.2, include_tags_ccm=False, per_modality_trust=False):
108
+ super().__init__()
109
+ self.include_tags_ccm = include_tags_ccm
110
+ self.per_modality_trust = per_modality_trust
111
+ self.num_classes = num_classes
112
+ h_dim = hidden_dim * 2
113
+ self.encoders = nn.ModuleDict({
114
+ "tags": StreamEncoder(vocab_sizes["tags"], emb_dim, hidden_dim, attn_dim, proj_dim, mlp_dim, dropout),
115
+ "text": StreamEncoder(vocab_sizes["text"], emb_dim, hidden_dim, attn_dim, proj_dim, mlp_dim, dropout),
116
+ "audio_transcript": StreamEncoder(vocab_sizes["audio_transcript"], emb_dim, hidden_dim, attn_dim, proj_dim, mlp_dim, dropout),
117
+ "video_transcript": StreamEncoder(vocab_sizes["video_transcript"], emb_dim, hidden_dim, attn_dim, proj_dim, mlp_dim, dropout),
118
+ })
119
+ ccm_dim = 3 + (3 if include_tags_ccm else 0)
120
+ trust_in = h_dim + ccm_dim
121
+ if per_modality_trust:
122
+ self.trust_mlps = nn.ModuleDict({k: self._make_mlp(trust_in, mlp_dim, 1, dropout)
123
+ for k in ["text","audio_transcript","video_transcript","tags"]})
124
+ self.trust_mlp = None
125
+ else:
126
+ self.trust_mlp = self._make_mlp(trust_in, mlp_dim, 1, dropout)
127
+ self.trust_mlps = None
128
+ self.uncertainty_mlp = self._make_mlp(h_dim, mlp_dim, 1, dropout)
129
+ classifier_in = proj_dim * 5 + ccm_dim + 4 + 4
130
+ out_dim = 1 if num_classes == 2 else num_classes
131
+ self.mlp = nn.Sequential(
132
+ nn.Linear(classifier_in, mlp_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(mlp_dim, out_dim)
133
+ )
134
+
135
+ @staticmethod
136
+ def _make_mlp(in_dim, hidden_dim, out_dim, dropout):
137
+ return nn.Sequential(nn.Linear(in_dim, hidden_dim), nn.ReLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, out_dim))
138
+
139
+ @staticmethod
140
+ def _cosine(a, b):
141
+ return F.cosine_similarity(a, b, dim=-1, eps=1e-8).unsqueeze(-1)
142
+
143
+ def _compute_ccm(self, h_text, h_audio, h_video, h_tags):
144
+ sims = [self._cosine(h_text, h_audio), self._cosine(h_text, h_video), self._cosine(h_audio, h_video)]
145
+ if self.include_tags_ccm:
146
+ sims += [self._cosine(h_text, h_tags), self._cosine(h_audio, h_tags), self._cosine(h_video, h_tags)]
147
+ return torch.cat(sims, dim=-1)
148
+
149
+ def _trust_logit(self, key, h_i, ccm):
150
+ x = torch.cat([h_i, ccm], dim=-1)
151
+ return self.trust_mlps[key](x) if self.per_modality_trust else self.trust_mlp(x)
152
+
153
+ def forward(self, batch, return_details=False):
154
+ h_tags, p_tags = self.encoders["tags"](batch["tags"])
155
+ h_text, p_text = self.encoders["text"](batch["text"])
156
+ h_audio, p_audio = self.encoders["audio_transcript"](batch["audio_transcript"])
157
+ h_video, p_video = self.encoders["video_transcript"](batch["video_transcript"])
158
+ ccm = self._compute_ccm(h_text, h_audio, h_video, h_tags)
159
+ trust_logits = torch.cat([self._trust_logit("text", h_text, ccm),
160
+ self._trust_logit("audio_transcript", h_audio, ccm),
161
+ self._trust_logit("video_transcript", h_video, ccm),
162
+ self._trust_logit("tags", h_tags, ccm)], dim=-1)
163
+ trust_w = torch.softmax(trust_logits, dim=-1)
164
+ sigmas = torch.cat([F.softplus(self.uncertainty_mlp(h)) + 1e-6
165
+ for h in [h_text, h_audio, h_video, h_tags]], dim=-1)
166
+ confidence = 1.0 / sigmas
167
+ fusion_w = trust_w * confidence
168
+ fusion_w = fusion_w / (fusion_w.sum(dim=-1, keepdim=True) + 1e-8)
169
+ proj_stack = torch.stack([p_text, p_audio, p_video, p_tags], dim=1)
170
+ fused = torch.sum(proj_stack * fusion_w.unsqueeze(-1), dim=1)
171
+ combined = torch.cat([p_text, p_audio, p_video, p_tags, fused, ccm, trust_w, sigmas], dim=-1)
172
+ logits = self.mlp(combined)
173
+ if not return_details: return logits
174
+ return logits, {"ccm": ccm, "trust_w": trust_w, "sigma": sigmas, "fusion_w": fusion_w}
175
+
176
+
177
+ # ── Globals ────────────────────────────────────────────────────────────────────
178
+ _model = None
179
+ _vocabs = None
180
+ _max_lens = None
181
+ _config = None
182
+ _device = "cpu"
183
+
184
+ REPO_ID = "rocky250/MHMisinfo"
185
+ YT_API_KEY = os.environ.get("YT_API_KEY", "")
186
+
187
+
188
+ def _load_model():
189
+ global _model, _vocabs, _max_lens, _config
190
+ if _model is not None:
191
+ return
192
+ ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="best_multimodal.pt")
193
+ ckpt = torch.load(ckpt_path, map_location=_device, weights_only=False)
194
+ vocabs_raw = ckpt["vocabs"]
195
+ _vocabs = {k: Vocab.from_serializable(v) for k, v in vocabs_raw.items()}
196
+ _max_lens = ckpt["max_lens"]
197
+ _config = ckpt["config"]
198
+ num_classes = ckpt["num_classes"]
199
+ _model = MultiStreamModel(
200
+ vocab_sizes={k: len(v.token_to_idx) for k, v in _vocabs.items()},
201
+ num_classes=num_classes,
202
+ emb_dim=_config["emb_dim"], hidden_dim=_config["hidden_dim"],
203
+ attn_dim=_config["attn_dim"], proj_dim=_config["proj_dim"],
204
+ mlp_dim=_config["mlp_dim"], dropout=_config["dropout"],
205
+ include_tags_ccm=_config.get("include_tags_ccm", False),
206
+ per_modality_trust=_config.get("per_modality_trust", False),
207
+ ).to(_device)
208
+ _model.load_state_dict(ckpt["model_state"])
209
+ _model.eval()
210
+
211
+
212
+ def _extract_video_id(url: str) -> Optional[str]:
213
+ patterns = [
214
+ r"(?:v=|youtu\.be/|embed/|shorts/)([A-Za-z0-9_-]{11})",
215
+ ]
216
+ for p in patterns:
217
+ m = re.search(p, url)
218
+ if m: return m.group(1)
219
+ return None
220
+
221
+
222
+ def _fetch_yt_metadata(video_id: str):
223
+ """Fetch title, description, tags via YouTube Data API v3."""
224
+ if not YT_API_KEY:
225
+ return None, None, None, "⚠️ No YouTube API key set. Set the YT_API_KEY secret in Space settings."
226
+ try:
227
+ yt = yt_build("youtube", "v3", developerKey=YT_API_KEY, cache_discovery=False)
228
+ resp = yt.videos().list(part="snippet", id=video_id).execute()
229
+ if not resp.get("items"):
230
+ return None, None, None, "❌ Video not found or unavailable."
231
+ snippet = resp["items"][0]["snippet"]
232
+ title = snippet.get("title", "")
233
+ desc = snippet.get("description", "")
234
+ tags = " ".join(snippet.get("tags", []))
235
+ return title, desc, tags, None
236
+ except Exception as e:
237
+ return None, None, None, f"❌ YouTube API error: {e}"
238
+
239
+
240
+ def _fetch_transcript(video_id: str, field: str) -> str:
241
+ """Fetch transcript text (same text used for both audio & video transcript streams)."""
242
+ try:
243
+ transcript_list = YouTubeTranscriptApi.get_transcript(video_id, languages=["en"])
244
+ return " ".join(t["text"] for t in transcript_list)
245
+ except (NoTranscriptFound, TranscriptsDisabled):
246
+ return ""
247
+ except Exception:
248
+ return ""
249
+
250
+
251
+ def _encode_single(text: str, tags: str, audio_t: str, video_t: str) -> Dict[str, torch.Tensor]:
252
+ _load_model()
253
+ streams = {
254
+ "tags": tokenize_tags(tags),
255
+ "text": tokenize_text(text),
256
+ "audio_transcript": tokenize_text(audio_t),
257
+ "video_transcript": tokenize_text(video_t),
258
+ }
259
+ batch = {}
260
+ for s, tokens in streams.items():
261
+ ids = _vocabs[s].encode(tokens, _max_lens[s])
262
+ batch[s] = torch.tensor([ids], dtype=torch.long).to(_device)
263
+ return batch
264
+
265
+
266
+ def _run_inference(text, tags, audio_t, video_t):
267
+ batch = _encode_single(text, tags, audio_t, video_t)
268
+ with torch.no_grad():
269
+ logits, details = _model(batch, return_details=True)
270
+ prob = float(torch.sigmoid(logits).squeeze())
271
+ pred = int(prob >= 0.5)
272
+ trust = details["trust_w"][0].cpu().numpy().tolist()
273
+ sigma = details["sigma"][0].cpu().numpy().tolist()
274
+ ccm = details["ccm"][0].cpu().numpy().tolist()
275
+ return prob, pred, trust, sigma, ccm
276
+
277
+
278
+ # ── Gradio logic ───────────────────────────────────────────────────────────────
279
+ MODALITIES = ["text", "audio_transcript", "video_transcript", "tags"]
280
+ CCM_LABELS_3 = ["text↔audio", "text↔video", "audio↔video"]
281
+ CCM_LABELS_6 = CCM_LABELS_3 + ["text↔tags", "audio↔tags", "video↔tags"]
282
+
283
+ LABEL_COLORS = {0: "#22c55e", 1: "#ef4444"}
284
+ LABEL_NAMES = {0: "βœ… Credible / Not Misinformation", 1: "⚠️ Potential Misinformation"}
285
+
286
+
287
+ def _bar(value: float, color: str) -> str:
288
+ pct = int(value * 100)
289
+ return (
290
+ f'<div style="background:#e5e7eb;border-radius:6px;height:14px;width:100%;margin:2px 0">'
291
+ f'<div style="background:{color};width:{pct}%;height:100%;border-radius:6px;transition:width 0.4s"></div>'
292
+ f'</div><small style="color:#6b7280">{value:.3f}</small>'
293
+ )
294
+
295
+
296
+ def analyze_url(url: str):
297
+ if not url.strip():
298
+ return [gr.update(visible=False)] * 4 + ["Please enter a YouTube URL."]
299
+
300
+ video_id = _extract_video_id(url.strip())
301
+ if not video_id:
302
+ return [gr.update(visible=False)] * 4 + ["❌ Could not extract a valid YouTube video ID from that URL."]
303
+
304
+ # Fetch metadata
305
+ title, desc, tags, err = _fetch_yt_metadata(video_id)
306
+ if err:
307
+ return [gr.update(visible=False)] * 4 + [err]
308
+
309
+ # Fetch transcript
310
+ transcript = _fetch_transcript(video_id, "transcript")
311
+ text_field = f"{title} {desc}".strip()
312
+
313
+ # Run model
314
+ try:
315
+ _load_model()
316
+ prob, pred, trust, sigma, ccm = _run_inference(text_field, tags, transcript, transcript)
317
+ except Exception as e:
318
+ return [gr.update(visible=False)] * 4 + [f"❌ Model error: {e}"]
319
+
320
+ # ── Verdict card ──────────────────────────────────────────────────────────
321
+ color = LABEL_COLORS[pred]
322
+ label_text = LABEL_NAMES[pred]
323
+ conf_pct = int(prob * 100) if pred == 1 else int((1 - prob) * 100)
324
+ verdict_html = f"""
325
+ <div style="border:2px solid {color};border-radius:12px;padding:20px 24px;background:{color}18;margin-bottom:8px">
326
+ <div style="font-size:1.5rem;font-weight:700;color:{color}">{label_text}</div>
327
+ <div style="font-size:2.5rem;font-weight:800;color:{color};margin:6px 0">{conf_pct}% confident</div>
328
+ <div style="color:#6b7280;font-size:0.9rem">Raw misinfo probability: <b>{prob:.4f}</b></div>
329
+ </div>
330
+ <div style="background:#f9fafb;border-radius:10px;padding:14px 16px;margin-top:6px">
331
+ <b>🎬 Video:</b> <a href="{url}" target="_blank">{title}</a><br>
332
+ <b>🏷️ Tags:</b> {tags[:120] + '…' if len(tags)>120 else (tags or '(none)')}<br>
333
+ <b>πŸ“ Transcript:</b> {('Available (' + str(len(transcript.split())) + ' words)') if transcript else '(not available β€” model used title/description only)'}
334
+ </div>
335
+ """
336
+
337
+ # ── Modality trust weights ─────────────────────────────────────────────────
338
+ trust_html = "<h4 style='margin-bottom:8px'>Modality Trust Weights</h4>"
339
+ trust_html += "<small style='color:#6b7280'>How much the model relied on each stream</small><br><br>"
340
+ for m, t in zip(MODALITIES, trust):
341
+ trust_html += f"<b>{m.replace('_',' ').title()}</b>{_bar(t, '#3b82f6')}"
342
+
343
+ # ── Uncertainty (sigma) ───────────────────────────────────────────────────
344
+ sigma_html = "<h4 style='margin-bottom:8px'>Uncertainty (Οƒ)</h4>"
345
+ sigma_html += "<small style='color:#6b7280'>Higher = encoder less certain about this stream</small><br><br>"
346
+ max_s = max(sigma) if sigma else 1
347
+ for m, s in zip(MODALITIES, sigma):
348
+ sigma_html += f"<b>{m.replace('_',' ').title()}</b>{_bar(s/max_s, '#f59e0b')}"
349
+
350
+ # ── CCM ───────────────────────────────────────────────────────────────────
351
+ ccm_labels = CCM_LABELS_6 if len(ccm) == 6 else CCM_LABELS_3
352
+ ccm_html = "<h4 style='margin-bottom:8px'>Cross-Channel Consistency (CCM)</h4>"
353
+ ccm_html += "<small style='color:#6b7280'>Cosine similarity between modality representations (βˆ’1 to 1)</small><br><br>"
354
+ for lbl, val in zip(ccm_labels, ccm):
355
+ norm = (val + 1) / 2 # map [-1,1] β†’ [0,1]
356
+ ccm_html += f"<b>{lbl}</b>{_bar(norm, '#8b5cf6')}<small style='color:#9ca3af'>raw: {val:.3f}</small><br>"
357
+
358
+ status = "βœ… Analysis complete."
359
+ return (
360
+ gr.update(value=verdict_html, visible=True),
361
+ gr.update(value=trust_html, visible=True),
362
+ gr.update(value=sigma_html, visible=True),
363
+ gr.update(value=ccm_html, visible=True),
364
+ status,
365
+ )
366
+
367
+
368
+ # ── UI ─────────────────────────────────────────────────────────────────────────
369
+ CSS = """
370
+ #header { text-align:center; margin-bottom: 20px; }
371
+ #header h1 { font-size: 2rem; font-weight: 800; margin: 0; }
372
+ #header p { color: #6b7280; margin: 4px 0 0; }
373
+ .panel { border-radius:12px !important; }
374
+ footer { display:none !important; }
375
+ """
376
+
377
+ with gr.Blocks(css=CSS, title="MHMisinfo β€” Mental Health Misinformation Detector") as demo:
378
+ gr.HTML("""
379
+ <div id="header">
380
+ <h1>🧠 MHMisinfo</h1>
381
+ <p>4-Stream SeTa-Attention model for detecting mental health misinformation on YouTube</p>
382
+ <p style="font-size:0.8rem;color:#9ca3af">
383
+ Based on: <i>"Supporters and Skeptics: LLM-based Analysis of Engagement with Mental Health (Mis)Information Content on Video-sharing Platforms"</i>
384
+ </p>
385
+ </div>
386
+ """)
387
+
388
+ with gr.Row():
389
+ with gr.Column(scale=3):
390
+ url_input = gr.Textbox(
391
+ placeholder="Paste a YouTube URL here, e.g. https://www.youtube.com/watch?v=...",
392
+ label="YouTube Video URL",
393
+ lines=1,
394
+ )
395
+ with gr.Column(scale=1, min_width=120):
396
+ analyze_btn = gr.Button("πŸ” Analyze", variant="primary", size="lg")
397
+
398
+ status_box = gr.Textbox(label="Status", interactive=False, lines=1, visible=True)
399
+
400
+ with gr.Row():
401
+ verdict_out = gr.HTML(visible=False, elem_classes="panel")
402
+
403
+ with gr.Row():
404
+ with gr.Column():
405
+ trust_out = gr.HTML(visible=False, elem_classes="panel")
406
+ with gr.Column():
407
+ sigma_out = gr.HTML(visible=False, elem_classes="panel")
408
+
409
+ with gr.Row():
410
+ ccm_out = gr.HTML(visible=False, elem_classes="panel")
411
+
412
+ gr.HTML("""
413
+ <hr style="margin:28px 0 16px">
414
+ <details>
415
+ <summary style="cursor:pointer;font-weight:600;color:#374151">ℹ️ How it works</summary>
416
+ <div style="padding:12px 0;color:#6b7280;font-size:0.9rem">
417
+ <b>4 streams:</b> video title+description (text), hashtags/tags, audio transcript, video transcript.<br>
418
+ Each stream is encoded by a BiGRU with SeTa dual-attention. The model computes:<br>
419
+ &nbsp;β€’ <b>CCM</b> (Cross-Channel Consistency Matrix) β€” cosine similarity between stream representations<br>
420
+ &nbsp;β€’ <b>Trust weights</b> β€” learned per-stream reliability given CCM context<br>
421
+ &nbsp;β€’ <b>Uncertainty (Οƒ)</b> β€” calibrated confidence per stream via DMTE<br>
422
+ These are fused into a single classification head.<br><br>
423
+ <b>Note:</b> The model was trained on short YouTube mental health videos. Results on other content types may vary.
424
+ ROC-AUC on held-out test: <b>0.967</b>. Positive-class F1: <b>0.828</b>.
425
+ </div>
426
+ </details>
427
+ """)
428
+
429
+ analyze_btn.click(
430
+ fn=analyze_url,
431
+ inputs=[url_input],
432
+ outputs=[verdict_out, trust_out, sigma_out, ccm_out, status_box],
433
+ )
434
+ url_input.submit(
435
+ fn=analyze_url,
436
+ inputs=[url_input],
437
+ outputs=[verdict_out, trust_out, sigma_out, ccm_out, status_box],
438
+ )
439
+
440
+ demo.launch()