ProfRom commited on
Commit
67f36ac
·
verified ·
1 Parent(s): ba336fe

Harting - Final submission

Browse files
Files changed (1) hide show
  1. app.py +200 -321
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
- from transformers import pipeline
10
- from datasets import load_dataset
11
-
12
- # Vocabulary dictionary covering Office-Home dataset classes + common COCO
13
- # household/office items DETR emits. Single-word keys are matched per-token in
14
- # captions and detection labels; multi-word keys (e.g. "dining table") are
15
- # matched as phrases.
16
- VOCAB_DICT = {
17
- # --- Furniture ---
18
- "chair": {"japanese": "いす", "romaji": "isu", "korean": "의자", "romanization": "uija"},
19
- "table": {"japanese": "テーブル", "romaji": "teeburu", "korean": "테이블", "romanization": "teibeul"},
20
- "dining table": {"japanese": "ダイニングテーブル", "romaji": "dainingu teeburu", "korean": "식탁", "romanization": "siktak"},
21
- "desk": {"japanese": "机", "romaji": "tsukue", "korean": "책상", "romanization": "chaeksang"},
22
- "bed": {"japanese": "ベッド", "romaji": "beddo", "korean": "침대", "romanization": "chimdae"},
23
- "couch": {"japanese": "ソファ", "romaji": "sofa", "korean": "소파", "romanization": "sopa"},
24
- "sofa": {"japanese": "ソファ", "romaji": "sofa", "korean": "소파", "romanization": "sopa"},
25
- "shelf": {"japanese": "棚", "romaji": "tana", "korean": "선반", "romanization": "seonban"},
26
- "curtain": {"japanese": "カーテン", "romaji": "kaaten", "korean": "커튼", "romanization": "keoteun"},
27
- "file cabinet": {"japanese": "ファイルキャビネット", "romaji": "fairu kyabinetto", "korean": "파일 캐비닛", "romanization": "pail kaebinit"},
28
-
29
- # --- Lighting / electrical ---
30
- "lamp": {"japanese": "ランプ", "romaji": "ranpu", "korean": "램프", "romanization": "raempeu"},
31
- "desk lamp": {"japanese": "デスクランプ", "romaji": "desuku ranpu", "korean": "책상 램프", "romanization": "chaeksang raempeu"},
32
- "lamp shade": {"japanese": "ランプシェード", "romaji": "ranpu sheedo", "korean": "램프 갓", "romanization": "raempeu gat"},
33
- "fan": {"japanese": "扇風機", "romaji": "senpuuki", "korean": "선풍기", "romanization": "seonpunggi"},
34
- "battery": {"japanese": "電池", "romaji": "denchi", "korean": "배터리", "romanization": "baeteori"},
35
- "candle": {"japanese": "ろうそく", "romaji": "rousoku", "korean": "양초", "romanization": "yangcho"},
36
-
37
- # --- Computing / electronics ---
38
- "laptop": {"japanese": "ノートパソコン", "romaji": "nooto pasokon", "korean": "노트북", "romanization": "noteubuk"},
39
- "computer": {"japanese": "コンピュータ", "romaji": "konpyuuta", "korean": "컴퓨터", "romanization": "keompyuteo"},
40
- "monitor": {"japanese": "モニター", "romaji": "monitaa", "korean": "모니터", "romanization": "moniteo"},
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
- # Pre-split single-word vs multi-word keys for efficient matching
127
- _SINGLE_WORD_KEYS = {k for k in VOCAB_DICT if " " not in k}
128
- _MULTI_WORD_KEYS = [k for k in VOCAB_DICT if " " in k]
129
 
130
- # Device setup
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
- # Load models globally as pipelines
136
- caption_pipeline = pipeline(
137
- "image-to-text",
138
- model="Salesforce/blip-image-captioning-base",
139
- device=DEVICE,
140
  )
141
 
142
- def generate_caption(image: Image.Image) -> str:
143
- """Generate caption using BLIP image-to-text pipeline."""
144
- out = caption_pipeline(image, max_new_tokens=50)
145
- if isinstance(out, list) and out and "generated_text" in out[0]:
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
- # Load up to 10 sample images from flwrlabs/office-home for one-click testing.
156
- # Filter to Office-Home classes whose label matches a key in VOCAB_DICT, so the
157
- # samples are guaranteed to produce vocab the app can actually translate. Dedupe
158
- # by class to maximize variety. Streaming mode avoids downloading the full dataset.
159
- SAMPLE_DIR = "sample_images"
160
- MAX_STREAM_SCAN = 2000 # safety cap so we don't iterate forever
161
-
162
- def load_sample_images(n: int = 10) -> List[str]:
163
- paths: List[str] = []
164
- try:
165
- os.makedirs(SAMPLE_DIR, exist_ok=True)
166
- ds = load_dataset("flwrlabs/office-home", split="train", streaming=True)
167
- class_names = ds.features["label"].names if "label" in ds.features else []
168
- seen_classes: set = set()
169
- for i, example in enumerate(ds):
170
- if len(paths) >= n or i >= MAX_STREAM_SCAN:
171
- break
172
- img = example.get("image")
173
- label_idx = example.get("label")
174
- if img is None or label_idx is None or not class_names:
175
- continue
176
- raw_label = class_names[label_idx]
177
- normalized = raw_label.lower().replace("_", "")
178
- if not any(vocab_key in normalized for vocab_key in VOCAB_DICT):
179
- continue
180
- if raw_label in seen_classes:
181
- continue
182
- seen_classes.add(raw_label)
183
- path = os.path.join(SAMPLE_DIR, f"sample_{len(paths):02d}_{raw_label}.jpg")
184
- img.convert("RGB").save(path, "JPEG")
185
- paths.append(path)
186
- except Exception as e:
187
- print(f"Could not load sample images from flwrlabs/office-home: {e}")
188
- return paths
189
-
190
- SAMPLE_PATHS = load_sample_images(10)
191
-
192
-
193
- def clean_text(text: str) -> str:
194
- """Clean and normalize text."""
195
- return re.sub(r"[^a-zA-Z\s]", "", text.lower()).strip()
196
-
197
-
198
- def extract_vocab_from_caption(caption: str) -> List[str]:
199
- """Extract vocab from caption text. Single-word keys match per-token;
200
- multi-word keys are matched as phrases."""
201
- cleaned = clean_text(caption)
202
- tokens = set(cleaned.split())
203
- matches = {k for k in _SINGLE_WORD_KEYS if k in tokens}
204
- matches.update(k for k in _MULTI_WORD_KEYS if k in cleaned)
205
- return list(matches)
206
-
207
-
208
- def extract_vocab_from_detection(detection_results: List[Dict]) -> List[str]:
209
- """Extract vocab from detection labels (often multi-word, e.g. 'dining table')."""
210
- matches = set()
211
- for res in detection_results:
212
- if res.get("score", 0) <= 0.5:
213
- continue
214
- label = res.get("label", "").lower()
215
- if label in VOCAB_DICT:
216
- matches.add(label)
217
- continue
218
- for token in label.split():
219
- if token in _SINGLE_WORD_KEYS:
220
- matches.add(token)
221
- return list(matches)
222
-
223
-
224
- def translate_term(term: str, lang: str) -> Dict[str, str]:
225
- """Translate term using dictionary."""
226
- if term not in VOCAB_DICT:
227
- return {"translation": "translation unavailable", "romanization": "N/A"}
228
- entry = VOCAB_DICT[term]
229
- if lang == "Japanese":
230
- return {"translation": entry["japanese"], "romanization": entry["romaji"]}
231
- elif lang == "Korean":
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
- generate_btn = gr.Button("Generate Flashcards")
322
-
323
- with gr.Row():
324
- caption_output = gr.Textbox(label="Image Caption", lines=2)
325
- detection_output = gr.Dataframe(label="Object Detection Results", headers=["Label", "Score", "Box"])
326
-
327
- flashcard_output = gr.Dataframe(label="Flashcard Table", headers=["English", "Translation", "Romanization", "Source"])
328
- stats_output = gr.Textbox(label="Comparison Statistics", lines=8)
329
-
330
- generate_btn.click(
331
- fn=process_image,
332
- inputs=[image_input, lang_input],
333
- outputs=[caption_output, detection_output, flashcard_output, stats_output],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  )
335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
 
337
- if __name__ == "__main__":
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()