Workpam commited on
Commit
9aa248c
·
verified ·
1 Parent(s): b02a4db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +235 -192
app.py CHANGED
@@ -1,208 +1,251 @@
1
  import gradio as gr
2
- from transformers import AutoProcessor, LlavaForConditionalGeneration
3
  from PIL import Image
4
  import torch
 
5
  import json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # --- Device / dtype selection ---
8
- use_cuda = torch.cuda.is_available()
9
- dtype = torch.float16 if use_cuda else torch.float32 # float16 only on GPU
10
- device = "cuda" if use_cuda else "cpu"
11
-
12
- model_name = "llava-hf/llava-v1.6-mistral-7b-hf"
13
-
14
- # Load processor and model. Let HF handle device placement if using device_map.
15
- processor = AutoProcessor.from_pretrained(model_name)
16
 
17
- model = LlavaForConditionalGeneration.from_pretrained(
18
- model_name,
19
- torch_dtype=dtype,
20
- device_map="auto" if use_cuda else None,
21
- )
22
- model.eval()
23
-
24
- # System instruction: explicit schema for structured JSON output
25
- SYSTEM_INSTRUCTION = (
26
- "You are an assistant that generates detailed alt text for images. "
27
- "Produce a JSON object with these keys:\n"
28
- "1. main_objects: list of the primary objects/things in the image.\n"
29
- "2. visible_text: any readable text (quote it); null if none.\n"
30
- "3. background: description of the background (excluding main objects).\n"
31
- "4. colors_materials: dominant colors, textures, materials visible.\n"
32
- "5. spatial_relationships: how objects relate/are positioned relative to each other.\n"
33
- "6. uncertainties: list of things you are unsure about (use qualifiers like 'appears to be', 'possibly').\n"
34
- "7. summary_alt_text: one concise sentence suitable as alt text for accessibility.\n"
35
- "After the JSON, also provide a short human-readable paragraph summarizing the scene."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  )
37
 
38
- def generate_structured_alt_text(image: Image.Image) -> dict:
39
- """
40
- Returns a dict with structured fields plus a fallback message if on CPU.
41
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  try:
43
- image = image.convert("RGB")
44
-
45
- # CPU fallback / performance adjustments
46
- if not use_cuda:
47
- # aggressively resize to keep inference lightweight
48
- max_side = 800
49
- if max(image.size) > max_side:
50
- scale = max_side / max(image.size)
51
- image = image.resize((int(image.width * scale), int(image.height * scale)), Image.BICUBIC)
 
 
 
 
 
 
52
  else:
53
- # on GPU, cap size but allow higher fidelity
54
- max_side = 1024
55
- if max(image.size) > max_side:
56
- scale = max_side / max(image.size)
57
- image = image.resize((int(image.width * scale), int(image.height * scale)), Image.BICUBIC)
58
-
59
- # Build conversation with schema request
60
- user_prompt = (
61
- "Please analyze the image and output the JSON as per the system schema. "
62
- "Focus on objects, text, background, colors, spatial layout, and uncertainties. "
63
- "Then give a concise alt-text sentence."
64
- )
65
- conversation = [
66
- {"role": "system", "content": SYSTEM_INSTRUCTION},
67
- {
68
- "role": "user",
69
- "content": [
70
- {"type": "image", "image": image},
71
- {"type": "text", "text": user_prompt},
72
- ],
73
- },
74
- ]
75
-
76
- with torch.inference_mode():
77
- inputs = processor.apply_chat_template(
78
- conversation,
79
- add_generation_prompt=True,
80
- tokenize=True,
81
- return_tensors="pt",
82
- )
83
- # Move to model device
84
- for k, v in inputs.items():
85
- inputs[k] = v.to(model.device)
86
-
87
- # Adjust generation params depending on device
88
- if use_cuda:
89
- gen_kwargs = dict(
90
- **inputs,
91
- max_new_tokens=150,
92
- do_sample=True,
93
- temperature=0.7,
94
- top_p=0.9,
95
- repetition_penalty=1.1,
96
- early_stopping=True,
97
- )
98
- else:
99
- # CPU: deterministic, shorter, less sampling for speed/stability
100
- gen_kwargs = dict(
101
- **inputs,
102
- max_new_tokens=100,
103
- do_sample=False, # greedy
104
- early_stopping=True,
105
- )
106
-
107
- output_ids = model.generate(**gen_kwargs)
108
- raw_output = processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
109
-
110
- # Attempt to split JSON and narrative
111
- structured = {}
112
- narrative = ""
113
- try:
114
- # Heuristic: locate first '{' and matching '}' to extract JSON
115
- first_brace = raw_output.find("{")
116
- if first_brace != -1:
117
- # naive brace matching
118
- depth = 0
119
- for idx in range(first_brace, len(raw_output)):
120
- if raw_output[idx] == "{":
121
- depth += 1
122
- elif raw_output[idx] == "}":
123
- depth -= 1
124
- if depth == 0:
125
- json_text = raw_output[first_brace: idx + 1]
126
- # Parse JSON (allow trailing commas / minor fixes)
127
- structured = json.loads(json_text.replace("\n", " ").strip())
128
- narrative = raw_output[idx + 1 :].strip()
129
- break
130
- if not structured:
131
- # Fallback: try to parse entire output as JSON
132
- structured = json.loads(raw_output)
133
- else:
134
- # No JSON detected; fallback to putting entire caption into summary_alt_text
135
- narrative = raw_output
136
- except Exception:
137
- # Parsing failed: fall back to minimal structure
138
- structured = {
139
- "main_objects": None,
140
- "visible_text": None,
141
- "background": None,
142
- "colors_materials": None,
143
- "spatial_relationships": None,
144
- "uncertainties": None,
145
- "summary_alt_text": None,
146
- }
147
  narrative = raw_output
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- # Ensure summary_alt_text exists
150
- if not structured.get("summary_alt_text"):
151
- # Create a one-sentence alt text from narrative or main_objects
152
- if narrative:
153
- # naive truncation
154
- structured["summary_alt_text"] = narrative.split(".")[0].strip() + "."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  else:
156
- structured["summary_alt_text"] = "Image description unavailable."
157
-
158
- result = {
159
- "structured": structured,
160
- "narrative": narrative,
161
- "device": device,
162
- "note": (
163
- "Running on CPU: output is shorter and deterministic." if not use_cuda else "Running on GPU: full-quality generation."
164
- ),
165
- }
166
- return result
167
-
168
- except RuntimeError as e:
169
- if "out of memory" in str(e).lower():
170
- if use_cuda:
171
- torch.cuda.empty_cache()
172
- return {"error": "Out of memory during generation. Try smaller image or reduce tokens."}
173
- return {"error": f"Runtime error during generation: {e}"}
174
- except Exception as e:
175
- return {"error": f"Unexpected error: {e}"}
176
-
177
-
178
- def gradio_wrapper(image: Image.Image):
179
- out = generate_structured_alt_text(image)
180
- # Format output: pretty JSON plus narrative
181
- if "error" in out:
182
- return out["error"]
183
- structured = out["structured"]
184
- human_readable = out["narrative"]
185
- # Combine into a display string
186
- display = "Structured JSON:\n"
187
- try:
188
- display += json.dumps(structured, indent=2, ensure_ascii=False)
189
- except Exception:
190
- display += str(structured)
191
- display += f"\n\nNarrative summary:\n{human_readable}\n\n(Note: {out['note']})"
192
- return display
193
-
194
-
195
- iface = gr.Interface(
196
- fn=gradio_wrapper,
197
- inputs=gr.Image(type="pil"),
198
- outputs=gr.Textbox(label="Structured Alt Text + Summary", lines=15),
199
- title="Structured Alt Text Generator (LLaVA) with CPU Fallback",
200
- description=(
201
- "Generates a JSON breakdown of the image (objects, text, background, etc.) plus a concise alt-text sentence. "
202
- "If running on CPU, it automatically falls back to a lighter generation mode."
203
- ),
204
- allow_flagging="never",
205
- )
206
 
207
  if __name__ == "__main__":
208
  iface.launch()
 
1
  import gradio as gr
 
2
  from PIL import Image
3
  import torch
4
+ import hashlib
5
  import json
6
+ from functools import lru_cache
7
+
8
+ # ---- Try loading LLaVA first (8-bit, low memory) ----
9
+ use_llava = False
10
+ use_blip2 = False
11
+ llava_model = None
12
+ llava_processor = None
13
+ blip2_model = None
14
+ blip2_processor = None
15
+
16
+ def safe_hash_image(img: Image.Image) -> str:
17
+ h = hashlib.sha256()
18
+ with img.convert("RGB") as im:
19
+ im_bytes = im.resize((256, 256)).tobytes()
20
+ h.update(im_bytes)
21
+ return h.hexdigest()
22
+
23
+
24
+ def try_load_llava():
25
+ global llava_model, llava_processor, use_llava
26
+ try:
27
+ from transformers import AutoProcessor, LlavaForConditionalGeneration
28
+
29
+ model_name = "llava-hf/llava-v1.6-mistral-7b-hf"
30
+ llava_processor = AutoProcessor.from_pretrained(model_name)
31
+ llava_model = LlavaForConditionalGeneration.from_pretrained(
32
+ model_name,
33
+ load_in_8bit=True, # quantize to 8-bit
34
+ device_map="auto", # let HF distribute
35
+ low_cpu_mem_usage=True,
36
+ trust_remote_code=True,
37
+ )
38
+ llava_model.eval()
39
+ use_llava = True
40
+ print("Loaded LLaVA in 8-bit mode.")
41
+ except Exception as e:
42
+ print(f"LLaVA load failed, will fallback to BLIP-2. Reason: {e}")
43
 
 
 
 
 
 
 
 
 
 
44
 
45
+ def try_load_blip2():
46
+ global blip2_model, blip2_processor, use_blip2
47
+ try:
48
+ from transformers import Blip2Processor, Blip2ForConditionalGeneration
49
+
50
+ fallback_name = "Salesforce/blip2-flan-t5-base"
51
+ blip2_processor = Blip2Processor.from_pretrained(fallback_name)
52
+ blip2_model = Blip2ForConditionalGeneration.from_pretrained(
53
+ fallback_name,
54
+ device_map="auto" if torch.cuda.is_available() else None,
55
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
56
+ )
57
+ blip2_model.eval()
58
+ use_blip2 = True
59
+ print("Loaded BLIP-2 fallback model.")
60
+ except Exception as e:
61
+ print(f"BLIP-2 load failed too: {e}")
62
+
63
+
64
+ # Load models at startup
65
+ try_load_llava()
66
+ if not use_llava:
67
+ try_load_blip2()
68
+ elif not torch.cuda.is_available():
69
+ # If LLaVA is loaded but only CPU is present, might still be heavy; optionally fall back
70
+ # Keep LLaVA but warning in output if memory becomes an issue.
71
+ pass
72
+
73
+ # Common system instruction for structured output
74
+ STRUCTURE_INSTRUCTION = (
75
+ "Produce a JSON object with keys:\n"
76
+ "1. main_objects: list of primary objects.\n"
77
+ "2. visible_text: any readable text in quotes or null.\n"
78
+ "3. background: description of background excluding main objects.\n"
79
+ "4. colors_materials: dominant colors/textures/materials.\n"
80
+ "5. spatial_relationships: relative positions of objects.\n"
81
+ "6. uncertainties: things not certain.\n"
82
+ "7. summary_alt_text: concise one-sentence alt text.\n"
83
+ "After the JSON, add a short human-readable paragraph summarizing the image."
84
  )
85
 
86
+ def generate_with_llava(image: Image.Image) -> str:
87
+ from transformers import AutoProcessor
88
+
89
+ # Resize moderately to save memory
90
+ max_side = 1024
91
+ if max(image.size) > max_side:
92
+ scale = max_side / max(image.size)
93
+ image = image.resize((int(image.width * scale), int(image.height * scale)), Image.BICUBIC)
94
+ conversation = [
95
+ {"role": "system", "content": STRUCTURE_INSTRUCTION},
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image},
100
+ {
101
+ "type": "text",
102
+ "text": "Analyze and output as described."
103
+ },
104
+ ],
105
+ },
106
+ ]
107
+ with torch.inference_mode():
108
+ inputs = llava_processor.apply_chat_template(
109
+ conversation,
110
+ add_generation_prompt=True,
111
+ tokenize=True,
112
+ return_tensors="pt",
113
+ )
114
+ for k, v in inputs.items():
115
+ inputs[k] = v.to(llava_model.device)
116
+ gen_kwargs = dict(
117
+ **inputs,
118
+ max_new_tokens=150,
119
+ do_sample=True,
120
+ temperature=0.7,
121
+ top_p=0.9,
122
+ repetition_penalty=1.1,
123
+ early_stopping=True,
124
+ )
125
+ output_ids = llava_model.generate(**gen_kwargs)
126
+ raw = llava_processor.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
127
+ return raw
128
+
129
+ def generate_with_blip2(image: Image.Image) -> str:
130
+ from transformers import Blip2Processor
131
+
132
+ prompt = (
133
+ STRUCTURE_INSTRUCTION
134
+ + " Analyze the image and respond."
135
+ )
136
+ # Resize a bit to keep CPU reasonable
137
+ max_side = 800 if not torch.cuda.is_available() else 1024
138
+ if max(image.size) > max_side:
139
+ scale = max_side / max(image.size)
140
+ image = image.resize((int(image.width * scale), int(image.height * scale)), Image.BICUBIC)
141
+
142
+ inputs = blip2_processor(images=image, text=prompt, return_tensors="pt")
143
+ for k, v in inputs.items():
144
+ inputs[k] = v.to(blip2_model.device) if hasattr(blip2_model, "device") else v
145
+ with torch.inference_mode():
146
+ generated_ids = blip2_model.generate(**inputs, max_new_tokens=140, early_stopping=True)
147
+ raw = blip2_processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
148
+ return raw
149
+
150
+ def extract_structured_and_narrative(raw_output: str) -> (dict, str):
151
+ structured = {}
152
+ narrative = ""
153
  try:
154
+ first_brace = raw_output.find("{")
155
+ if first_brace != -1:
156
+ depth = 0
157
+ for idx in range(first_brace, len(raw_output)):
158
+ if raw_output[idx] == "{":
159
+ depth += 1
160
+ elif raw_output[idx] == "}":
161
+ depth -= 1
162
+ if depth == 0:
163
+ json_text = raw_output[first_brace: idx + 1]
164
+ structured = json.loads(json_text.replace("\n", " ").strip())
165
+ narrative = raw_output[idx + 1 :].strip()
166
+ break
167
+ if not structured:
168
+ structured = json.loads(raw_output)
169
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  narrative = raw_output
171
+ except Exception:
172
+ structured = {
173
+ "main_objects": None,
174
+ "visible_text": None,
175
+ "background": None,
176
+ "colors_materials": None,
177
+ "spatial_relationships": None,
178
+ "uncertainties": None,
179
+ "summary_alt_text": None,
180
+ }
181
+ narrative = raw_output
182
 
183
+ if not structured.get("summary_alt_text"):
184
+ if narrative:
185
+ structured["summary_alt_text"] = narrative.split(".")[0].strip() + "."
186
+ else:
187
+ structured["summary_alt_text"] = "Description unavailable."
188
+
189
+ return structured, narrative
190
+
191
+ # Cache results per image hash to avoid recompute in session
192
+ @lru_cache(maxsize=128)
193
+ def generate_cached(image_hash: str, use_llava_flag: bool, use_blip2_flag: bool, raw_bytes: bytes) -> dict:
194
+ # raw_bytes is a dummy to make hashable; we only use image_hash to key.
195
+ # In practice, caller will pass image_bytes for uniqueness.
196
+ dummy_image = Image.frombytes("RGB", (1,1), b"\x00") # unused
197
+ # This wrapper won't be used; actual generation happens in wrapper below.
198
+ return {}
199
+
200
+ def pipeline(image: Image.Image) -> str:
201
+ if image is None:
202
+ return "No image provided."
203
+ # Decide which model to use
204
+ if use_llava:
205
+ try:
206
+ raw = generate_with_llava(image)
207
+ structured, narrative = extract_structured_and_narrative(raw)
208
+ note = "LLaVA (8-bit) used."
209
+ except Exception as e:
210
+ raw = f"LLaVA generation failed: {e}"
211
+ if use_blip2:
212
+ raw = generate_with_blip2(image)
213
+ structured, narrative = extract_structured_and_narrative(raw)
214
+ note = "Fell back to BLIP-2 after LLaVA error."
215
  else:
216
+ return f"Both models failed. Last error: {e}"
217
+ elif use_blip2:
218
+ try:
219
+ raw = generate_with_blip2(image)
220
+ structured, narrative = extract_structured_and_narrative(raw)
221
+ note = "BLIP-2 used."
222
+ except Exception as e:
223
+ return f"BLIP-2 generation failed: {e}"
224
+ else:
225
+ return "No model loaded."
226
+
227
+ # Compose display
228
+ out = {
229
+ "structured": structured,
230
+ "narrative": narrative,
231
+ "note": note,
232
+ }
233
+ pretty = "Structured JSON:\n" + json.dumps(structured, indent=2, ensure_ascii=False)
234
+ pretty += f"\n\nNarrative summary:\n{narrative}\n\n(Note: {note})"
235
+ return pretty
236
+
237
+ # Gradio UI
238
+ with gr.Blocks() as iface:
239
+ gr.Markdown("## Structured Alt Text Generator — LLaVA with BLIP-2 Fallback")
240
+ with gr.Row():
241
+ inp = gr.Image(type="pil", label="Upload Image")
242
+ out = gr.Textbox(label="Output (JSON + Summary)", lines=18)
243
+ btn = gr.Button("Describe Image")
244
+ btn.click(fn=pipeline, inputs=inp, outputs=out)
245
+ gr.Markdown(
246
+ "👆 If LLaVA fails due to memory constraints, the system automatically falls back to BLIP-2. "
247
+ "For best performance on LLaVA, deploy with a GPU-backed Space."
248
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
  if __name__ == "__main__":
251
  iface.launch()