Gokulram2710 commited on
Commit
28b96b3
1 Parent(s): a54c06d

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from threading import Thread
3
+
4
+ import gradio as gr
5
+ import spaces
6
+ import torch
7
+ from PIL import Image
8
+ from transformers import AutoProcessor, AutoModelForCausalLM
9
+ from transformers import TextIteratorStreamer
10
+
11
+ import subprocess
12
+ subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
13
+
14
+ # thanks to https://huggingface.co/ysharma
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
+ user_prompt = '<|user|>\n'
24
+ assistant_prompt = '<|assistant|>\n'
25
+ prompt_suffix = "<|end|>\n"
26
+
27
+
28
+
29
+ model_id = "microsoft/Phi-3-vision-128k-instruct"
30
+
31
+ processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
32
+
33
+ model = AutoModelForCausalLM.from_pretrained(
34
+ model_id,
35
+ torch_dtype="auto",
36
+ trust_remote_code=True,
37
+ )
38
+
39
+ model.to("cuda:0")
40
+
41
+
42
+ @spaces.GPU
43
+ def bot_streaming(message, history):
44
+ print(f'message is - {message}')
45
+ print(f'history is - {history}')
46
+ if message["files"]:
47
+ # message["files"][-1] is a Dict or just a string
48
+ if type(message["files"][-1]) == dict:
49
+ image = message["files"][-1]["path"]
50
+ else:
51
+ image = message["files"][-1]
52
+ else:
53
+ # if there's no image uploaded for this turn, look for images in the past turns
54
+ # kept inside tuples, take the last one
55
+ for hist in history:
56
+ if type(hist[0]) == tuple:
57
+ image = hist[0][0]
58
+ try:
59
+ if image is None:
60
+ # Handle the case where image is None
61
+ raise gr.Error("You need to upload an image for Phi3-Vision to work. Close the error and try again with an Image.")
62
+ except NameError:
63
+ # Handle the case where 'image' is not defined at all
64
+ raise gr.Error("You need to upload an image for Phi3-Vision to work. Close the error and try again with an Image.")
65
+
66
+ conversation = []
67
+ flag=False
68
+ for user, assistant in history:
69
+ if assistant is None:
70
+ #pass
71
+ flag=True
72
+ conversation.extend([{"role": "user", "content":""}])
73
+ continue
74
+ if flag==True:
75
+ conversation[0]['content'] = f"<|image_1|>\n{user}"
76
+ conversation.extend([{"role": "assistant", "content": assistant}])
77
+ flag=False
78
+ continue
79
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
80
+
81
+ if len(history) == 0:
82
+ conversation.append({"role": "user", "content": f"<|image_1|>\n{message['text']}"})
83
+ else:
84
+ conversation.append({"role": "user", "content": message['text']})
85
+ print(f"prompt is -\n{conversation}")
86
+ prompt = processor.tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True)
87
+ image = Image.open(image)
88
+ inputs = processor(prompt, image, return_tensors="pt").to("cuda:0")
89
+
90
+ streamer = TextIteratorStreamer(processor, **{"skip_special_tokens": True, "skip_prompt": True, 'clean_up_tokenization_spaces':False,})
91
+ generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024, do_sample=False, temperature=0.0, eos_token_id=processor.tokenizer.eos_token_id,)
92
+
93
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
94
+ thread.start()
95
+
96
+ buffer = ""
97
+ for new_text in streamer:
98
+ buffer += new_text
99
+ yield buffer
100
+
101
+
102
+ chatbot = gr.Chatbot(placeholder=PLACEHOLDER, scale=1)
103
+ chat_input = gr.MultimodalTextbox(interactive=True, file_types=["image"], placeholder="Enter message or upload file...",
104
+ show_label=False)
105
+ with gr.Blocks(fill_height=True, ) as demo:
106
+ gr.ChatInterface(
107
+ fn=bot_streaming,
108
+ title="Phi-3 Vision 128k Instruct",
109
+ examples=[{"text": "What is on the flower?", "files": ["./bee.jpg"]},
110
+ {"text": "How to make this pastry?", "files": ["./baklava.png"]}],
111
+ description="Try [microsoft/Phi-3-vision-128k-instruct](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct). 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.",
112
+ stop_btn="Stop Generation",
113
+ multimodal=True,
114
+ textbox=chat_input,
115
+ chatbot=chatbot,
116
+ )
117
+
118
+ demo.queue(api_open=False)
119
+ demo.launch(show_api=False, share=False)