Harting - Final submission
Browse files
app.py
CHANGED
|
@@ -1,338 +1,217 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
import time
|
| 4 |
-
from typing import List, Dict, Any
|
| 5 |
|
|
|
|
|
|
|
| 6 |
import torch
|
| 7 |
import gradio as gr
|
| 8 |
from PIL import Image
|
| 9 |
-
|
| 10 |
-
from
|
| 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 |
-
"keyboard": {"japanese": "キーボード", "romaji": "kiibodo", "korean": "키보드", "romanization": "kibodeu"},
|
| 42 |
-
"mouse": {"japanese": "マウス", "romaji": "mausu", "korean": "마우스", "romanization": "mauseu"},
|
| 43 |
-
"printer": {"japanese": "プリンター", "romaji": "purintaa", "korean": "프린터", "romanization": "peurinteo"},
|
| 44 |
-
"webcam": {"japanese": "ウェブカメラ", "romaji": "webu kamera", "korean": "웹캠", "romanization": "wepkaem"},
|
| 45 |
-
"speaker": {"japanese": "スピーカー", "romaji": "supiikaa", "korean": "스피커", "romanization": "seupikeo"},
|
| 46 |
-
"tv": {"japanese": "テレビ", "romaji": "terebi", "korean": "텔레비전", "romanization": "tellebijeon"},
|
| 47 |
-
"television": {"japanese": "テレビ", "romaji": "terebi", "korean": "텔레비전", "romanization": "tellebijeon"},
|
| 48 |
-
"remote": {"japanese": "リモコン", "romaji": "rimokon", "korean": "리모컨", "romanization": "rimokeon"},
|
| 49 |
-
"radio": {"japanese": "ラジオ", "romaji": "rajio", "korean": "라디오", "romanization": "radio"},
|
| 50 |
-
"phone": {"japanese": "電話", "romaji": "denwa", "korean": "전화", "romanization": "jeonhwa"},
|
| 51 |
-
"telephone": {"japanese": "電話", "romaji": "denwa", "korean": "전화", "romanization": "jeonhwa"},
|
| 52 |
-
"cell phone": {"japanese": "携帯電話", "romaji": "keitai denwa", "korean": "휴대폰", "romanization": "hyudaepon"},
|
| 53 |
-
"calculator": {"japanese": "電卓", "romaji": "dentaku", "korean": "계산기", "romanization": "gyesangi"},
|
| 54 |
-
"clock": {"japanese": "時計", "romaji": "tokei", "korean": "시계", "romanization": "sigye"},
|
| 55 |
-
"alarm clock": {"japanese": "目覚まし時計", "romaji": "mezamashi dokei", "korean": "알람 시계", "romanization": "allam sigye"},
|
| 56 |
-
|
| 57 |
-
# --- Stationery / office supplies ---
|
| 58 |
-
"pen": {"japanese": "ペン", "romaji": "pen", "korean": "펜", "romanization": "pen"},
|
| 59 |
-
"pencil": {"japanese": "鉛筆", "romaji": "enpitsu", "korean": "연필", "romanization": "yeonpil"},
|
| 60 |
-
"marker": {"japanese": "マーカー", "romaji": "maakaa", "korean": "마커", "romanization": "makeo"},
|
| 61 |
-
"eraser": {"japanese": "消しゴム", "romaji": "keshigomu", "korean": "지우개", "romanization": "jiugae"},
|
| 62 |
-
"ruler": {"japanese": "定規", "romaji": "jougi", "korean": "자", "romanization": "ja"},
|
| 63 |
-
"scissors": {"japanese": "はさみ", "romaji": "hasami", "korean": "가위", "romanization": "gawi"},
|
| 64 |
-
"notebook": {"japanese": "ノート", "romaji": "nooto", "korean": "공책", "romanization": "gongchaek"},
|
| 65 |
-
"book": {"japanese": "本", "romaji": "hon", "korean": "책", "romanization": "chaek"},
|
| 66 |
-
"folder": {"japanese": "フォルダ", "romaji": "foruda", "korean": "폴더", "romanization": "poldeo"},
|
| 67 |
-
"clipboard": {"japanese": "クリップボード", "romaji": "kurippu boodo", "korean": "클립보드", "romanization": "keullipbodeu"},
|
| 68 |
-
"calendar": {"japanese": "カレンダー", "romaji": "karendaa", "korean": "달력", "romanization": "dallyeok"},
|
| 69 |
-
"paper clip": {"japanese": "クリップ", "romaji": "kurippu", "korean": "종이 클립", "romanization": "jongi keullip"},
|
| 70 |
-
"push pin": {"japanese": "画びょう", "romaji": "gabyou", "korean": "압정", "romanization": "apjeong"},
|
| 71 |
-
"exit sign": {"japanese": "出口表示", "romaji": "deguchi hyouji", "korean": "출구 표지", "romanization": "chulgu pyoji"},
|
| 72 |
-
|
| 73 |
-
# --- Kitchen / dining ---
|
| 74 |
-
"mug": {"japanese": "マグカップ", "romaji": "magu kappu", "korean": "머그컵", "romanization": "meogeukeop"},
|
| 75 |
-
"cup": {"japanese": "カップ", "romaji": "kappu", "korean": "컵", "romanization": "keop"},
|
| 76 |
-
"wine glass": {"japanese": "ワイングラス", "romaji": "wain gurasu", "korean": "와인 잔", "romanization": "wain jan"},
|
| 77 |
-
"bottle": {"japanese": "ボトル", "romaji": "botoru", "korean": "병", "romanization": "byeong"},
|
| 78 |
-
"bowl": {"japanese": "ボウル", "romaji": "bouru", "korean": "그릇", "romanization": "geureut"},
|
| 79 |
-
"fork": {"japanese": "フォーク", "romaji": "fooku", "korean": "포크", "romanization": "pokeu"},
|
| 80 |
-
"spoon": {"japanese": "スプーン", "romaji": "supuun", "korean": "숟가락", "romanization": "sutgarak"},
|
| 81 |
-
"knife": {"japanese": "ナイフ", "romaji": "naifu", "korean": "칼", "romanization": "kal"},
|
| 82 |
-
"kettle": {"japanese": "やかん", "romaji": "yakan", "korean": "주전자", "romanization": "jujeonja"},
|
| 83 |
-
"pan": {"japanese": "フライパン", "romaji": "furaipan", "korean": "팬", "romanization": "paen"},
|
| 84 |
-
"oven": {"japanese": "オーブン", "romaji": "oobun", "korean": "오븐", "romanization": "obeun"},
|
| 85 |
-
"microwave": {"japanese": "電子レンジ", "romaji": "denshi renji", "korean": "전자레인지", "romanization": "jeonjareinji"},
|
| 86 |
-
"toaster": {"japanese": "トースター", "romaji": "toosutaa", "korean": "토스터", "romanization": "toseuteo"},
|
| 87 |
-
"refrigerator": {"japanese": "冷蔵庫", "romaji": "reizouko", "korean": "냉장고", "romanization": "naengjanggo"},
|
| 88 |
-
"sink": {"japanese": "流し", "romaji": "nagashi", "korean": "싱크대", "romanization": "singkeudae"},
|
| 89 |
-
"soda": {"japanese": "ソーダ", "romaji": "sooda", "korean": "탄산음료", "romanization": "tansaneumnyo"},
|
| 90 |
-
|
| 91 |
-
# --- Bathroom ---
|
| 92 |
-
"toothbrush": {"japanese": "歯ブラシ", "romaji": "ha burashi", "korean": "칫솔", "romanization": "chitsol"},
|
| 93 |
-
"toilet": {"japanese": "トイレ", "romaji": "toire", "korean": "화장실", "romanization": "hwajangsil"},
|
| 94 |
-
|
| 95 |
-
# --- Tools / hardware ---
|
| 96 |
-
"hammer": {"japanese": "ハンマー", "romaji": "hanmaa", "korean": "망치", "romanization": "mangchi"},
|
| 97 |
-
"drill": {"japanese": "ドリル", "romaji": "doriru", "korean": "드릴", "romanization": "deuril"},
|
| 98 |
-
"screwdriver": {"japanese": "ドライバー", "romaji": "doraibaa", "korean": "드라이버", "romanization": "deuraibeo"},
|
| 99 |
-
"bucket": {"japanese": "バケツ", "romaji": "baketsu", "korean": "양동이", "romanization": "yangdongi"},
|
| 100 |
-
"mop": {"japanese": "モップ", "romaji": "moppu", "korean": "대걸레", "romanization": "daegeolle"},
|
| 101 |
-
"trash can": {"japanese": "ゴミ箱", "romaji": "gomibako", "korean": "쓰레기통", "romanization": "sseuregitong"},
|
| 102 |
-
|
| 103 |
-
# --- Personal items / clothing ---
|
| 104 |
-
"backpack": {"japanese": "リュックサック", "romaji": "ryukku sakku", "korean": "백팩", "romanization": "baekpaek"},
|
| 105 |
-
"handbag": {"japanese": "ハンドバッグ", "romaji": "hando baggu", "korean": "핸드백", "romanization": "haendeubaek"},
|
| 106 |
-
"suitcase": {"japanese": "スーツケース", "romaji": "suutsu keesu", "korean": "여행 가방", "romanization": "yeohaeng gabang"},
|
| 107 |
-
"umbrella": {"japanese": "傘", "romaji": "kasa", "korean": "우산", "romanization": "usan"},
|
| 108 |
-
"glasses": {"japanese": "眼鏡", "romaji": "megane", "korean": "안경", "romanization": "angyeong"},
|
| 109 |
-
"tie": {"japanese": "ネクタイ", "romaji": "nekutai", "korean": "넥타이", "romanization": "nektai"},
|
| 110 |
-
"helmet": {"japanese": "ヘルメット", "romaji": "herumetto", "korean": "헬멧", "romanization": "helmet"},
|
| 111 |
-
"sneakers": {"japanese": "スニーカー", "romaji": "suniikaa", "korean": "운동화", "romanization": "undonghwa"},
|
| 112 |
-
"flipflops": {"japanese": "ビーチサンダル", "romaji": "biichi sandaru", "korean": "슬리퍼", "romanization": "seullipeo"},
|
| 113 |
-
"bike": {"japanese": "自転車", "romaji": "jitensha", "korean": "자전거", "romanization": "jajeongeo"},
|
| 114 |
-
|
| 115 |
-
# --- Decor / misc ---
|
| 116 |
-
"flower": {"japanese": "花", "romaji": "hana", "korean": "꽃", "romanization": "kkot"},
|
| 117 |
-
"plant": {"japanese": "植物", "romaji": "shokubutsu", "korean": "식물", "romanization": "singmul"},
|
| 118 |
-
"potted plant": {"japanese": "鉢植え", "romaji": "hachi-ue", "korean": "화분", "romanization": "hwabun"},
|
| 119 |
-
"vase": {"japanese": "花瓶", "romaji": "kabin", "korean": "꽃병", "romanization": "kkotbyeong"},
|
| 120 |
-
"toy": {"japanese": "おもちゃ", "romaji": "omocha", "korean": "장난감", "romanization": "jangnangam"},
|
| 121 |
-
"teddy bear": {"japanese": "テディベア", "romaji": "tedi bea", "korean": "곰인형", "romanization": "gominhyeong"},
|
| 122 |
-
"postit": {"japanese": "付箋", "romaji": "fusen", "korean": "포스트잇", "romanization": "poseuteuit"},
|
| 123 |
-
"hairdryer": {"japanese": "ドライヤー", "romaji": "doraiyaa", "korean": "드라이어", "romanization": "deuraieo"},
|
| 124 |
}
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
_MULTI_WORD_KEYS = [k for k in VOCAB_DICT if " " in k]
|
| 129 |
|
| 130 |
-
#
|
| 131 |
-
USE_GPU = torch.cuda.is_available()
|
| 132 |
-
DEVICE = 0 if USE_GPU else -1
|
| 133 |
-
TORCH_DTYPE = torch.float16 if USE_GPU else None
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
"
|
| 138 |
-
|
| 139 |
-
device=
|
| 140 |
)
|
| 141 |
|
| 142 |
-
|
| 143 |
-
"
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
return out[0]["generated_text"]
|
| 147 |
-
return ""
|
| 148 |
-
|
| 149 |
-
detection_pipeline = pipeline(
|
| 150 |
-
"object-detection",
|
| 151 |
-
model="facebook/detr-resnet-50",
|
| 152 |
-
device=DEVICE,
|
| 153 |
)
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
return
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
return {"translation": entry["korean"], "romanization": entry["romanization"]}
|
| 233 |
-
return {"translation": term, "romanization": "N/A"}
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
def generate_flashcard_table(vocab_list: List[str], lang: str) -> List[List[str]]:
|
| 237 |
-
"""Generate flashcard table."""
|
| 238 |
-
table = [["English", f"{lang} Translation", "Romanization", "Source"]]
|
| 239 |
-
for term in vocab_list:
|
| 240 |
-
trans = translate_term(term, lang)
|
| 241 |
-
table.append([term, trans["translation"], trans["romanization"], "extracted"])
|
| 242 |
-
return table
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
def compute_comparison_stats(
|
| 246 |
-
caption_vocab: List[str],
|
| 247 |
-
detection_vocab: List[str],
|
| 248 |
-
caption_time: float,
|
| 249 |
-
detection_time: float,
|
| 250 |
-
detection_results: List[Dict],
|
| 251 |
-
) -> str:
|
| 252 |
-
"""Compute comparison statistics."""
|
| 253 |
-
overlap = set(caption_vocab) & set(detection_vocab)
|
| 254 |
-
avg_conf = sum(r["score"] for r in detection_results) / len(detection_results) if detection_results else 0.0
|
| 255 |
-
|
| 256 |
-
stats = f"""
|
| 257 |
-
Captioning Vocab Terms: {len(caption_vocab)}
|
| 258 |
-
Detection Vocab Terms: {len(detection_vocab)}
|
| 259 |
-
Overlapping Terms: {len(overlap)}
|
| 260 |
-
Caption Output Length: {len(' '.join(caption_vocab))}
|
| 261 |
-
Detection Output Length: {len(detection_vocab)}
|
| 262 |
-
Average Detection Confidence: {avg_conf:.2f}
|
| 263 |
-
Captioning Time: {caption_time:.2f}s
|
| 264 |
-
Detection Time: {detection_time:.2f}s
|
| 265 |
-
Conclusion: {'Captioning' if len(caption_vocab) > len(detection_vocab) else 'Detection'} provided more vocabulary terms.
|
| 266 |
-
"""
|
| 267 |
-
return stats.strip()
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
def process_image(image: Image.Image, language: str):
|
| 271 |
-
"""Main processing function."""
|
| 272 |
-
if image is None:
|
| 273 |
-
return "No image uploaded.", [], [], "No image."
|
| 274 |
-
|
| 275 |
-
# Algorithm 1: Captioning
|
| 276 |
-
start = time.time()
|
| 277 |
-
try:
|
| 278 |
-
caption = generate_caption(image)
|
| 279 |
-
except Exception as e:
|
| 280 |
-
caption = f"Captioning failed: {e}"
|
| 281 |
-
caption_time = time.time() - start
|
| 282 |
-
|
| 283 |
-
# Algorithm 2: Detection
|
| 284 |
-
start = time.time()
|
| 285 |
-
try:
|
| 286 |
-
detection_results = detection_pipeline(image)
|
| 287 |
-
except Exception as e:
|
| 288 |
-
detection_results = []
|
| 289 |
-
detection_time = time.time() - start
|
| 290 |
-
|
| 291 |
-
# NLP: Extract vocab
|
| 292 |
-
caption_vocab = extract_vocab_from_caption(caption)
|
| 293 |
-
detection_vocab = extract_vocab_from_detection(detection_results)
|
| 294 |
-
all_vocab = list(set(caption_vocab + detection_vocab))
|
| 295 |
-
|
| 296 |
-
# Flashcard table
|
| 297 |
-
flashcard_table = generate_flashcard_table(all_vocab, language)
|
| 298 |
-
|
| 299 |
-
# Comparison stats
|
| 300 |
-
stats = compute_comparison_stats(caption_vocab, detection_vocab, caption_time, detection_time, detection_results)
|
| 301 |
-
|
| 302 |
-
return caption, detection_results, flashcard_table, stats
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
# Gradio Interface
|
| 306 |
-
with gr.Blocks(title="Multimodal Language Flashcard Generator") as demo:
|
| 307 |
-
gr.Markdown("# Multimodal Language Flashcard Generator")
|
| 308 |
-
gr.Markdown("Upload an image, select a language, and generate flashcards with captioning and object detection.")
|
| 309 |
-
|
| 310 |
-
with gr.Row():
|
| 311 |
-
image_input = gr.Image(type="pil", label="Upload Image")
|
| 312 |
-
lang_input = gr.Dropdown(["Japanese", "Korean"], label="Target Language", value="Japanese")
|
| 313 |
-
|
| 314 |
-
if SAMPLE_PATHS:
|
| 315 |
-
gr.Examples(
|
| 316 |
-
examples=[[p] for p in SAMPLE_PATHS],
|
| 317 |
-
inputs=[image_input],
|
| 318 |
-
label="Sample images from flwrlabs/office-home (click one to load)",
|
| 319 |
)
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
)
|
| 335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
-
|
| 338 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
|
| 2 |
+
import numpy as np
|
| 3 |
+
import librosa
|
| 4 |
import torch
|
| 5 |
import gradio as gr
|
| 6 |
from PIL import Image
|
| 7 |
+
import requests
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration
|
| 11 |
+
|
| 12 |
+
# Device configuration
|
| 13 |
+
torch_device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
pipeline_device = 0 if torch.cuda.is_available() else -1
|
| 15 |
+
|
| 16 |
+
# ---------- LABEL DEFINITIONS ----------
|
| 17 |
+
|
| 18 |
+
CANONICAL_LABELS = ["anger", "happiness", "neutral", "sadness"]
|
| 19 |
+
|
| 20 |
+
TEXT_MODEL_LABEL_MAP = {
|
| 21 |
+
"anger": "anger",
|
| 22 |
+
"joy": "happiness",
|
| 23 |
+
"neutral": "neutral",
|
| 24 |
+
"sadness": "sadness",
|
| 25 |
+
"disgust": None,
|
| 26 |
+
"fear": None,
|
| 27 |
+
"surprise": None
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
AUDIO_MODEL_LABEL_MAP = {
|
| 31 |
+
"ang": "anger",
|
| 32 |
+
"hap": "happiness",
|
| 33 |
+
"neu": "neutral",
|
| 34 |
+
"sad": "sadness",
|
| 35 |
+
"anger": "anger",
|
| 36 |
+
"happy": "happiness",
|
| 37 |
+
"neutral": "neutral",
|
| 38 |
+
"sadness": "sadness"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
}
|
| 40 |
|
| 41 |
+
TEXT_WEIGHT = 0.40
|
| 42 |
+
AUDIO_WEIGHT = 0.60
|
|
|
|
| 43 |
|
| 44 |
+
# ---------- LOAD MODELS ----------
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
text_classifier = pipeline(
|
| 47 |
+
"text-classification",
|
| 48 |
+
model="j-hartmann/emotion-english-distilroberta-base",
|
| 49 |
+
top_k=None,
|
| 50 |
+
device=pipeline_device
|
| 51 |
)
|
| 52 |
|
| 53 |
+
audio_classifier = pipeline(
|
| 54 |
+
"audio-classification",
|
| 55 |
+
model="superb/wav2vec2-base-superb-er",
|
| 56 |
+
device=pipeline_device
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
)
|
| 58 |
|
| 59 |
+
image_classifier = pipeline(
|
| 60 |
+
"image-classification",
|
| 61 |
+
model="google/vit-base-patch16-224",
|
| 62 |
+
device=pipeline_device
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
image_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 66 |
+
image_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(torch_device)
|
| 67 |
+
|
| 68 |
+
# ---------- HELPER FUNCTIONS ----------
|
| 69 |
+
|
| 70 |
+
def initialize_score_dict():
|
| 71 |
+
return {label: 0.0 for label in CANONICAL_LABELS}
|
| 72 |
+
|
| 73 |
+
def normalize_text_label(label):
|
| 74 |
+
return TEXT_MODEL_LABEL_MAP.get(str(label).lower(), None)
|
| 75 |
+
|
| 76 |
+
def normalize_audio_label(label):
|
| 77 |
+
return AUDIO_MODEL_LABEL_MAP.get(str(label).lower(), None)
|
| 78 |
+
|
| 79 |
+
def format_top_predictions(predictions, top_k=3):
|
| 80 |
+
return "\n".join([f"{p['label']} ({p['score']:.4f})" for p in predictions[:top_k]])
|
| 81 |
+
|
| 82 |
+
# ---------- TEXT MODEL ----------
|
| 83 |
+
|
| 84 |
+
def predict_text_emotion(transcript):
|
| 85 |
+
if not transcript or transcript.strip() == "":
|
| 86 |
+
return [], initialize_score_dict()
|
| 87 |
+
|
| 88 |
+
preds = text_classifier(transcript)
|
| 89 |
+
|
| 90 |
+
if isinstance(preds, list) and isinstance(preds[0], list):
|
| 91 |
+
preds = preds[0]
|
| 92 |
+
|
| 93 |
+
scores = initialize_score_dict()
|
| 94 |
+
normalized = []
|
| 95 |
+
|
| 96 |
+
for item in preds:
|
| 97 |
+
mapped = normalize_text_label(item["label"])
|
| 98 |
+
if mapped:
|
| 99 |
+
scores[mapped] += item["score"]
|
| 100 |
+
normalized.append({"label": mapped, "score": item["score"]})
|
| 101 |
+
|
| 102 |
+
return sorted(normalized, key=lambda x: x["score"], reverse=True), scores
|
| 103 |
+
|
| 104 |
+
# ---------- AUDIO MODEL ----------
|
| 105 |
+
|
| 106 |
+
def predict_audio_emotion(audio):
|
| 107 |
+
array = audio["array"]
|
| 108 |
+
sr = audio["sampling_rate"]
|
| 109 |
+
|
| 110 |
+
if sr != 16000:
|
| 111 |
+
array = librosa.resample(array, orig_sr=sr, target_sr=16000)
|
| 112 |
+
sr = 16000
|
| 113 |
+
|
| 114 |
+
preds = audio_classifier({"array": array, "sampling_rate": sr}, top_k=4)
|
| 115 |
+
|
| 116 |
+
scores = initialize_score_dict()
|
| 117 |
+
normalized = []
|
| 118 |
+
|
| 119 |
+
for item in preds:
|
| 120 |
+
mapped = normalize_audio_label(item["label"])
|
| 121 |
+
if mapped:
|
| 122 |
+
scores[mapped] += item["score"]
|
| 123 |
+
normalized.append({"label": mapped, "score": item["score"]})
|
| 124 |
+
|
| 125 |
+
return sorted(normalized, key=lambda x: x["score"], reverse=True), scores
|
| 126 |
+
|
| 127 |
+
# ---------- FUSION ----------
|
| 128 |
+
|
| 129 |
+
def fuse_scores(text_scores, audio_scores):
|
| 130 |
+
fused_scores = {}
|
| 131 |
+
|
| 132 |
+
for label in CANONICAL_LABELS:
|
| 133 |
+
fused_scores[label] = (
|
| 134 |
+
TEXT_WEIGHT * text_scores.get(label, 0.0) +
|
| 135 |
+
AUDIO_WEIGHT * audio_scores.get(label, 0.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
)
|
| 137 |
|
| 138 |
+
best_label = max(fused_scores, key=fused_scores.get)
|
| 139 |
+
return best_label, fused_scores[best_label]
|
| 140 |
+
|
| 141 |
+
# ---------- IMAGE ----------
|
| 142 |
+
|
| 143 |
+
def run_image(image):
|
| 144 |
+
if image is None:
|
| 145 |
+
return "No image.", "No classification.", "No evaluation."
|
| 146 |
+
|
| 147 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 148 |
+
|
| 149 |
+
with torch.no_grad():
|
| 150 |
+
output = image_model.generate(**inputs, max_new_tokens=30)
|
| 151 |
+
|
| 152 |
+
caption = image_processor.decode(output[0], skip_special_tokens=True)
|
| 153 |
+
|
| 154 |
+
preds = image_classifier(image)[:3]
|
| 155 |
+
classification = "\n".join([f"{p['label']} ({p['score']:.4f})" for p in preds])
|
| 156 |
+
|
| 157 |
+
return caption, classification, "Completed"
|
| 158 |
+
|
| 159 |
+
# ---------- MAIN MULTIMODAL ----------
|
| 160 |
+
|
| 161 |
+
def run_audio_text(audio_input, transcript):
|
| 162 |
+
|
| 163 |
+
if audio_input is None:
|
| 164 |
+
return "No audio provided.", "", "", ""
|
| 165 |
+
|
| 166 |
+
sr, audio_array = audio_input
|
| 167 |
+
|
| 168 |
+
audio = {
|
| 169 |
+
"array": np.asarray(audio_array, dtype=np.float32),
|
| 170 |
+
"sampling_rate": int(sr)
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
text_preds, text_scores = predict_text_emotion(transcript)
|
| 174 |
+
audio_preds, audio_scores = predict_audio_emotion(audio)
|
| 175 |
+
|
| 176 |
+
fused_label, fused_score = fuse_scores(text_scores, audio_scores)
|
| 177 |
+
|
| 178 |
+
return (
|
| 179 |
+
transcript if transcript else "No transcript",
|
| 180 |
+
format_top_predictions(text_preds),
|
| 181 |
+
format_top_predictions(audio_preds),
|
| 182 |
+
f"{fused_label.upper()} (confidence: {fused_score:.4f})"
|
| 183 |
)
|
| 184 |
|
| 185 |
+
# ---------- UI ----------
|
| 186 |
+
|
| 187 |
+
with gr.Blocks() as demo:
|
| 188 |
+
|
| 189 |
+
gr.Markdown("# Multimodal AI System")
|
| 190 |
+
|
| 191 |
+
with gr.Tabs():
|
| 192 |
+
|
| 193 |
+
with gr.Tab("Audio + Text"):
|
| 194 |
+
audio = gr.Audio(type="numpy")
|
| 195 |
+
text = gr.Textbox()
|
| 196 |
+
|
| 197 |
+
out1 = gr.Textbox(label="Transcript")
|
| 198 |
+
out2 = gr.Textbox(label="Text Prediction")
|
| 199 |
+
out3 = gr.Textbox(label="Audio Prediction")
|
| 200 |
+
out4 = gr.Textbox(label="Fused Result")
|
| 201 |
+
|
| 202 |
+
btn = gr.Button("Run")
|
| 203 |
+
|
| 204 |
+
btn.click(run_audio_text, [audio, text], [out1, out2, out3, out4])
|
| 205 |
+
|
| 206 |
+
with gr.Tab("Image Analysis"):
|
| 207 |
+
image = gr.Image(type="pil")
|
| 208 |
+
|
| 209 |
+
cap = gr.Textbox(label="Caption")
|
| 210 |
+
cls = gr.Textbox(label="Classification")
|
| 211 |
+
eval = gr.Textbox(label="Status")
|
| 212 |
+
|
| 213 |
+
btn2 = gr.Button("Run Image")
|
| 214 |
+
|
| 215 |
+
btn2.click(run_image, image, [cap, cls, eval])
|
| 216 |
|
| 217 |
+
demo.launch()
|
|
|