Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from transformers import AutoModelForCausalLM
|
| 4 |
+
from transformers import AutoProcessor
|
| 5 |
+
from transformers import TextIteratorStreamer
|
| 6 |
+
import time
|
| 7 |
+
from threading import Thread
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
model_id = "microsoft/Phi-3-vision-128k-instruct"
|
| 11 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", trust_remote_code=True, torch_dtype="auto")
|
| 12 |
+
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
| 13 |
+
model.to("cuda:0")
|
| 14 |
+
|
| 15 |
+
PLACEHOLDER = """
|
| 16 |
+
<div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
|
| 17 |
+
<img src="https://cdn-thumbnails.huggingface.co/social-thumbnails/models/microsoft/Phi-3-vision-128k-instruct.png" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
|
| 18 |
+
<h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Microsoft's Phi3-Vision-128k-Context</h1>
|
| 19 |
+
<p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Phi-3-Vision is a 4.2B parameter multimodal model that brings together language and vision capabilities.</p>
|
| 20 |
+
</div>
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
#@spaces.GPU
|
| 24 |
+
def bot_streaming(message, history):
|
| 25 |
+
print(f'message is - {message}')
|
| 26 |
+
print(f'history is - {history}')
|
| 27 |
+
if message["files"]:
|
| 28 |
+
# message["files"][-1] is a Dict or just a string
|
| 29 |
+
if type(message["files"][-1]) == dict:
|
| 30 |
+
image = message["files"][-1]["path"]
|
| 31 |
+
else:
|
| 32 |
+
image = message["files"][-1]
|
| 33 |
+
else:
|
| 34 |
+
# if there's no image uploaded for this turn, look for images in the past turns
|
| 35 |
+
# kept inside tuples, take the last one
|
| 36 |
+
for hist in history:
|
| 37 |
+
if type(hist[0]) == tuple:
|
| 38 |
+
image = hist[0][0]
|
| 39 |
+
try:
|
| 40 |
+
if image is None:
|
| 41 |
+
# Handle the case where image is None
|
| 42 |
+
raise gr.Error("You need to upload an image for FalconVLM to work. Close the error and try again with an Image.")
|
| 43 |
+
except NameError:
|
| 44 |
+
# Handle the case where 'image' is not defined at all
|
| 45 |
+
raise gr.Error("You need to upload an image for FalconVLM to work. Close the error and try again with an Image.")
|
| 46 |
+
|
| 47 |
+
conversation = []
|
| 48 |
+
flag=False
|
| 49 |
+
for user, assistant in history:
|
| 50 |
+
if assistant is None:
|
| 51 |
+
#pass
|
| 52 |
+
flag=True
|
| 53 |
+
conversation.extend([{"role": "user", "content":""}])
|
| 54 |
+
continue
|
| 55 |
+
if flag==True:
|
| 56 |
+
conversation[0]['content'] = f"<|image_1|>\n{user}"
|
| 57 |
+
conversation.extend([{"role": "assistant", "content": assistant}])
|
| 58 |
+
flag=False
|
| 59 |
+
continue
|
| 60 |
+
#conversation += f"""User:<image>\n{user} Falcon:{assistant} """
|
| 61 |
+
conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
|
| 62 |
+
|
| 63 |
+
if len(history) == 0:
|
| 64 |
+
conversation.append({"role": "user", "content": f"<|image_1|>\n{message['text']}"})
|
| 65 |
+
else:
|
| 66 |
+
conversation.append({"role": "user", "content": message['text']})
|
| 67 |
+
print(f"prompt is -\n{conversation}")
|
| 68 |
+
#prompt = f"""User:<image>\n{message['text']} Falcon:"""
|
| 69 |
+
prompt = processor.tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True)
|
| 70 |
+
image = Image.open(image)
|
| 71 |
+
inputs = processor(prompt, image, return_tensors="pt").to("cuda:0")
|
| 72 |
+
#inputs = processor(prompt, image, return_tensors='pt').to(0, torch.float16)
|
| 73 |
+
|
| 74 |
+
streamer = TextIteratorStreamer(processor, **{"skip_special_tokens": True, "skip_prompt": True, 'clean_up_tokenization_spaces':False,}) # "eos_token_id":processor.tokenizer.eos_token_id})
|
| 75 |
+
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024, do_sample=False, temperature=0.0, eos_token_id=processor.tokenizer.eos_token_id,)
|
| 76 |
+
|
| 77 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 78 |
+
thread.start()
|
| 79 |
+
|
| 80 |
+
buffer = ""
|
| 81 |
+
for new_text in streamer:
|
| 82 |
+
# find <|eot_id|> and remove it from the new_text
|
| 83 |
+
#if "<|eot_id|>" in new_text:
|
| 84 |
+
# new_text = new_text.split("<|eot_id|>")[0]
|
| 85 |
+
buffer += new_text
|
| 86 |
+
yield buffer
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
chatbot=gr.Chatbot(scale=1, placeholder=PLACEHOLDER)
|
| 90 |
+
chat_input = gr.MultimodalTextbox(interactive=True, file_types=["image"], placeholder="Enter message or upload file...", show_label=False)
|
| 91 |
+
with gr.Blocks(fill_height=True, ) as demo:
|
| 92 |
+
gr.ChatInterface(
|
| 93 |
+
fn=bot_streaming,
|
| 94 |
+
title="FalconVLM",
|
| 95 |
+
examples=[{"text": "What is on the flower?", "files": ["./bee.jpg"]},
|
| 96 |
+
{"text": "How to make this pastry?", "files": ["./baklava.png"]}],
|
| 97 |
+
description="Try [tiiuae/falcon-11B-VLM](https://huggingface.co/tiiuae/falcon-11B-vlm). Upload an image and start chatting about it, or simply try one of the examples below. If you don't upload an image, you will receive an error.",
|
| 98 |
+
stop_btn="Stop Generation",
|
| 99 |
+
multimodal=True,
|
| 100 |
+
textbox=chat_input,
|
| 101 |
+
chatbot=chatbot,
|
| 102 |
+
cache_examples=False,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
demo.queue()
|
| 106 |
+
demo.launch(debug=True, quiet=True)
|