ProfRom commited on
Commit
5a12058
·
verified ·
1 Parent(s): eeeb737

Morrison 2 - Final submission

Browse files
Files changed (1) hide show
  1. app.py +321 -27
app.py CHANGED
@@ -1,44 +1,338 @@
 
 
 
 
 
1
  import torch
2
  import gradio as gr
3
  from PIL import Image
4
- from transformers import BlipProcessor, BlipForQuestionAnswering
 
5
 
6
- MODEL_ID = "Salesforce/blip-vqa-base"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
9
 
10
- processor = BlipProcessor.from_pretrained(MODEL_ID)
11
- model = BlipForQuestionAnswering.from_pretrained(MODEL_ID).to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- def answer_question(image, question):
14
- if image is None:
15
- return "Please upload an image."
16
- if not question or question.strip() == "":
17
- return "Please enter a question about the image."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- if not isinstance(image, Image.Image):
20
- image = Image.fromarray(image)
 
 
 
 
 
 
 
 
 
21
 
22
- image = image.convert("RGB")
 
 
 
 
 
 
 
 
 
23
 
24
- inputs = processor(image, question, return_tensors="pt").to(device)
 
 
25
 
26
- with torch.no_grad():
27
- output_ids = model.generate(**inputs, max_new_tokens=20)
 
 
28
 
29
- answer = processor.decode(output_ids[0], skip_special_tokens=True)
30
- return answer
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- demo = gr.Interface(
33
- fn=answer_question,
34
- inputs=[
35
- gr.Image(type="pil", label="Upload an Image"),
36
- gr.Textbox(label="Ask a Question", placeholder="Example: What animal is in this image?")
37
- ],
38
- outputs=gr.Textbox(label="Model Answer"),
39
- title="BLIP Visual Question Answering",
40
- description="Upload an image and ask a question. This app uses Salesforce/blip-vqa-base."
41
  )
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  if __name__ == "__main__":
44
  demo.launch()
 
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()