File size: 5,671 Bytes
5dae26f
 
 
 
 
 
 
725ac0d
719c202
5dae26f
 
725ac0d
a2e1737
725ac0d
a2e1737
5dae26f
 
 
20f775b
a2e1737
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dae26f
 
 
 
 
 
 
 
a2e1737
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dae26f
a2e1737
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dae26f
a2e1737
 
 
 
 
 
 
5dae26f
 
a2e1737
 
 
 
5dae26f
a2e1737
 
 
 
5dae26f
 
 
 
 
a2e1737
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
725ac0d
a2e1737
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dae26f
725ac0d
 
 
 
 
 
5dae26f
 
a2e1737
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import re
import PIL.Image
import gradio as gr
import jax
import jax.numpy as jnp
import numpy as np
import flax.linen as nn
from inference import PaliGemmaModel, VAEModel

COLORS = ['#4285f4', '#db4437', '#f4b400', '#0f9d58', '#e48ef1']

# Instantiate the models
pali_gemma_model = PaliGemmaModel()
vae_model = VAEModel('vae-oid.npz')

##### Parse segmentation output tokens into masks
##### Also returns bounding boxes with their labels

def parse_segmentation(input_image, input_text, max_new_tokens=100):
    out = pali_gemma_model.infer(image=input_image, text=input_text, max_new_tokens=max_new_tokens)
    objs = extract_objs(out.lstrip("\n"), input_image.size[0], input_image.size[1], unique_labels=True)
    labels = set(obj.get('name') for obj in objs if obj.get('name'))
    color_map = {l: COLORS[i % len(COLORS)] for i, l in enumerate(labels)}
    highlighted_text = [(obj['content'], obj.get('name')) for obj in objs]
    annotated_img = (
        input_image,
        [
            (
                obj['mask'] if obj.get('mask') is not None else obj['xyxy'],
                obj['name'] or '',
            )
            for obj in objs
            if 'mask' in obj or 'xyxy' in obj
        ],
    )
    has_annotations = bool(annotated_img[1])
    return annotated_img

INTRO_TEXT="🔬🧠 CellVision AI -- Intelligent Cell Imaging Analysis 🤖🧫"
IMAGE_PROMPT="""
Describe the morphological characteristics and visible interactions between different cell types.
Assess the biological context to identify signs of cancer and the presence of antigens.
"""

with gr.Blocks(css="style.css") as demo:
    gr.Markdown(INTRO_TEXT)
    with gr.Tab("Segment/Detect"):
        with gr.Row():
            with gr.Column():
                image = gr.Image(type="pil")
                seg_input = gr.Text(label="Entities to Segment/Detect")

            with gr.Column():
                annotated_image = gr.AnnotatedImage(label="Output")

        seg_btn = gr.Button("Submit")
        examples = [
            ["./examples/cart1.jpg", "segment cells"],
            ["./examples/cart1.jpg", "detect cells"],
            ["./examples/cart2.jpg", "segment cells"],
            ["./examples/cart2.jpg", "detect cells"],
            ["./examples/cart3.jpg", "segment cells"],
            ["./examples/cart3.jpg", "detect cells"]
        ]
        gr.Examples(
            examples=examples,
            inputs=[image, seg_input],
        )
        seg_inputs = [
            image,
            seg_input,
        ]
        seg_outputs = [
            annotated_image
        ]
        seg_btn.click(
            fn=parse_segmentation,
            inputs=seg_inputs,
            outputs=seg_outputs,
        )
    with gr.Tab("Text Generation"):
        with gr.Column():
            image = gr.Image(type="pil")
            text_input = gr.Text(label="Input Text")
            text_output = gr.Text(label="Text Output")
            chat_btn = gr.Button()
            tokens = gr.Slider(
                label="Max New Tokens",
                info="Set to larger for longer generation.",
                minimum=10,
                maximum=100,
                value=50,
                step=10,
            )

        chat_inputs = [
            image,
            text_input,
            tokens
        ]
        chat_outputs = [
            text_output
        ]
        chat_btn.click(
            fn=pali_gemma_model.infer,
            inputs=chat_inputs,
            outputs=chat_outputs,
        )

        examples = [
            ["./examples/cart1.jpg", IMAGE_PROMPT],
            ["./examples/cart2.jpg", IMAGE_PROMPT],
            ["./examples/cart3.jpg", IMAGE_PROMPT]
        ]
        gr.Examples(
            examples=examples,
            inputs=chat_inputs,
        )

### Postprocessing Utils for Segmentation Tokens
### Segmentation tokens are passed to another VAE which decodes them to a mask

def extract_objs(text, width, height, unique_labels=False):
    """Returns objs for a string with "<loc>" and "<seg>" tokens."""
    objs = []
    seen = set()
    while text:
        m = _SEGMENT_DETECT_RE.match(text)
        if not m:
            break
        print("m", m)
        gs = list(m.groups())
        before = gs.pop(0)
        name = gs.pop()
        y1, x1, y2, x2 = [int(x) / 1024 for x in gs[:4]]

        y1, x1, y2, x2 = map(round, (y1*height, x1*width, y2*height, x2*width))
        seg_indices = gs[4:20]
        if seg_indices[0] is None:
            mask = None
        else:
            seg_indices = np.array([int(x) for x in seg_indices], dtype=np.int32)
            m64, = vae_model.reconstruct_masks(seg_indices[None])[..., 0]
            m64 = np.clip(np.array(m64) * 0.5 + 0.5, 0, 1)
            m64 = PIL.Image.fromarray((m64 * 255).astype('uint8'))
            mask = np.zeros([height, width])
            if y2 > y1 and x2 > x1:
                mask[y1:y2, x1:x2] = np.array(m64.resize([x2 - x1, y2 - y1])) / 255.0

        content = m.group()
        if before:
            objs.append(dict(content=before))
            content = content[len(before):]
        while unique_labels and name in seen:
            name = (name or '') + "'"
        seen.add(name)
        objs.append(dict(
            content=content, xyxy=(x1, y1, x2, y2), mask=mask, name=name))
        text = text[len(before) + len(content):]

    if text:
        objs.append(dict(content=text))

    return objs

_SEGMENT_DETECT_RE = re.compile(
    r'(.*?)' +
    r'<loc(\d{4})>' * 4 + r'\s*' +
    '(?:%s)?' % (r'<seg(\d{3})>' * 16) +
    r'\s*([^;<>]+)? ?(?:; )?',
)

if __name__ == "__main__":
    demo.queue(max_size=10).launch(debug=True)