Spaces:
Running
on
Zero
Running
on
Zero
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
+
import torch
|
3 |
+
import re
|
4 |
+
import gradio as gr
|
5 |
+
from threading import Thread
|
6 |
+
from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM
|
7 |
+
|
8 |
+
import subprocess
|
9 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
10 |
+
|
11 |
+
model_id = "vikhyatk/moondream2"
|
12 |
+
revision = "2024-04-02"
|
13 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
|
14 |
+
moondream = AutoModelForCausalLM.from_pretrained(
|
15 |
+
model_id, trust_remote_code=True, revision=revision,
|
16 |
+
torch_dtype=torch.bfloat16, device_map={"": "cuda"},
|
17 |
+
attn_implementation="flash_attention_2"
|
18 |
+
)
|
19 |
+
moondream.eval()
|
20 |
+
|
21 |
+
|
22 |
+
@spaces.GPU(duration=10)
|
23 |
+
def answer_question(img, prompt):
|
24 |
+
image_embeds = moondream.encode_image(img)
|
25 |
+
streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
|
26 |
+
thread = Thread(
|
27 |
+
target=moondream.answer_question,
|
28 |
+
kwargs={
|
29 |
+
"image_embeds": image_embeds,
|
30 |
+
"question": prompt,
|
31 |
+
"tokenizer": tokenizer,
|
32 |
+
"streamer": streamer,
|
33 |
+
},
|
34 |
+
)
|
35 |
+
thread.start()
|
36 |
+
|
37 |
+
buffer = ""
|
38 |
+
for new_text in streamer:
|
39 |
+
buffer += new_text
|
40 |
+
yield buffer.strip()
|
41 |
+
|
42 |
+
|
43 |
+
with gr.Blocks() as demo:
|
44 |
+
gr.Markdown(
|
45 |
+
"""
|
46 |
+
# π moondream2
|
47 |
+
A tiny vision language model. [GitHub](https://github.com/vikhyat/moondream)
|
48 |
+
"""
|
49 |
+
)
|
50 |
+
with gr.Row():
|
51 |
+
prompt = gr.Textbox(label="Input", value="Describe this image.", scale=4)
|
52 |
+
submit = gr.Button("Submit")
|
53 |
+
with gr.Row():
|
54 |
+
img = gr.Image(type="pil", label="Upload an Image")
|
55 |
+
output = gr.TextArea(label="Response")
|
56 |
+
submit.click(answer_question, [img, prompt], output)
|
57 |
+
prompt.submit(answer_question, [img, prompt], output)
|
58 |
+
|
59 |
+
demo.queue().launch()
|