akhaliq HF Staff commited on
Commit
f8d8011
·
verified ·
1 Parent(s): c59409d

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +162 -0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from PIL import Image
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM
5
+
6
+ # Model configuration
7
+ MID = "apple/FastVLM-0.5B"
8
+ IMAGE_TOKEN_INDEX = -200
9
+
10
+ # Load model and tokenizer once at startup
11
+ print("Loading model...")
12
+ tok = AutoTokenizer.from_pretrained(MID, trust_remote_code=True)
13
+ model = AutoModelForCausalLM.from_pretrained(
14
+ MID,
15
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
16
+ device_map="auto",
17
+ trust_remote_code=True,
18
+ )
19
+ print("Model loaded successfully!")
20
+
21
+ def caption_image(image, custom_prompt=None):
22
+ """
23
+ Generate a caption for the input image.
24
+
25
+ Args:
26
+ image: PIL Image from Gradio
27
+ custom_prompt: Optional custom prompt to use instead of default
28
+
29
+ Returns:
30
+ Generated caption text
31
+ """
32
+ if image is None:
33
+ return "Please upload an image first."
34
+
35
+ try:
36
+ # Convert image to RGB if needed
37
+ if image.mode != "RGB":
38
+ image = image.convert("RGB")
39
+
40
+ # Use custom prompt or default
41
+ prompt = custom_prompt if custom_prompt else "Describe this image in detail."
42
+
43
+ # Build chat message
44
+ messages = [
45
+ {"role": "user", "content": f"<image>\n{prompt}"}
46
+ ]
47
+
48
+ # Render to string to place <image> token correctly
49
+ rendered = tok.apply_chat_template(
50
+ messages, add_generation_prompt=True, tokenize=False
51
+ )
52
+
53
+ # Split at image token
54
+ pre, post = rendered.split("<image>", 1)
55
+
56
+ # Tokenize text around the image token
57
+ pre_ids = tok(pre, return_tensors="pt", add_special_tokens=False).input_ids
58
+ post_ids = tok(post, return_tensors="pt", add_special_tokens=False).input_ids
59
+
60
+ # Insert IMAGE token id at placeholder position
61
+ img_tok = torch.tensor([[IMAGE_TOKEN_INDEX]], dtype=pre_ids.dtype)
62
+ input_ids = torch.cat([pre_ids, img_tok, post_ids], dim=1).to(model.device)
63
+ attention_mask = torch.ones_like(input_ids, device=model.device)
64
+
65
+ # Preprocess image using model's vision tower
66
+ px = model.get_vision_tower().image_processor(
67
+ images=image, return_tensors="pt"
68
+ )["pixel_values"]
69
+ px = px.to(model.device, dtype=model.dtype)
70
+
71
+ # Generate caption
72
+ with torch.no_grad():
73
+ out = model.generate(
74
+ inputs=input_ids,
75
+ attention_mask=attention_mask,
76
+ images=px,
77
+ max_new_tokens=128,
78
+ do_sample=False, # Deterministic generation
79
+ temperature=1.0,
80
+ )
81
+
82
+ # Decode and return the generated text
83
+ generated_text = tok.decode(out[0], skip_special_tokens=True)
84
+
85
+ # Extract only the assistant's response
86
+ if "assistant" in generated_text:
87
+ response = generated_text.split("assistant")[-1].strip()
88
+ else:
89
+ response = generated_text
90
+
91
+ return response
92
+
93
+ except Exception as e:
94
+ return f"Error generating caption: {str(e)}"
95
+
96
+ # Create Gradio interface
97
+ with gr.Blocks(title="FastVLM Image Captioning") as demo:
98
+ gr.Markdown(
99
+ """
100
+ # 🖼️ FastVLM Image Captioning
101
+
102
+ Upload an image to generate a detailed caption using Apple's FastVLM-0.5B model.
103
+ You can use the default prompt or provide your own custom prompt.
104
+ """
105
+ )
106
+
107
+ with gr.Row():
108
+ with gr.Column():
109
+ image_input = gr.Image(
110
+ type="pil",
111
+ label="Upload Image",
112
+ elem_id="image-upload"
113
+ )
114
+
115
+ custom_prompt = gr.Textbox(
116
+ label="Custom Prompt (Optional)",
117
+ placeholder="Leave empty for default: 'Describe this image in detail.'",
118
+ lines=2
119
+ )
120
+
121
+ with gr.Row():
122
+ clear_btn = gr.ClearButton([image_input, custom_prompt])
123
+ generate_btn = gr.Button("Generate Caption", variant="primary")
124
+
125
+ with gr.Column():
126
+ output = gr.Textbox(
127
+ label="Generated Caption",
128
+ lines=8,
129
+ max_lines=15,
130
+ show_copy_button=True
131
+ )
132
+
133
+ # Event handlers
134
+ generate_btn.click(
135
+ fn=caption_image,
136
+ inputs=[image_input, custom_prompt],
137
+ outputs=output
138
+ )
139
+
140
+ # Also generate on image upload if no custom prompt
141
+ image_input.change(
142
+ fn=lambda img, prompt: caption_image(img, prompt) if img is not None and not prompt else None,
143
+ inputs=[image_input, custom_prompt],
144
+ outputs=output
145
+ )
146
+
147
+ gr.Markdown(
148
+ """
149
+ ---
150
+ **Model:** [apple/FastVLM-0.5B](https://huggingface.co/apple/FastVLM-0.5B)
151
+
152
+ **Note:** This model runs best on GPU. CPU inference may be slower.
153
+ """
154
+ )
155
+
156
+ if __name__ == "__main__":
157
+ demo.launch(
158
+ share=False,
159
+ show_error=True,
160
+ server_name="0.0.0.0",
161
+ server_port=7860
162
+ )