zastixx commited on
Commit
32cf8e8
·
verified ·
1 Parent(s): 3f8ca9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -92
app.py CHANGED
@@ -1,107 +1,126 @@
1
- """
2
- import streamlit as st
3
- import firebase_admin
4
- from firebase_admin import credentials, auth
5
-
6
-
7
  import streamlit as st
8
-
9
- st.set_page_config(initial_sidebar_state="collapsed")
10
-
 
 
 
 
 
 
 
 
 
 
11
  st.markdown(
12
  """
13
- <style>
14
- [data-testid="collapsedControl"] {
15
- display: none
16
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- .reportview-container {
19
  margin-top: -2em;
20
  }
21
  #MainMenu {visibility: hidden;}
22
  .stDeployButton {display:none;}
 
23
  #stDecoration {display:none;}
24
- </style>
25
-
26
- </style>
27
  """,
28
  unsafe_allow_html=True,
29
  )
30
 
31
 
 
 
 
32
 
33
- # Check if Firebase Admin SDK has been initialized
34
- if not firebase_admin._apps:
35
- # Initialize Firebase Admin SDK
36
- cred = credentials.Certificate("tokens/gdfg-cf9d9-firebase-adminsdk-593q1-5d02a16c64.json") # Update with your own service account key
37
- firebase_admin.initialize_app(cred)
38
-
39
- # Function to sign up a new user
40
- def signup(email, password):
41
- try:
42
- user = auth.create_user(email=email, password=password)
43
- st.success("User created successfully!")
44
- return True
45
- except Exception as e:
46
- st.error(f"Error creating user: {e}")
47
- return False
48
-
49
- # Function to log in existing user
50
- def login(email, password):
51
- try:
52
- user = auth.get_user_by_email(email)
53
- st.session_state['logged_in'] = True # Initialize the 'logged_in' key
54
- st.success("Login successful!")
55
- return True
56
- except Exception as e:
57
- st.error(f"Error logging in: {e}")
58
- return False
59
-
60
- # Main function
61
- def main():
62
- st.title("VX1000 BetaV")
63
-
64
- # Sign up form
65
- with st.form("signup_form"):
66
- st.header("Sign Up")
67
- email = st.text_input("Email")
68
- password = st.text_input("Password", type="password")
69
- signup_button = st.form_submit_button("Sign Up")
70
-
71
- if signup_button:
72
- if signup(email, password):
73
- # Redirect to another Python code after signup
74
- st.success("Check your Mail")
75
- # Insert code for redirection here
76
-
77
- # Login form
78
- with st.form("login_form"):
79
- st.header("Login")
80
- email = st.text_input("Email")
81
- password = st.text_input("Password", type="password")
82
- login_button = st.form_submit_button("Login")
83
-
84
- # if login_button:
85
- if login(email, password):
86
- if 'logged_in' in st.session_state and st.session_state['logged_in']: # Check if logged in
87
- st.switch_page("pages/VX1000 BetaV Model.py")# Redirect to new page after successful login
88
- else:
89
- st.warning("An unexpected error occurred. Please try again.")
90
-
91
- st.markdown(
92
- """
93
- <hr style="margin-top: 50px;">
94
- <footer style="text-align: center;">
95
- <p>© 2024 VX1000 BetaV All rights reserved.</p>
96
- <p>Made with ❤️ by<a href="https://builtwithtarun.me/" target="_blank"> Tarun</a></p>
97
-
98
- </footer>
99
- """,
100
- unsafe_allow_html=True
101
- )
102
-
103
- if __name__ == "__main__":
104
- main()
105
- """
106
- import streamlit as st
107
- <p>© 2024 VX1000 BetaV All rights reserved.</p>
 
1
+ from langchain_community.vectorstores import FAISS
2
+ from langchain_community.embeddings import HuggingFaceEmbeddings
3
+ from langchain.prompts import PromptTemplate
4
+ import os
5
+ from langchain.memory import ConversationBufferWindowMemory
6
+ from langchain.chains import ConversationalRetrievalChain
7
  import streamlit as st
8
+ import time
9
+ from dotenv import load_dotenv, find_dotenv
10
+ from langchain_together import Together
11
+
12
+ load_dotenv(find_dotenv())
13
+ st.set_page_config(page_title="VX1000 BetaV")
14
+ col1, col2, col3 = st.columns([1, 2, 1])
15
+ with col2:
16
+ st.title("VX1000 BetaV 🦾")
17
+ st.caption('⚠️ **_Note: Please Wait 5 second after Prompt_**')
18
+
19
+ #st.sidebar.title("Welcome to VX1000 BetaV Model")
20
+ #st.sidebar.title("Shoot your questions")
21
  st.markdown(
22
  """
23
+ <style>
24
+ div.stButton > button:first-child {
25
+ background-color: #ffd0d0;
26
+ }
27
+
28
+ div.stButton > button:active {
29
+ background-color: #ff6262;
30
+ }
31
+
32
+ .st-emotion-cache-6qob1r {
33
+ position: relative;
34
+ height: 100%;
35
+ width: 100%;
36
+ background-color: black;
37
+ overflow: overlay;
38
+ }
39
+
40
+ div[data-testid="stStatusWidget"] div button {
41
+ display: none;
42
+ }
43
 
44
+ .reportview-container {
45
  margin-top: -2em;
46
  }
47
  #MainMenu {visibility: hidden;}
48
  .stDeployButton {display:none;}
49
+ footer {visibility: hidden;}
50
  #stDecoration {display:none;}
51
+ button[title="View fullscreen"]{
52
+ visibility: hidden;}
53
+ </style>
54
  """,
55
  unsafe_allow_html=True,
56
  )
57
 
58
 
59
+ def reset_conversation():
60
+ st.session_state.messages = []
61
+ st.session_state.memory.clear()
62
 
63
+
64
+ if "messages" not in st.session_state:
65
+ st.session_state.messages = []
66
+
67
+ if "memory" not in st.session_state:
68
+ st.session_state.memory = ConversationBufferWindowMemory(k=2, memory_key="chat_history", return_messages=True)
69
+
70
+ embeddings = HuggingFaceEmbeddings(model_name="nomic-ai/nomic-embed-text-v1-ablated", model_kwargs={"trust_remote_code": True})
71
+ db = FAISS.load_local("data_byte", embeddings, allow_dangerous_deserialization=True)
72
+ db_retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 4})
73
+
74
+ prompt_template = """<s>[INST]This is a chat template ,Don't generate gym related every time answer,your name is VX1000 BetaV Model,this model is made by Tarun,trained by Tarun,made by Tarun ,llm model is made by Tarun,you have 1 bilion parameters, and you are the private gpt model , your primary objective is to provide accurate and concise information related to code, question solving, based on the user's questions. Do not generate your own questions and answers. You will adhere strictly to the instructions provided, offering relevant context from the knowledge base while avoiding unnecessary details. Your responses will be brief, to the point, and in compliance with the established format. If a question falls outside the given context, rely on your own knowledge base to generate an appropriate response. You will prioritize the user's query and refrain from posing additional questions and do not repeat the prompt template and the things that you have said already.
75
+ QUESTION: {question}
76
+ CONTEXT: {context}
77
+ CHAT HISTORY: {chat_history}[/INST]
78
+ ASSISTANT:
79
+ </s>
80
+ """
81
+
82
+ prompt = PromptTemplate(template=prompt_template,
83
+ input_variables=['question', 'context', 'chat_history'])
84
+
85
+ llm = Together(
86
+ model="mistralai/Mixtral-8x7B-Instruct-v0.1",
87
+ temperature=0.7,
88
+ max_tokens=1024,
89
+ top_k=1,
90
+ together_api_key=os.environ['T_API']
91
+ )
92
+
93
+ qa = ConversationalRetrievalChain.from_llm(
94
+ llm=llm,
95
+ memory=st.session_state.memory,
96
+ retriever=db_retriever,
97
+ combine_docs_chain_kwargs={'prompt': prompt}
98
+ )
99
+
100
+ for message in st.session_state.messages:
101
+ with st.chat_message(message.get("role")):
102
+ st.write(message.get("content"))
103
+
104
+ input_prompt = st.chat_input("Say something")
105
+
106
+ if input_prompt:
107
+ with st.chat_message("user"):
108
+ st.write(input_prompt)
109
+
110
+ st.session_state.messages.append({"role": "user", "content": input_prompt})
111
+
112
+ with st.chat_message("assistant"):
113
+ with st.status("Lifting data, one bit at a time 💡🦾...", expanded=True):
114
+ result = qa.invoke(input=input_prompt)
115
+
116
+ message_placeholder = st.empty()
117
+
118
+ full_response = "⚠️ **_Note: Information provided may be inaccurate._** \n\n\n"
119
+ for chunk in result["answer"]:
120
+ full_response += chunk
121
+ time.sleep(0.02)
122
+
123
+ message_placeholder.markdown(full_response + " ")
124
+ st.button('Reset All Chat 🗑️', on_click=reset_conversation)
125
+
126
+ st.session_state.messages.append({"role": "assistant", "content": result["answer"]})