Skip to content

Commit 7af0847

Browse files
authored
setup and app fix for seamless importing! (#16)
* import .txt file * adding app and app_utils to package * Delete app.py - moved * Delete app_utils.py - moved * include app and app_utils * Update app.py - title fix * app edits * closer ---------
1 parent 5efb3ff commit 7af0847

File tree

4 files changed

+285
-323
lines changed

4 files changed

+285
-323
lines changed

amadeusgpt/app.py

Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
import os
2+
import streamlit as st
3+
import traceback
4+
from collections import defaultdict
5+
import uuid
6+
from amadeusgpt.logger import AmadeusLogger
7+
from datetime import datetime
8+
import requests
9+
from amadeusgpt import app_utils
10+
from amadeusgpt.utils import validate_openai_api_key
11+
12+
st._is_running_with_streamlit = True
13+
os.environ["streamlit_app"] = "True"
14+
assert "streamlit_app" in os.environ, "The 'streamlit_app' environment variable is not set!"
15+
16+
# Initialize session state variables if not present
17+
if "exist_valid_openai_api_key" not in st.session_state:
18+
st.session_state["exist_valid_openai_api_key"] = False
19+
20+
def main():
21+
subprocess.run(["./launch_app"], check=True)
22+
st.title("AmadeusGPT")
23+
24+
import time
25+
from streamlit_profiler import Profiler
26+
27+
# TITLE PANEL
28+
st.set_page_config(layout="wide")
29+
app_utils.load_css("static/styles/style.css")
30+
31+
32+
###### Initialize ######
33+
if "amadeus" not in st.session_state:
34+
st.session_state["amadeus"] = app_utils.summon_the_beast()[0]
35+
if "log_folder" not in st.session_state:
36+
st.session_state["log_folder"] = app_utils.summon_the_beast()[1]
37+
if "chatbot" not in st.session_state:
38+
st.session_state["chatbot"] = []
39+
if "user" not in st.session_state:
40+
st.session_state["user"] = []
41+
if "user_input" not in st.session_state:
42+
st.session_state["user_input"] = ""
43+
if "uploaded_files" not in st.session_state:
44+
st.session_state["uploaded_files"] = []
45+
if "uploaded_video_file" not in st.session_state:
46+
st.session_state["uploaded_video_file"] = None
47+
if "uploaded_keypoint_file" not in st.session_state:
48+
st.session_state["uploaded_keypoint_file"] = None
49+
50+
if "example" not in st.session_state:
51+
st.session_state["example"] = ""
52+
if "chat_history" not in st.session_state:
53+
st.session_state["chat_history"] = ""
54+
if "previous_roi" not in st.session_state:
55+
st.session_state["previous_roi"] = {}
56+
if "roi_exist" not in st.session_state:
57+
st.session_state["roi_exist"] = False
58+
if "exist_valid_openai_api_key" not in st.session_state:
59+
if "OPENAI_API_KEY" in os.environ:
60+
st.session_state["exist_valid_openai_api_key"] = True
61+
else:
62+
st.session_state["exist_valid_openai_api_key"] = False
63+
if "enable_explainer" not in st.session_state:
64+
st.session_state["enable_explainer"] = False
65+
66+
if "enable_SAM" not in st.session_state:
67+
st.session_state["enable_SAM"] = False
68+
69+
example_to_page = {}
70+
71+
72+
def valid_api_key():
73+
if "OPENAI_API_KEY" in os.environ:
74+
api_token = os.environ["OPENAI_API_KEY"]
75+
else:
76+
api_token = st.session_state["openAI_token"]
77+
check_valid = validate_openai_api_key(api_token)
78+
79+
if check_valid:
80+
st.session_state["exist_valid_openai_api_key"] = True
81+
st.session_state["OPENAI_API_KEY"] = api_token
82+
st.success("OpenAI API Key Validated!")
83+
else:
84+
st.error("Invalid OpenAI API Key")
85+
86+
87+
def welcome_page(text):
88+
with st.sidebar as sb:
89+
if st.session_state["exist_valid_openai_api_key"] is not True:
90+
api_token = st.sidebar.text_input(
91+
"Your openAI API token",
92+
"place your token here",
93+
key="openAI_token",
94+
on_change=valid_api_key,
95+
)
96+
97+
model_selection = st.sidebar.selectbox(
98+
"Select a GPT-4 model",
99+
("gpt-4", "gpt-4-1106-preview"),
100+
)
101+
st.session_state["gpt_model"] = model_selection
102+
103+
enable_explainer = st.sidebar.selectbox(
104+
"Do you want to use our LLM Explainer Module? This outputs a written description of the query results, but can be slow.",
105+
("No", "Yes"),
106+
)
107+
st.session_state["enable_explainer"] = enable_explainer
108+
109+
enable_SAM = st.sidebar.selectbox(
110+
"Do you want to use Segment Anything on your own data? This can be slow and requires you to download the model weights.",
111+
("No", "Yes"),
112+
)
113+
st.session_state["enable_SAM"] = enable_SAM
114+
115+
116+
117+
# remove this for now
118+
# st.caption(f"git hash: {app_utils.get_git_hash()}")
119+
120+
st.image(
121+
os.path.join(os.getcwd(), "static/images/amadeusgpt_logo.png"),
122+
caption=None,
123+
width=None,
124+
use_column_width=None,
125+
clamp=False,
126+
channels="RGB",
127+
output_format="auto",
128+
)
129+
130+
st.markdown(
131+
"##### 🪄 We turn natural language descriptions of behaviors into machine-executable code"
132+
)
133+
134+
small_head = "#" * 6
135+
small_font = ""
136+
137+
st.markdown("### 👥 Instructions")
138+
139+
st.markdown(
140+
f"{small_font} - We use LLMs to bridge natural language and behavior analysis code. For more details, check out our NeurIPS 2023 paper '[AmadeusGPT: a natural language interface for interactive animal behavioral analysis' by Shaokai Ye, Jessy Lauer, Mu Zhou, Alexander Mathis \& Mackenzie W. Mathis](https://github.com/AdaptiveMotorControlLab/AmadeusGPT)."
141+
)
142+
st.markdown(
143+
f"{small_font} - 🤗 Please note that depending on openAI, the runtimes can vary - you can see the app is `🏃RUNNING` in the top right when you run demos or ask new queries.\n"
144+
)
145+
st.markdown(
146+
f"{small_font} - Please give us feedback if the output is correct 👍, or needs improvement 👎. This is an ` academic research project` demo, so expect a few bumps please, but we are actively working to make it better 💕.\n"
147+
)
148+
st.markdown(
149+
f"{small_font} - ⬅️ To get started, watch the quick video below ⬇️, and then select a demo from the drop-down menu. 🔮 We recommend to refresh the browser/app between demos."
150+
)
151+
152+
st.markdown(
153+
f"{small_font} - To create an OpenAI API key please see: https://platform.openai.com/overview.\n"
154+
)
155+
156+
st.markdown("### How AmadeusGPT🎻 works")
157+
158+
st.markdown(
159+
f"{small_font} - To capture animal-environment states, AmadeusGPT🎻 leverages state-of-the-art pretrained models, such as SuperAnimals for animal pose estimation and Segment-Anything (SAM) for object segmentation. The platform enables spatio-temporal reasoning to parse the outputs of computer vision models into quantitative behavior analysis. Additionally, AmadeusGPT🎻 simplifies the integration of arbitrary behavioral modules, making it easier to combine tools for task-specific models and interface with machine code."
160+
)
161+
st.markdown(
162+
f"{small_font} - We built core modules that interface with several integrations, plus built a dual-memory system to augment chatGPT, thereby allowing longer reasoning."
163+
)
164+
st.markdown(
165+
f"{small_font} - This demo serves to highlight a hosted user-experience, but does not include all the features yet..."
166+
)
167+
st.markdown(f"{small_font} - Watch the video below to see how to use the App.")
168+
169+
st.video("static/demo_withvoice.mp4")
170+
171+
st.markdown("### ⚠️ Disclaimers")
172+
173+
st.markdown(
174+
f"{small_font} Refer to https://streamlit.io/privacy-policy for the privacy policy for your personal information.\n"
175+
f"{small_font} Please note that to improve AmadeusGPT🎻 we log your queries and the generated code on our demos."
176+
f"{small_font} Note, we do *not* log your openAI API key under any circumstances and we rely on streamlit cloud for privately securing your connections.\n"
177+
f"{small_font} If you have security concerns over the API key, we suggest that you re-set your API key after you finish using our app.\n"
178+
)
179+
180+
st.markdown("### 💻 The underlying core computer vision models explained")
181+
st.markdown(
182+
f"{small_font} We use pretrained computer vision models to capture the state of the animal and the environment. We hope this can reduce the entry barrier to behavior analysis.\n"
183+
f"{small_font} Therefore, we can ask questions about animals' behaviors that are composed by animal's state, animal-animal interactions or animal-environment interactions.\n"
184+
)
185+
st.markdown(
186+
f"{small_font} DeepLabCut-SuperAnimal models, see https://arxiv.org/abs/2203.07436"
187+
)
188+
st.markdown(
189+
f"{small_font} MetaAI Segment-Anything models, see https://arxiv.org/abs/2304.02643"
190+
)
191+
192+
st.markdown("### FAQ")
193+
st.markdown(f"{small_font} Q: What can be done by AmadeusGPT🎻?")
194+
st.markdown(
195+
f"{small_font} - A: We provide a natural language interface to analyze video-based behavioral data. \n"
196+
f"{small_font} We expect the user to describe a behavior before asking about the behaviors.\n"
197+
f"{small_font} In general, one can define behaviors related to the movement of an animal (see EPM example), animal to animal interactions (see the MABe example) and\n"
198+
f"{small_font} animal-environment interaction (check MausHaus example)."
199+
)
200+
st.markdown(f"{small_font} Q: Can I run my own videos?")
201+
st.markdown(
202+
f"{small_font} - A: Not yet - due to limited compute resources we disabled on-demand pose estimation and object segmentation thus we cannot take new videos at this time. For your best experience, we pre-compute the pose and segmentation for example videos we provided. However, running DeepLabCut, SAM and other computer vision models is possible with AmadeusGPT🎻 so stay tuned!"
203+
)
204+
st.markdown(
205+
f"{small_font} Q: in the demos you use the term 'unit' - What is the unit being used?"
206+
)
207+
st.markdown(
208+
f"{small_font} - A: Pixels for distance and pixel per frame for speed and velocity given we don't have real-world values in distance"
209+
)
210+
st.markdown(
211+
f"{small_font} Q: How can I draw ROI and use the ROI to define a behavior?"
212+
)
213+
st.markdown(f"{small_font} - A: Check the video on the EPM tab!")
214+
st.markdown(f"{small_font} Q: How can I ask AmadeusGPT🎻 to plot something?")
215+
st.markdown(f"{small_font} - A: Check the demo video and prompts in the examples")
216+
st.markdown(
217+
f"{small_font} Q: Why did AmadeusGPT🎻 produce errors or give me unexpected answers to my questions?"
218+
)
219+
st.markdown(
220+
f"{small_font} - A: Most likely that you are asking for something that is beyond the current capability of AmadeusGPT🎻 or\n"
221+
"you are asking questions in a way that is unexpected. In either cases, we appreciate it if you can provide feedback \n"
222+
"to us in our GitHub repo so we can improve our system (and note we log your queries and will use this to improve AmadeusGPT🎻)."
223+
)
224+
225+
st.markdown(f"{small_font} Q: Does it work with mice only?")
226+
st.markdown(
227+
f"{small_font} - A: No, AmadeusGPT🎻 can work with a range of animals as long as poses are extracted and behaviors can be defined with those poses. We will add examples of other animals in the future."
228+
)
229+
st.markdown(f"{small_font} Q: How do I know I can trust AmadeusGPT🎻's answers?")
230+
st.markdown(
231+
f"{small_font} - A: For people who are comfortable with reading Python code, reading the code can help validate the answer. We welcome the community to check our APIs. Otherwise, try visualize your questions by asking \n"
232+
f"{small_font} AmadeusGPT🎻 to plot the related data and use the visualization as a cross validation. We are also developing new features\n"
233+
f"{small_font} to help you gain more confidence on the results and how the results are obtained."
234+
)
235+
st.markdown(
236+
f"{small_font} Q: Why the page is blocked for a long time and there is no response?"
237+
)
238+
st.markdown(
239+
f"{small_font} - A: There might be a high traffic for either ChatGPT API or the Streamlit server. Refresh the page and retry or come back later."
240+
)
241+
242+
243+
if st.session_state["exist_valid_openai_api_key"]:
244+
example_list = ["Welcome", "Custom", "EPM", "MausHaus", "MABe", "Horse"]
245+
else:
246+
example_list = ["Welcome"]
247+
248+
for key in example_list:
249+
if key == "Welcome":
250+
example_to_page[key] = welcome_page
251+
else:
252+
example_to_page[key] = app_utils.render_page_by_example
253+
254+
with st.sidebar as sb:
255+
example_bar = st.sidebar.selectbox(
256+
"Select an example dataset", example_to_page.keys()
257+
)
258+
259+
try:
260+
if "enable_profiler" in os.environ:
261+
with Profiler():
262+
example_to_page[example_bar](example_bar)
263+
else:
264+
example_to_page[example_bar](example_bar)
265+
266+
except Exception as e:
267+
print(traceback.format_exc())
268+
if "streamlit_cloud" in os.environ:
269+
if "session_id" in st.session_state:
270+
AmadeusLogger.store_chats("errors", str(e) + "\n" + traceback.format_exc())
271+
AmadeusLogger.debug(traceback.format_exc())
272+
273+
274+
if __name__ == "__main__":
275+
main()
File renamed without changes.

0 commit comments

Comments
 (0)