akhaliq HF Staff commited on
Commit
7231c7d
·
verified ·
1 Parent(s): 726f983

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +183 -0
app.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import torch
4
+ from PIL import Image as PILImage
5
+ from PIL import ImageDraw, ImageFont
6
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, AutoProcessor
7
+ from loguru import logger
8
+ import gradio as gr
9
+ import spaces
10
+
11
+ # Prefer local repo package over any site-installed "perceptron" (adjust if needed)
12
+ REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
13
+ if REPO_ROOT not in sys.path:
14
+ sys.path.insert(0, REPO_ROOT)
15
+
16
+ from perceptron.tensorstream import VisionType
17
+ from perceptron.tensorstream.ops import tensor_stream_token_view, modality_mask
18
+ from perceptron.pointing.parser import extract_points
19
+
20
+ # Global model and processor
21
+ model = None
22
+ processor = None
23
+ device = None
24
+ dtype = None
25
+ config = None
26
+
27
+ def load_model():
28
+ global model, processor, device, dtype, config
29
+ hf_path = "PerceptronAI/Isaac-0.1"
30
+ logger.info(f"Loading processor and config from HF checkpoint: {hf_path}")
31
+ config = AutoConfig.from_pretrained(hf_path, trust_remote_code=True)
32
+ tokenizer = AutoTokenizer.from_pretrained(hf_path, trust_remote_code=True, use_fast=False)
33
+ processor = AutoProcessor.from_pretrained(hf_path, trust_remote_code=True)
34
+ processor.tokenizer = tokenizer # Ensure tokenizer is set
35
+
36
+ logger.info(f"Loading AutoModelForCausalLM from HF checkpoint: {hf_path}")
37
+ model = AutoModelForCausalLM.from_pretrained(hf_path, trust_remote_code=True)
38
+
39
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
40
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
41
+ model = model.to(device=device, dtype=dtype)
42
+ model.eval()
43
+
44
+ logger.info(f"Model loaded on {device} with dtype {dtype}")
45
+
46
+ @spaces.GPU(duration=120)
47
+ def init():
48
+ if model is None:
49
+ load_model()
50
+ return "Model loaded successfully"
51
+
52
+ def document_to_messages(document, vision_token="<image>"):
53
+ messages = []
54
+ images = []
55
+ for item in document:
56
+ itype = item.get("type")
57
+ if itype == "text":
58
+ content = item.get("content")
59
+ if content:
60
+ messages.append({"role": item.get("role", "user"), "content": content})
61
+ elif itype == "image":
62
+ if "content" in item and item["content"] is not None:
63
+ img = PILImage.open(item["content"]).convert("RGB")
64
+ images.append(img)
65
+ messages.append({"role": item.get("role", "user"), "content": vision_token})
66
+ return messages, images
67
+
68
+ def decode_tensor_stream(tensor_stream, tokenizer):
69
+ token_view = tensor_stream_token_view(tensor_stream)
70
+ mod = modality_mask(tensor_stream)
71
+ text_tokens = token_view[(mod != VisionType.image.value)]
72
+ decoded = tokenizer.decode(text_tokens[0] if len(text_tokens.shape) > 1 else text_tokens)
73
+ return decoded
74
+
75
+ def visualize_predictions(generated_text, image, output_path="prediction.jpeg"):
76
+ boxes = extract_points(generated_text, expected="box")
77
+ if not boxes:
78
+ logger.info("No bounding boxes found in the generated text")
79
+ image.save(output_path)
80
+ return output_path
81
+
82
+ img_width, img_height = image.size
83
+ img_with_boxes = image.copy()
84
+ draw = ImageDraw.Draw(img_with_boxes)
85
+
86
+ try:
87
+ font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 16)
88
+ except:
89
+ font = ImageFont.load_default()
90
+
91
+ colors = ["red", "green", "blue", "yellow", "magenta", "cyan", "orange", "purple"]
92
+
93
+ for idx, box in enumerate(boxes):
94
+ color = colors[idx % len(colors)]
95
+ norm_x1, norm_y1 = box.top_left.x, box.top_left.y
96
+ norm_x2, norm_y2 = box.bottom_right.x, box.bottom_right.y
97
+ x1 = int((norm_x1 / 1000.0) * img_width)
98
+ y1 = int((norm_y1 / 1000.0) * img_height)
99
+ x2 = int((norm_x2 / 1000.0) * img_width)
100
+ y2 = int((norm_y2 / 1000.0) * img_height)
101
+
102
+ x1 = max(0, min(x1, img_width - 1))
103
+ y1 = max(0, min(y1, img_height - 1))
104
+ x2 = max(0, min(x2, img_width - 1))
105
+ y2 = max(0, min(y2, img_height - 1))
106
+
107
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=3)
108
+
109
+ if box.mention:
110
+ text_y = max(y1 - 20, 5)
111
+ text_bbox = draw.textbbox((x1, text_y), box.mention, font=font)
112
+ draw.rectangle(text_bbox, fill=color)
113
+ draw.text((x1, text_y), box.mention, fill="white", font=font)
114
+
115
+ img_with_boxes.save(output_path, "JPEG")
116
+ return output_path
117
+
118
+ @spaces.GPU(duration=120)
119
+ def generate_response(image, prompt):
120
+ if model is None:
121
+ return "Model not loaded. Click 'Load Model' first.", None
122
+
123
+ document = [
124
+ {"type": "text", "content": "<hint>BOX</hint>", "role": "user"},
125
+ {"type": "image", "content": image, "role": "user"},
126
+ {"type": "text", "content": prompt, "role": "user"},
127
+ ]
128
+
129
+ messages, images = document_to_messages(document, vision_token=config.vision_token)
130
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
131
+ inputs = processor(text=text, images=images, return_tensors="pt")
132
+ tensor_stream = inputs["tensor_stream"].to(device)
133
+ input_ids = inputs["input_ids"].to(device)
134
+
135
+ decoded_content = decode_tensor_stream(tensor_stream, processor.tokenizer)
136
+
137
+ with torch.no_grad():
138
+ generated_ids = model.generate(
139
+ tensor_stream=tensor_stream,
140
+ max_new_tokens=256,
141
+ do_sample=False,
142
+ pad_token_id=processor.tokenizer.eos_token_id,
143
+ eos_token_id=processor.tokenizer.eos_token_id,
144
+ )
145
+
146
+ generated_text = processor.tokenizer.decode(generated_ids[0], skip_special_tokens=False)
147
+
148
+ if images:
149
+ vis_path = visualize_predictions(generated_text, images[0])
150
+ return generated_text, vis_path
151
+ else:
152
+ return generated_text, None
153
+
154
+ with gr.Blocks(title="HuggingFace Perceptron Demo") as demo:
155
+ gr.Markdown("# HuggingFace Perceptron Pipeline Demo")
156
+ gr.Markdown("Built with [anycoder](https://huggingface.co/spaces/akhaliq/anycoder)")
157
+ gr.Markdown("""
158
+ This demo shows how to use the Perceptron Isaac model for multimodal generation with text and images.
159
+ Upload an image and provide a prompt to generate responses with bounding box visualizations.
160
+ """)
161
+
162
+ with gr.Row():
163
+ load_btn = gr.Button("Load Model", variant="primary")
164
+
165
+ image_input = gr.Image(type="filepath", label="Upload Image", sources=["upload", "webcam"])
166
+ prompt_input = gr.Textbox(
167
+ label="Prompt",
168
+ value="Determine whether it is safe to cross the street. Look for signage and moving traffic.",
169
+ lines=3,
170
+ placeholder="Enter your prompt here..."
171
+ )
172
+
173
+ with gr.Row():
174
+ generate_btn = gr.Button("Generate Response", variant="primary")
175
+
176
+ generated_text = gr.Textbox(label="Generated Text", lines=10)
177
+ visualized_image = gr.Image(label="Visualized Predictions (with Bounding Boxes)")
178
+
179
+ load_btn.click(init, outputs=gr.Textbox(value="Loading...", visible=False))
180
+ generate_btn.click(generate_response, inputs=[image_input, prompt_input], outputs=[generated_text, visualized_image])
181
+
182
+ if __name__ == "__main__":
183
+ demo.launch()