ehartford commited on
Commit
17c2c06
1 Parent(s): c1cd8b2

Create dolphin_vision_streamlit.py

Browse files
Files changed (1) hide show
  1. dolphin_vision_streamlit.py +76 -0
dolphin_vision_streamlit.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import transformers
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from PIL import Image
6
+ import warnings
7
+
8
+ # Disable warnings and progress bars
9
+ transformers.logging.set_verbosity_error()
10
+ transformers.logging.disable_progress_bar()
11
+ warnings.filterwarnings('ignore')
12
+
13
+ # Set device
14
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
15
+ torch.set_default_device(device)
16
+
17
+ @st.cache_resource
18
+ def load_model():
19
+ model_name = 'cognitivecomputations/dolphin-vision-72b'
20
+ model = AutoModelForCausalLM.from_pretrained(
21
+ model_name,
22
+ torch_dtype=torch.float16,
23
+ device_map='auto',
24
+ trust_remote_code=True
25
+ )
26
+ tokenizer = AutoTokenizer.from_pretrained(
27
+ model_name,
28
+ trust_remote_code=True
29
+ )
30
+ return model, tokenizer
31
+
32
+ def generate_response(model, tokenizer, prompt, image=None):
33
+ messages = [
34
+ {"role": "user", "content": f'<image>\n{prompt}' if image else prompt}
35
+ ]
36
+ text = tokenizer.apply_chat_template(
37
+ messages,
38
+ tokenize=False,
39
+ add_generation_prompt=True
40
+ )
41
+ text_chunks = [tokenizer(chunk).input_ids for chunk in text.split('<image>')]
42
+ input_ids = torch.tensor(text_chunks[0] + [-200] + text_chunks[1], dtype=torch.long).unsqueeze(0)
43
+
44
+ if image:
45
+ image_tensor = model.process_images([image], model.config).to(dtype=model.dtype)
46
+ else:
47
+ image_tensor = None
48
+
49
+ output_ids = model.generate(
50
+ input_ids,
51
+ images=image_tensor,
52
+ max_new_tokens=2048,
53
+ use_cache=True
54
+ )[0]
55
+
56
+ return tokenizer.decode(output_ids[input_ids.shape[1]:], skip_special_tokens=True).strip()
57
+
58
+ st.title("Chat with DolphinVision 🐬")
59
+
60
+ model, tokenizer = load_model()
61
+
62
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
63
+ image = None
64
+ if uploaded_file is not None:
65
+ image = Image.open(uploaded_file)
66
+ st.image(image, caption='Uploaded Image', use_column_width=True)
67
+
68
+ user_input = st.text_input("You:", "")
69
+
70
+ if st.button("Send"):
71
+ if user_input:
72
+ with st.spinner("Generating response..."):
73
+ response = generate_response(model, tokenizer, user_input, image)
74
+ st.text_area("DolphinVision:", value=response, height=200)
75
+ else:
76
+ st.warning("Please enter a message.")