Afsha001 commited on
Commit
25245f2
Β·
1 Parent(s): c1b05fd

add app.py and requirements.txt

Browse files
Files changed (2) hide show
  1. app.py +390 -143
  2. requirements.txt +10 -4
app.py CHANGED
@@ -1,154 +1,401 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
 
7
  import torch
 
 
 
 
 
 
 
 
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
-
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
 
 
81
 
82
- result = gr.Image(label="Result", show_label=False)
83
 
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
- if __name__ == "__main__":
154
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ import os
3
+ import re
4
+ import time
5
  import torch
6
+ import numpy as np
7
+ import requests
8
+ import streamlit as st
9
+ from PIL import Image
10
+ from io import BytesIO
11
+ from collections import Counter
12
+ from sklearn.metrics.pairwise import cosine_similarity
13
+ from sklearn.preprocessing import normalize
14
 
15
+ # ── Page config ──
16
+ st.set_page_config(
17
+ page_title = "Image Caption Fusion",
18
+ page_icon = "πŸ–ΌοΈ",
19
+ layout = "wide"
20
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ # ── API Keys from HF Secrets ──
23
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
24
+ JINA_KEY = os.environ.get("JINA_KEY", "")
25
 
26
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
27
 
28
+ # ── API endpoints ──
29
+ QWEN_VL_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2-VL-2B-Instruct"
30
+ QWEN_LM_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-1.5B-Instruct"
31
+ JINA_URL = "https://api.jina.ai/v1/rerank"
32
+
33
+ HF_HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
34
+ JINA_HEADERS = {"Authorization": f"Bearer {JINA_KEY}", "Content-Type": "application/json"}
35
+
36
+ DETECT_PROMPT = (
37
+ "person . child . man . woman . boy . girl . "
38
+ "dog . cat . horse . bird . animal . "
39
+ "ball . toy . bicycle . car . bench . "
40
+ "tree . grass . water . sky . mountain . "
41
+ "building . stairs . door . fence . floor . "
42
+ "jacket . dress . shirt . hat . bag ."
43
+ )
44
+
45
+ # ── Load local models once at startup ──
46
+ @st.cache_resource
47
+ def load_local_models():
48
+ from transformers import (
49
+ BlipProcessor, BlipForImageTextRetrieval,
50
+ AutoProcessor, AutoModelForZeroShotObjectDetection
51
+ )
52
+
53
+ st.write("⏳ Loading BLIP ITM model (CPU)...")
54
+ blip_processor = BlipProcessor.from_pretrained(
55
+ "Salesforce/blip-image-captioning-large"
56
+ )
57
+ itm_model = BlipForImageTextRetrieval.from_pretrained(
58
+ "Salesforce/blip-itm-large-coco",
59
+ torch_dtype = torch.float32
60
+ )
61
+ itm_model.eval()
62
+
63
+ st.write(" Loading DINO model (CPU)...")
64
+ dino_processor = AutoProcessor.from_pretrained(
65
+ "IDEA-Research/grounding-dino-base"
66
+ )
67
+ dino_model = AutoModelForZeroShotObjectDetection.from_pretrained(
68
+ "IDEA-Research/grounding-dino-base",
69
+ torch_dtype = torch.float32
70
+ )
71
+ dino_model.eval()
72
+
73
+ return blip_processor, itm_model, dino_processor, dino_model
74
+
75
+ # ── Step 2: BLIP ITM Scoring (local CPU) ──
76
+ def compute_itm_scores(image, captions, blip_processor, itm_model):
77
+ scores = []
78
+ for cap in captions:
79
+ inp = blip_processor(
80
+ images=image, text=cap,
81
+ return_tensors="pt", padding=True
82
+ )
83
+ with torch.no_grad():
84
+ out = itm_model(**inp)
85
+ score = torch.nn.functional.softmax(
86
+ out.itm_score, dim=1
87
+ )[:, 1].item()
88
+ scores.append(round(score, 4))
89
+ return scores
90
 
91
+ # ── Step 3: Jina Reranker Scoring (API) ──
92
+ def compute_jina_scores(image, captions):
93
+ buffered = BytesIO()
94
+ image.save(buffered, format="JPEG")
95
+ img_b64 = __import__("base64").b64encode(buffered.getvalue()).decode()
96
+
97
+ scores = []
98
+ for cap in captions:
99
+ try:
100
+ payload = {
101
+ "model" : "jina-reranker-m0",
102
+ "query" : cap,
103
+ "documents" : [{"type": "image_url",
104
+ "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}}]
105
+ }
106
+ response = requests.post(
107
+ JINA_URL,
108
+ headers = JINA_HEADERS,
109
+ json = payload,
110
+ timeout = 30
111
  )
112
+ if response.status_code == 200:
113
+ result = response.json()
114
+ score = result["results"][0]["relevance_score"]
115
+ scores.append(round(float(score), 4))
116
+ else:
117
+ scores.append(0.5)
118
+ except:
119
+ scores.append(0.5)
120
+ return scores
121
+
122
+ # ── Step 4: Cosine Similarity Scoring (local numpy) ──
123
+ def compute_cosine_scores(image, captions, blip_processor, itm_model):
124
+ # Get image embedding
125
+ img_inp = blip_processor(images=image, return_tensors="pt")
126
+ with torch.no_grad():
127
+ vis_out = itm_model.vision_model(
128
+ pixel_values=img_inp["pixel_values"]
129
+ )
130
+ img_feat = itm_model.vision_proj(
131
+ vis_out.last_hidden_state[:, 0, :]
132
+ ).numpy()
133
+ img_feat = normalize(img_feat, norm="l2")
134
+
135
+ # Get caption embeddings
136
+ cap_inp = blip_processor(
137
+ text=captions, return_tensors="pt",
138
+ padding=True, truncation=True, max_length=512
139
+ )
140
+ with torch.no_grad():
141
+ txt_out = itm_model.text_encoder(
142
+ input_ids = cap_inp["input_ids"],
143
+ attention_mask = cap_inp["attention_mask"]
144
+ )
145
+ cap_feat = itm_model.text_proj(
146
+ txt_out.last_hidden_state[:, 0, :]
147
+ ).numpy()
148
+ cap_feat = normalize(cap_feat, norm="l2")
149
+
150
+ scores = cosine_similarity(img_feat, cap_feat)[0]
151
+ return [round(float(s), 4) for s in scores]
152
+
153
+ # ── Step 5: Majority Voting ──
154
+ def majority_voting(captions, itm_scores, jina_scores, cosine_scores):
155
+ itm_ranked = np.argsort(itm_scores)[::-1]
156
+ jina_ranked = np.argsort(jina_scores)[::-1]
157
+ cos_ranked = np.argsort(cosine_scores)[::-1]
158
+
159
+ votes = [
160
+ int(itm_ranked[0]), int(itm_ranked[1]),
161
+ int(jina_ranked[0]), int(jina_ranked[1]),
162
+ int(cos_ranked[0]), int(cos_ranked[1]),
163
+ ]
164
+
165
+ vote_counts = Counter(votes)
166
+ top2_indices = [idx for idx, _ in vote_counts.most_common(2)]
167
 
168
+ if len(top2_indices) < 2:
169
+ top2_indices = [int(itm_ranked[0]), int(jina_ranked[0])]
170
+
171
+ return (
172
+ captions[top2_indices[0]],
173
+ captions[top2_indices[1]],
174
+ top2_indices,
175
+ dict(vote_counts)
176
+ )
177
+
178
+ # ── Step 6: DINO Object Detection (local CPU) ──
179
+ def detect_objects(image, dino_processor, dino_model, threshold=0.3):
180
+ inp = dino_processor(
181
+ images=image, text=DETECT_PROMPT,
182
+ return_tensors="pt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  )
184
+ with torch.no_grad():
185
+ outputs = dino_model(**inp)
186
+
187
+ target_sizes = torch.tensor([image.size[::-1]])
188
+ results = dino_processor.post_process_grounded_object_detection(
189
+ outputs, inp.input_ids,
190
+ target_sizes=target_sizes
191
+ )[0]
192
+
193
+ scores = results["scores"]
194
+ labels = results["labels"]
195
+ keep = scores >= threshold
196
+ labels = [labels[i] for i in range(len(labels)) if keep[i]]
197
+ sc_list= scores[keep].tolist()
198
+
199
+ if not labels:
200
+ return "No objects detected", []
201
+
202
+ seen = {}
203
+ for lbl, sc in zip(labels, sc_list):
204
+ lbl = lbl.strip().lower()
205
+ if lbl not in seen or seen[lbl] < sc:
206
+ seen[lbl] = sc
207
+
208
+ sorted_labels = [l for l, _ in sorted(seen.items(), key=lambda x: x[1], reverse=True)]
209
+ label_str = "Detected: [" + ", ".join(sorted_labels) + "]"
210
+ return label_str, sorted_labels
211
 
212
+ # ── Step 7: Qwen2.5-1.5B Caption Fusion (API) ──
213
+ def fuse_captions_api(cap1, cap2, dino_labels):
214
+ prompt = f"""You are given two captions and detected objects for the same image.
215
+ Write ONE fluent, natural, descriptive caption combining the best details.
216
+ Return ONLY the caption, no explanation, no prefix.
217
+
218
+ Caption 1 : {cap1}
219
+ Caption 2 : {cap2}
220
+ Detected objects : {dino_labels}
221
+
222
+ Fused caption :"""
223
+
224
+ try:
225
+ response = requests.post(
226
+ QWEN_LM_URL,
227
+ headers = HF_HEADERS,
228
+ json = {
229
+ "inputs" : prompt,
230
+ "parameters" : {
231
+ "max_new_tokens" : 80,
232
+ "do_sample" : False,
233
+ "repetition_penalty" : 1.1,
234
+ "return_full_text" : False
235
+ }
236
+ },
237
+ timeout = 40
238
+ )
239
+ if response.status_code == 200:
240
+ result = response.json()
241
+ if isinstance(result, list):
242
+ fused = result[0].get("generated_text", "").strip()
243
+ else:
244
+ fused = str(result).strip()
245
+
246
+ # Clean any prefix Qwen adds
247
+ for prefix in ["Fused caption :", "Fused caption:", "Caption:"]:
248
+ if fused.lower().startswith(prefix.lower()):
249
+ fused = fused[len(prefix):].strip()
250
+ return fused if fused else cap1
251
+
252
+ else:
253
+ return cap1
254
+
255
+ except Exception as e:
256
+ return cap1
257
+
258
+ # ════════════════════════════════════════
259
+ # STREAMLIT UI
260
+ # ════════════════════════════════════════
261
+
262
+ # ── Sidebar ──
263
+ with st.sidebar:
264
+ st.title(" Image Caption Fusion")
265
+ st.markdown("---")
266
+ st.markdown("### Pipeline")
267
+ st.markdown("""
268
+ 1. **Qwen2-VL-2B** β€” Generate 5 captions
269
+ 2. **BLIP ITM** β€” Image-text matching score
270
+ 3. **Jina Reranker M0** β€” Semantic reranking
271
+ 4. **Cosine Similarity** β€” Embedding similarity
272
+ 5. **Majority Voting** β€” Best 2 captions
273
+ 6. **Grounding DINO** β€” Object detection
274
+ 7. **Qwen2.5-1.5B** β€” Caption fusion
275
+ """)
276
+ st.markdown("---")
277
+ st.markdown("### About")
278
+ st.markdown("""
279
+ This system generates a rich, humanized caption
280
+ for any image using a multi-model ensemble pipeline.
281
+ """)
282
+ st.markdown("---")
283
+ st.markdown("**Local models:** BLIP ITM, DINO")
284
+ st.markdown("**API models:** Qwen2-VL, Jina, Qwen2.5")
285
+
286
+ # ── Main area ──
287
+ st.title(" Image Caption Fusion System")
288
+ st.markdown("Upload any image and get a detailed, humanized caption.")
289
+ st.markdown("---")
290
+
291
+ uploaded = st.file_uploader(
292
+ " Upload an image",
293
+ type=["jpg", "jpeg", "png"],
294
+ help="Upload any image to generate a fused caption"
295
+ )
296
+
297
+ if uploaded:
298
+ image = Image.open(uploaded).convert("RGB")
299
+
300
+ col1, col2 = st.columns([1, 1])
301
+ with col1:
302
+ st.image(image, caption="Uploaded Image", use_column_width=True)
303
+
304
+ with col2:
305
+ if st.button(" Generate Caption", type="primary", use_container_width=True):
306
+
307
+ # Load local models
308
+ with st.spinner("Loading local models (first time takes ~2 min)..."):
309
+ blip_processor, itm_model, dino_processor, dino_model = load_local_models()
310
+
311
+ progress = st.progress(0)
312
+ status = st.empty()
313
+
314
+ # Step 1 β€” Generate captions
315
+ status.info(" Step 1/7 β€” Generating 5 captions with Qwen2-VL...")
316
+ captions = generate_captions_api(image)
317
+ progress.progress(14)
318
+
319
+ with st.expander(" 5 Generated Captions", expanded=False):
320
+ for i, c in enumerate(captions):
321
+ st.write(f"**{i+1}.** {c}")
322
+
323
+ # Step 2 β€” ITM scores
324
+ status.info(" Step 2/7 β€” Computing BLIP ITM scores...")
325
+ itm_scores = compute_itm_scores(image, captions, blip_processor, itm_model)
326
+ progress.progress(28)
327
+
328
+ # Step 3 β€” Jina scores
329
+ status.info(" Step 3/7 β€” Computing Jina Reranker scores...")
330
+ jina_scores = compute_jina_scores(image, captions)
331
+ progress.progress(42)
332
+
333
+ # Step 4 β€” Cosine scores
334
+ status.info(" Step 4/7 β€” Computing Cosine Similarity scores...")
335
+ cosine_scores = compute_cosine_scores(image, captions, blip_processor, itm_model)
336
+ progress.progress(57)
337
+
338
+ # Show score table
339
+ import pandas as pd
340
+ score_df = pd.DataFrame({
341
+ "Caption" : [f"Cap {i+1}: {c[:50]}..." for i, c in enumerate(captions)],
342
+ "ITM" : itm_scores,
343
+ "Jina" : jina_scores,
344
+ "Cosine" : cosine_scores
345
+ })
346
+ with st.expander(" All Scores", expanded=False):
347
+ st.dataframe(score_df, use_container_width=True)
348
+
349
+ # Step 5 β€” Majority voting
350
+ status.info(" Step 5/7 β€” Running Majority Voting...")
351
+ voted_cap1, voted_cap2, top2_idx, vote_counts = majority_voting(
352
+ captions, itm_scores, jina_scores, cosine_scores
353
+ )
354
+ progress.progress(71)
355
+
356
+ st.markdown("### Majority Voted Captions")
357
+ col_a, col_b = st.columns(2)
358
+ with col_a:
359
+ st.success(f" **Caption 1:**
360
+
361
+ {voted_cap1}")
362
+ with col_b:
363
+ st.info(f" **Caption 2:**
364
+
365
+ {voted_cap2}")
366
+
367
+ # Step 6 β€” DINO
368
+ status.info(" Step 6/7 β€” Detecting objects with DINO...")
369
+ label_str, label_list = detect_objects(image, dino_processor, dino_model)
370
+ progress.progress(85)
371
+
372
+ st.markdown("### Detected Objects")
373
+ if label_list:
374
+ cols = st.columns(min(len(label_list), 6))
375
+ for i, lbl in enumerate(label_list[:6]):
376
+ cols[i].markdown(
377
+ f"<span style='background:#e8f4fd;padding:4px 8px;"
378
+ f"border-radius:12px;font-size:13px'> {lbl}</span>",
379
+ unsafe_allow_html=True
380
+ )
381
+ else:
382
+ st.write(label_str)
383
+
384
+ # Step 7 β€” Qwen fusion
385
+ status.info("Step 7/7 β€” Fusing captions with Qwen2.5-1.5B...")
386
+ fused = fuse_captions_api(voted_cap1, voted_cap2, label_str)
387
+ progress.progress(100)
388
+ status.success(" Pipeline complete!")
389
+
390
+ # Final output
391
+ st.markdown("---")
392
+ st.markdown("### Final Fused Caption")
393
+ st.markdown(
394
+ f"<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);"
395
+ f"padding: 20px; border-radius: 12px; color: white; font-size: 18px;"
396
+ f"font-weight: 500; text-align: center;'>"
397
+ f" {fused}"
398
+ f"</div>",
399
+ unsafe_allow_html=True
400
+ )
401
+ st.markdown("---")
requirements.txt CHANGED
@@ -1,6 +1,12 @@
1
- accelerate
2
- diffusers
3
- invisible_watermark
 
 
4
  torch
5
  transformers
6
- xformers
 
 
 
 
 
1
+ streamlit
2
+ Pillow
3
+ numpy
4
+ scikit-learn
5
+ requests
6
  torch
7
  transformers
8
+ accelerate
9
+ einops
10
+ timm
11
+ supervision
12
+ huggingface_hub