File size: 14,701 Bytes
da22255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import gradio as gr
import torch
from PIL import Image

demo_imgs = [
    ["chinchilla_web-1024x683.jpg", "shiba-inu-dog-in-the-snow.jpg"],
    ["4645808729_2dfc59b6a5_z.jpg", "5944609705_4664531909_z.jpg"],
    ["COCO_train2014_000000310472.jpg", "COCO_train2014_000000194806.jpg"],
    [
        "bcee7a-20190225-a-london-underground-sign.jpg",
        "istockphoto-622434332-1024x1024.jpg",
    ],
    ["dogs.jpeg", "pandas.jpg"],
    ["11887_pesto-pasta_Rita-1x1-1-501c953b29074ab193e2b5ad36e64648.jpg", "hummus.jpg"],
]
demo_texts = [
    [
        "Output: This is a chinchilla. They are mainly found in Chile.",
        "Output: This is a shiba. They are very popular in Japan.",
    ],
    [
        "Output: a man and a woman on a train looking at their cell phones.",
        "Output: a lavish reception room with black and white tiled floor.",
    ],
    [
        "Question: Describe the scene. Answer: A black and yellow fire hydrant sitting on a sidewalk. The sidewalk is made from red bricks.",
        "Question: What is the man trying to catch? Answer: The man is catching a white kite that his friend is flying. The two men are on a beach.",
    ],
    ['Output: "Underground"', 'Output: "Congress Ave"'],
    ["Output: 2 dogs", "Output: 3 pandas"],
    [
        "Output: Step 1: Cook 8 oz. of pasta until al dente, then drain and set aside. Step 2: In a food processor, blend 2 cups fresh basil leaves, 1/2 cup grated Parmesan cheese, 1/2 cup pine nuts, 2 cloves garlic, and 1/4 cup olive oil until smooth. Step 3: Toss the pesto sauce with the cooked pasta until evenly coated. Step 4: Serve hot and enjoy!",
        "Output: Step 1: Drain and rinse a can of chickpeas. Step 2: Add chickpeas to a food processor along with 2-3 cloves of garlic, 2 tbsp of tahini, 2 tbsp of lemon juice, and 1/4 cup of olive oil. Step 3: Process until smooth, scraping down the sides as needed. Step 4: Add salt and pepper to taste. Step 5: If the hummus is too thick, add water 1 tbsp at a time until desired consistency is reached. Step 6: Serve with a drizzle of olive oil and some paprika for garnish. Enjoy!",
    ],
]

# cd to open_flamingo dir and pip install .
import os
os.system("cd open_flamingo && pip install .")

from open_flamingo import create_model_and_transforms

# read bad_words.txt
with open("bad_words.txt", "r") as f:
    bad_words = f.read().splitlines()
    bad_words = set([word.strip().lower() for word in bad_words])

model, image_processor, tokenizer = create_model_and_transforms(
    clip_vision_encoder_pretrained="openai",
    clip_vision_encoder_path="ViT-L-14",
    lang_encoder_path="togethercomputer/RedPajama-INCITE-Base-3B-v1",
    tokenizer_path="togethercomputer/RedPajama-INCITE-Base-3B-v1",
    cross_attn_every_n_layers=2,
)

model.eval()


def generate(
    idx,
    image,
    text,
    example_one_image=None,
    example_one_text=None,
    example_two_image=None,
    example_two_text=None,
    tc=True
):
    if not tc:
        raise gr.Error("Please read the terms and conditions.")

    if image is None:
        raise gr.Error("Please upload an image.")

    example_one_image = (
        Image.open(demo_imgs[idx][0])
        if example_one_image is None
        else example_one_image
    )
    example_one_text = (
        demo_texts[idx][0]
        if example_one_text is None
        else f"Output: {example_one_text}"
    )

    example_two_image = (
        Image.open(demo_imgs[idx][1])
        if example_two_image is None
        else example_two_image
    )
    example_two_text = (
        demo_texts[idx][1]
        if example_two_text is None
        else f"Output: {example_two_text}"
    )

    if (
        example_one_image is None
        or example_one_text is None
        or example_two_image is None
        or example_two_text is None
    ):
        raise gr.Error("Please fill in all the fields (image and text).")

    demo_plus_text = f"<image>{example_one_text}<|endofchunk|><image>{example_two_text}<|endofchunk|>"
    demo_plus_text += (
        "<image>Output:" if idx != 2 else f"<image>Question: {text.strip()} Answer:"
    )
    # demo_plus_image = [example_one_image, example_two_image, image]

    # print(demo_plus_image)
    print(demo_plus_text)

    lang_x = tokenizer(demo_plus_text, return_tensors="pt")
    input_ids = lang_x["input_ids"]
    attention_mask = lang_x["attention_mask"]

    vision_x = [image_processor(example_one_image).unsqueeze(0), image_processor(example_two_image).unsqueeze(0), image_processor(image).unsqueeze(0)]
    vision_x = torch.cat(vision_x, dim=0)
    vision_x = vision_x.unsqueeze(1).unsqueeze(0)
    print(vision_x.shape)

    # with torch.cuda.amp.autocast(dtype=torch.bfloat16):
    output = model.generate(
        vision_x=vision_x,
        lang_x=input_ids,
        attention_mask=attention_mask,
        max_new_tokens=100,
        num_beams=1,
    )

    gen_text = tokenizer.decode(
        output[0][len(input_ids[0]):], skip_special_tokens=True
    )

    print(gen_text)
    gen_text = gen_text.split("Output")[0]
    gen_text = gen_text.split("Question")[0]

    for word in gen_text.split(" "):
        word = (
            word.strip()
            .lower()
            .replace(".", "")
            .replace(",", "")
            .replace("?", "")
            .replace("!", "")
        )
        if word in bad_words:
            print("Found bad word: ", word)
            raise gr.Error(
                "We found harmful language in the generated text. Please try again."
            )

    return (
        f"Output:{gen_text}"
        if idx != 2
        else f"Question: {text.strip()} Answer: {gen_text}"
    )


with gr.Blocks() as demo:
    # As a consequence, you should treat this model as a research prototype and not as a production-ready model. Before using this demo please familiarize yourself with our [model card](https://github.com/mlfoundations/open_flamingo/blob/main/MODEL_CARD.md) and [terms and conditions](https://github.com/mlfoundations/open_flamingo/blob/main/TERMS_AND_CONDITIONS.md)
    gr.Markdown(
        """
    # 🦩 OpenFlamingo-9B Demo  
    
    Blog post: [An open-source framework for training vision-language models with in-context learning (like GPT-4!)]()
    GitHub: [open_flamingo](https://github.com/mlfoundations/open_flamingo)
    
    In this demo we implement an interactive interface that showcases the in-context learning capabilities of the OpenFlamingo-9B model, a large multimodal model trained on top of LLaMA-7B.
    The model is trained on an interleaved mixture of text and images and is able to generate text conditioned on sequences of images/text. To safeguard against harmful generations, we detect toxic text in the model output and reject it. However, we understand that this is not a perfect solution and we encourage you to use this demo responsibly. If you find that the model is generating harmful text, please report it using this [form](https://forms.gle/StbcPvyyW2p3Pc7z6).
    
    Note: This model is still a work in progress and is not fully trained. We are releasing it to showcase the capabilities of the framework and to get feedback from the community.
    """
    )

    with gr.Accordion("See terms and conditions"):
        gr.Markdown("""**Please read the following information carefully before proceeding.**
OpenFlamingo is a **research prototype** that aims to enable users to interact with AI through both language and images. AI agents equipped with both language and visual understanding can be useful on a larger variety of tasks compared to models that communicate solely via language. By releasing an open-source research prototype, we hope to help the research community better understand the risks and limitations of modern visual-language AI models and accelerate the development of safer and more reliable methods.
**Limitations.** OpenFlamingo is built on top of the LLaMA large language model developed by Meta AI. Large language models, including LLaMA, are trained on mostly unfiltered internet data, and have been shown to be able to produce toxic, unethical, inaccurate, and harmful content. On top of this, OpenFlamingo’s ability to support visual inputs creates additional risks, since it can be used in a wider variety of applications; image+text models may carry additional risks specific to multimodality. Please use discretion when assessing the accuracy or appropriateness of the model’s outputs, and be mindful before sharing its results.
**Privacy and data collection.** This demo does NOT store any personal information on its users, and it does NOT store user queries.
**Licensing.** As OpenFlamingo is built on top of the LLaMA large language model from Meta AI, the LLaMA license agreement (as documented in the Meta request form) also applies.""")
        read_tc = gr.Checkbox(
            label="I have read and agree to the terms and conditions")

    with gr.Tab("📷 Image Captioning"):
        with gr.Row():
            with gr.Column(scale=1):
                demo_image_one = gr.Image(value=Image.open(demo_imgs[1][0])
                                          )
                demo_text_one = gr.Textbox(
                    value=demo_texts[1][0], label="Demonstration sample 1", lines=2
                )
            with gr.Column(scale=1):
                demo_image_two = gr.Image(value=Image.open(demo_imgs[1][1])
                                          )
                demo_text_two = gr.Textbox(
                    value=demo_texts[1][1], label="Demonstration sample 2", lines=2
                )
            with gr.Column(scale=1):
                query_image = gr.Image(type="pil")
                text_output = gr.Textbox(value="Output:", label="Model output")

        run_btn = gr.Button("Run model")

        def on_click_fn(img): return generate(1, img, "", tc=read_tc)
        run_btn.click(on_click_fn, inputs=[query_image], outputs=[text_output])

    with gr.Tab("🦓 Animal recognition"):
        with gr.Row():
            with gr.Column(scale=1):
                demo_image_one = gr.Image(
                    value=Image.open(demo_imgs[0][0])
                )
                demo_text_one = gr.Textbox(
                    value=demo_texts[0][0], label="Demonstration sample 1", lines=2
                )
            with gr.Column(scale=1):
                demo_image_two = gr.Image(
                    value=Image.open(demo_imgs[0][1])
                )
                demo_text_two = gr.Textbox(
                    value=demo_texts[0][1], label="Demonstration sample 2", lines=2
                )
            with gr.Column(scale=1):
                query_image = gr.Image(type="pil")
                text_output = gr.Textbox(value="Output:", label="Model output")

        run_btn = gr.Button("Run model")

        def on_click_fn(img): return generate(0, img, "", tc=read_tc)
        run_btn.click(on_click_fn, inputs=[query_image], outputs=[text_output])

    with gr.Tab("🔢 Counting objects"):
        with gr.Row():
            with gr.Column(scale=1):
                demo_image_one = gr.Image(
                    value=Image.open(demo_imgs[4][0])
                )
                demo_text_one = gr.Textbox(
                    value=demo_texts[4][0], label="Demonstration sample 1", lines=2
                )
            with gr.Column(scale=1):
                demo_image_two = gr.Image(
                    value=Image.open(demo_imgs[4][1])
                )
                demo_text_two = gr.Textbox(
                    value=demo_texts[4][1], label="Demonstration sample 2", lines=2
                )
            with gr.Column(scale=1):
                query_image = gr.Image(type="pil")
                text_output = gr.Textbox(value="Output:", label="Model output")

        run_btn = gr.Button("Run model")

        def on_click_fn(img): return generate(4, img, "", tc=read_tc)
        run_btn.click(on_click_fn, inputs=[query_image], outputs=[text_output])

    with gr.Tab("🕵️ Visual Question Answering"):
        with gr.Row():
            with gr.Column(scale=1):
                demo_image_one = gr.Image(
                    value=Image.open(demo_imgs[2][0])
                )
                demo_text_one = gr.Textbox(
                    value=demo_texts[2][0], label="Demonstration sample 1", lines=2
                )
            with gr.Column(scale=1):
                demo_image_two = gr.Image(
                    value=Image.open(demo_imgs[2][1])
                )
                demo_text_two = gr.Textbox(
                    value=demo_texts[2][1], label="Demonstration sample 2", lines=2
                )
            with gr.Column(scale=1):
                query_image = gr.Image(type="pil")
                question = gr.Textbox(
                    label="Question: (e.g. 'What is the color of the object?' without \"Question:\" prefix)"
                )
                text_output = gr.Textbox(value="", label="Model output")

        run_btn = gr.Button("Run model")
        def on_click_fn(img, txt): return generate(2, img, txt, tc=read_tc)
        run_btn.click(
            on_click_fn, inputs=[query_image, question], outputs=[text_output]
        )

    with gr.Tab("🌎 Custom"):
        gr.Markdown(
            """### Customize the demonstration by uploading your own images and text samples. 
                    ### **Note: Any text prompt you use will be prepended with an 'Output:', so you don't need to include it in your prompt.**"""
        )
        with gr.Row():
            with gr.Column(scale=1):
                demo_image_one = gr.Image(type="pil")
                demo_text_one = gr.Textbox(
                    label="Demonstration sample 1", lines=2)
            with gr.Column(scale=1):
                demo_image_two = gr.Image(type="pil")
                demo_text_two = gr.Textbox(
                    label="Demonstration sample 2", lines=2)
            with gr.Column(scale=1):
                query_image = gr.Image(type="pil")
                text_output = gr.Textbox(value="Output:", label="Model output")

        run_btn = gr.Button("Run model")

        def on_click_fn(img, example_img_1, example_txt_1, example_img_2, example_txt_2): return generate(
            -1, img, "", example_img_1, example_txt_1, example_img_2, example_txt_2, tc=read_tc
        )
        run_btn.click(
            on_click_fn,
            inputs=[
                query_image,
                demo_image_one,
                demo_text_one,
                demo_image_two,
                demo_text_two,
            ],
            outputs=[text_output],
        )

demo.queue(concurrency_count=1)
demo.launch()