AI-ANK commited on
Commit
62257cb
·
1 Parent(s): 3032f55

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +162 -0
  2. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import extra_streamlit_components as stx
3
+ import requests
4
+ from PIL import Image
5
+ from transformers import AutoProcessor, AutoModelForVision2Seq
6
+ from io import BytesIO
7
+ import replicate
8
+ from llama_index.llms.palm import PaLM
9
+ from llama_index import ServiceContext, VectorStoreIndex, Document
10
+ from llama_index.memory import ChatMemoryBuffer
11
+ import os
12
+ import datetime
13
+
14
+ # Set up the title of the application
15
+ st.title("Image Captioning and Chat")
16
+
17
+ # Initialize the cookie manager
18
+ cookie_manager = stx.CookieManager()
19
+
20
+ @st.cache_resource
21
+ def get_vision_model():
22
+ model = AutoModelForVision2Seq.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
23
+ processor = AutoProcessor.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
24
+ return model, processor
25
+
26
+ # Function to get image caption via Kosmos2.
27
+ @st.cache_data
28
+ def get_image_caption(image_data):
29
+
30
+ model, processor = get_vision_model()
31
+ #model = AutoModelForVision2Seq.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
32
+ #processor = AutoProcessor.from_pretrained("ydshieh/kosmos-2-patch14-224", trust_remote_code=True)
33
+
34
+ prompt = "<grounding>An image of"
35
+ inputs = processor(text=prompt, images=image_data, return_tensors="pt")
36
+
37
+ generated_ids = model.generate(
38
+ pixel_values=inputs["pixel_values"],
39
+ input_ids=inputs["input_ids"][:, :-1],
40
+ attention_mask=inputs["attention_mask"][:, :-1],
41
+ img_features=None,
42
+ img_attn_mask=inputs["img_attn_mask"][:, :-1],
43
+ use_cache=True,
44
+ max_new_tokens=64,
45
+ )
46
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
47
+
48
+ text_description, entities = processor.post_process_generation(generated_text)
49
+
50
+ #Using replicate API
51
+ # input_data = {
52
+ # "image": image_data,
53
+ # "description_type": "Brief"
54
+ # }
55
+ # output = replicate.run(
56
+ # "lucataco/kosmos-2:3e7b211c29c092f4bcc8853922cc986baa52efe255876b80cac2c2fbb4aff805",
57
+ # input=input_data
58
+ # )
59
+ # # Split the output string on the newline character and take the first item
60
+ # text_description = output.split('\n\n')[0]
61
+ return text_description
62
+
63
+ # Function to create the chat engine.
64
+ @st.cache_resource
65
+ def create_chat_engine(img_desc, api_key):
66
+ llm = PaLM(api_key=api_key)
67
+ service_context = ServiceContext.from_defaults(llm=llm)
68
+ doc = Document(text=img_desc)
69
+ index = VectorStoreIndex.from_documents([doc], service_context=service_context)
70
+ chatmemory = ChatMemoryBuffer.from_defaults(token_limit=1500)
71
+
72
+ chat_engine = index.as_chat_engine(
73
+ chat_mode="context",
74
+ system_prompt=(
75
+ f"You are a chatbot, able to have normal interactions, as well as talk. "
76
+ "You always answer in great detail and are polite. Your responses always descriptive. "
77
+ "Your job is to talk about an image the user has uploaded. Image description: {img_desc}."
78
+ ),
79
+ verbose=True,
80
+ memory=chatmemory
81
+ )
82
+ return chat_engine
83
+
84
+ # Clear chat function
85
+ def clear_chat():
86
+ if "messages" in st.session_state:
87
+ del st.session_state.messages
88
+ if "image_file" in st.session_state:
89
+ del st.session_state.image_file
90
+
91
+ # Callback function to clear the chat when a new image is uploaded
92
+ def on_image_upload():
93
+ clear_chat()
94
+
95
+ # Add a clear chat button
96
+ if st.button("Clear Chat"):
97
+ clear_chat()
98
+
99
+ # Image upload section.
100
+ image_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"], key="uploaded_image", on_change=on_image_upload)
101
+ if image_file:
102
+ # Display the uploaded image at a standard width.
103
+ st.image(image_file, caption='Uploaded Image.', width=200)
104
+ # Process the uploaded image to get a caption.
105
+ image_data = BytesIO(image_file.getvalue())
106
+ img_desc = get_image_caption(image_data)
107
+ st.write(f"Image description: {img_desc}")
108
+
109
+ # Initialize the chat engine with the image description.
110
+ chat_engine = create_chat_engine(img_desc, os.environ["GOOGLE_API_KEY"])
111
+
112
+ # Initialize session state for messages if it doesn't exist
113
+ if "messages" not in st.session_state:
114
+ st.session_state.messages = []
115
+
116
+ # Display previous messages
117
+ for message in st.session_state.messages:
118
+ with st.chat_message(message["role"]):
119
+ st.markdown(message["content"])
120
+
121
+ # Handle new user input
122
+ user_input = st.chat_input("Ask me about the image:", key="chat_input")
123
+ if user_input:
124
+ # Retrieve the message count from cookies
125
+ message_count = cookie_manager.get(cookie='message_count')
126
+ if message_count is None:
127
+ message_count = 0
128
+ else:
129
+ message_count = int(message_count)
130
+
131
+ # Check if the message limit has been reached
132
+ if message_count >= 20:
133
+ st.error("Notice: The maximum message limit for this demo version has been reached.")
134
+ else:
135
+ # Append user message to the session state
136
+ st.session_state.messages.append({"role": "user", "content": user_input})
137
+
138
+ # Display user message immediately
139
+ with st.chat_message("user"):
140
+ st.markdown(user_input)
141
+
142
+ # Call the chat engine to get the response if an image has been uploaded
143
+ if image_file:
144
+ # Get the response from your chat engine
145
+ response = chat_engine.chat(user_input)
146
+
147
+ # Append assistant message to the session state
148
+ st.session_state.messages.append({"role": "assistant", "content": response})
149
+
150
+ # Display the assistant message
151
+ with st.chat_message("assistant"):
152
+ st.markdown(response)
153
+
154
+ # Increment the message count and update the cookie
155
+ message_count += 1
156
+ cookie_manager.set('message_count', str(message_count), expires_at=datetime.datetime.now() + datetime.timedelta(days=30))
157
+
158
+
159
+
160
+ # Set Replicate and Google API keys
161
+ os.environ['REPLICATE_API_TOKEN'] = st.secrets['REPLICATE_API_TOKEN']
162
+ os.environ["GOOGLE_API_KEY"] = st.secrets['GOOGLE_API_KEY']
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ google-generativeai
3
+ llama-hub
4
+ llama-index
5
+ transformers
6
+ Pillow
7
+ requests
8
+ nest_asyncio
9
+ torch
10
+ extra-streamlit-components
11
+ replicate