Workpam commited on
Commit
caefe12
·
verified ·
1 Parent(s): bf144eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -17
app.py CHANGED
@@ -2,6 +2,7 @@ import gradio as gr
2
  from transformers import pipeline
3
  from PIL import Image
4
  import torch
 
5
 
6
  # --- Model Setup ---
7
  # Qwen2.5-VL-7B-Instruct for rich, instruction-tuned image-to-text
@@ -16,29 +17,29 @@ captioner = pipeline(
16
  trust_remote_code=True
17
  )
18
 
 
 
 
 
 
 
19
  # --- Core Function ---
20
  def generate_alt_text(files, max_new_tokens):
21
- """
22
- Generate detailed, instruction-tuned alt text for uploaded images.
23
- """
24
  captions = []
25
  for f in files or []:
26
- # Load and preprocess image
27
  img = Image.open(f.name).convert("RGB")
28
- # Generate caption using Qwen2.5-VL
29
- result = captioner(
30
- img,
31
- generate_kwargs={
32
- "max_new_tokens": int(max_new_tokens),
33
- "num_beams": 4,
34
- "do_sample": False
35
- }
36
  )
37
- text = result[0]["generated_text"].strip()
38
- # Capitalize first letter
39
- if text:
40
- text = text[0].upper() + text[1:]
41
- captions.append(text)
42
  return "\n\n".join(captions)
43
 
44
  # --- Gradio Interface ---
 
2
  from transformers import pipeline
3
  from PIL import Image
4
  import torch
5
+ from transformers import AutoProcessor, AutoModelForCausalLM
6
 
7
  # --- Model Setup ---
8
  # Qwen2.5-VL-7B-Instruct for rich, instruction-tuned image-to-text
 
17
  trust_remote_code=True
18
  )
19
 
20
+ processor = AutoProcessor.from_pretrained(MODEL_NAME, trust_remote_code=True)
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ MODEL_NAME,
23
+ trust_remote_code=True
24
+ ).to(DEVICE)
25
+
26
  # --- Core Function ---
27
  def generate_alt_text(files, max_new_tokens):
 
 
 
28
  captions = []
29
  for f in files or []:
 
30
  img = Image.open(f.name).convert("RGB")
31
+ # 1) preprocess
32
+ inputs = processor(images=img, return_tensors="pt").to(DEVICE)
33
+ # 2) generate
34
+ outputs = model.generate(
35
+ **inputs,
36
+ max_new_tokens=int(max_new_tokens),
37
+ num_beams=4,
38
+ do_sample=False
39
  )
40
+ # 3) decode
41
+ cap = processor.decode(outputs[0], skip_special_tokens=True).strip().capitalize()
42
+ captions.append(cap)
 
 
43
  return "\n\n".join(captions)
44
 
45
  # --- Gradio Interface ---