zizytd commited on
Commit
a759c01
·
verified ·
1 Parent(s): 58ea3b2

updating v4

Browse files
Files changed (1) hide show
  1. app.py +42 -82
app.py CHANGED
@@ -2,32 +2,29 @@ import streamlit as st
2
  import json
3
  import os
4
  import re
5
- import requests
6
  import uuid
7
  import time
8
  import torch
9
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
10
 
11
- # Load the Hugging Face model
12
- model_name = "ethicsadvisorproject/Llama-2-7b-ethical-chat-finetune"
13
- tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir="/tmp")
14
- model = AutoModelForCausalLM.from_pretrained(
15
- model_name,
16
- torch_dtype=torch.float16,
17
- device_map="auto",
18
- offload_folder="/tmp"
19
- )
20
-
21
- pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_length=200)
22
-
23
  DB_DIR = 'user_data' # Directory to store individual user data
24
  os.makedirs(DB_DIR, exist_ok=True) # Ensure the directory exists
25
 
26
- def stream_data(textto):
27
- for word in textto.split(" "):
28
- yield word + " "
29
- time.sleep(0.02)
30
-
 
 
 
 
 
 
 
 
31
 
32
  def get_user_id():
33
  """Generate or retrieve a unique ID for the user."""
@@ -36,7 +33,7 @@ def get_user_id():
36
  return st.session_state.user_id
37
 
38
  def get_user_file(user_id):
39
- """Return the file path for a user's data file ok."""
40
  return os.path.join(DB_DIR, f"{user_id}.json")
41
 
42
  def load_user_data(user_id):
@@ -54,47 +51,34 @@ def save_user_data(user_id, data):
54
  json.dump(data, file)
55
 
56
  def main():
57
- endpoint_url = "https://zizytd-ethical-app-docker.hf.space/predict" # Endpoint URL from .env
58
-
59
- user_id = get_user_id()
60
- user_data = load_user_data(user_id)
61
-
62
- # st.set_page_config(page_title='Ethical GPT Assistant', layout='wide',
63
- # # initial_sidebar_state=st.session_state.get('sidebar_state', 'collapsed'),
64
- # )
65
 
66
- st.image("./logo/images.jpeg", use_container_width=True )
67
-
68
- #st.snow()
69
 
70
  intro = """
71
  ## Welcome to EthicsAdvisor
72
-
73
- Ethical GPT is an AI-powered chatbot designed to interact with you in an ethical, safe, and responsible manner. Our goal is to ensure that all responses provided by the assistant are respectful and considerate of various societal and ethical standards.
74
 
 
75
  Feel free to ask any questions, and rest assured that the assistant will provide helpful and appropriate responses.
76
  """
77
-
78
  st.markdown(intro)
79
 
80
  # Sidebar options
81
- models = ["llama-ethical"]
82
- st.sidebar.selectbox("Select Model", models, index=0)
83
-
84
  st.sidebar.title("❄️EthicsAdvisor 📄")
85
- st.sidebar.caption("Make AI to responde more ethical")
86
-
87
-
88
- with st.sidebar.expander("See fine tuning info"):
89
- st.caption("Original Data: [Data] (https://huggingface.co/datasets/MasahiroKaneko/eagle/)")
90
  st.caption("Modified Data: [Data](https://huggingface.co/datasets/ethicsadvisorproject/ethical_data_bigger/) 📝")
91
- st.caption("Used Model and Notebook: [Original model](https://huggingface.co/ethicsadvisorproject/Llama-2-7b-ethical-chat-finetune/) 🎈, Notebook used for fine tuning [Notebook](https://colab.research.google.com/drive/1eAAjdwwD0i-i9-ehEJYUKXvZoYK0T3ue#scrollTo=ib_We3NLtj2E)")
92
-
93
  with st.sidebar.expander("ℹ️ **Take survey**"):
94
- st.markdown("""You are welcome to give us your input on this research [here](https://forms.office.com/r/H4ARtETV2q).""")
95
- cols = st.columns(2)
 
 
 
96
 
97
- # Load chat history into session state
98
  if "messages" not in st.session_state:
99
  st.session_state.messages = user_data["chat_history"]
100
 
@@ -103,44 +87,20 @@ def main():
103
  with st.chat_message(message["role"]):
104
  st.markdown(message["content"])
105
 
106
- # # User input
107
- # # if prompt := st.chat_input("What is up?"):
108
- # # st.session_state.messages.append({"role": "user", "content": prompt})
109
- # # with st.chat_message("user"):
110
- # # st.markdown(prompt)
111
-
112
- # # # Send request to the endpoint
113
- # # headers = {'ngrok-skip-browser-warning': 'true'}
114
- # # data = {'messages': st.session_state.messages[-1]['content']}
115
-
116
- # # try:
117
- # # response = requests.post(endpoint_url, json=data, headers=headers)
118
- # # response.raise_for_status() # Raise exception for HTTP errors
119
- # # response_data = response.json()
120
- # # response_text = response_data.get('response_text', '')
121
 
122
- # # Clean response text
123
- # message = re.sub(r'<s>\[INST\].*?\[/INST\]', '', response_text).strip()
 
124
 
125
- # with st.chat_message("assistant"):
126
- # st.markdown(message)
127
-
128
- # st.session_state.messages.append({"role": "assistant", "content": message})
129
-
130
- # except requests.exceptions.RequestException as e:
131
- # st.error(f"Error communicating with the endpoint: {e}")
132
- # except KeyError:
133
- # st.error(f"Unexpected response format. Missing 'response_text' key. Received: {response.text}")
134
-
135
- if prompt := st.chat_input("What is up?"):
136
- response = pipe(f"<s>[INST] {prompt} [/INST]")
137
- response_text = response[0]["generated_text"].replace("<s>[INST]", "").replace("[/INST]", "").strip()
138
-
139
- message = re.sub(r'<s>\[INST\].*?\[/INST\]', '', response_text).strip()
140
-
141
  with st.chat_message("assistant"):
142
  st.markdown(response_text)
143
-
144
  st.session_state.messages.append({"role": "assistant", "content": response_text})
145
 
146
  # Save updated chat history
@@ -152,7 +112,7 @@ def main():
152
  st.session_state.messages = []
153
  user_data["chat_history"] = []
154
  save_user_data(user_id, user_data)
155
- st.rerun()
156
 
157
  if __name__ == '__main__':
158
- main()
 
2
  import json
3
  import os
4
  import re
 
5
  import uuid
6
  import time
7
  import torch
8
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
9
 
10
+ # Constants
11
+ MODEL_NAME = "ethicsadvisorproject/Llama-2-7b-ethical-chat-finetune"
 
 
 
 
 
 
 
 
 
 
12
  DB_DIR = 'user_data' # Directory to store individual user data
13
  os.makedirs(DB_DIR, exist_ok=True) # Ensure the directory exists
14
 
15
+ # Load the Hugging Face model
16
+ @st.cache_resource
17
+ def load_model():
18
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, cache_dir="/tmp")
19
+ model = AutoModelForCausalLM.from_pretrained(
20
+ MODEL_NAME,
21
+ torch_dtype=torch.float16,
22
+ device_map="auto",
23
+ offload_folder="/tmp"
24
+ )
25
+ return pipeline("text-generation", model=model, tokenizer=tokenizer, max_length=200)
26
+
27
+ pipe = load_model()
28
 
29
  def get_user_id():
30
  """Generate or retrieve a unique ID for the user."""
 
33
  return st.session_state.user_id
34
 
35
  def get_user_file(user_id):
36
+ """Return the file path for a user's data file."""
37
  return os.path.join(DB_DIR, f"{user_id}.json")
38
 
39
  def load_user_data(user_id):
 
51
  json.dump(data, file)
52
 
53
  def main():
54
+ st.set_page_config(page_title='Ethical GPT Assistant', layout='wide')
 
 
 
 
 
 
 
55
 
56
+ st.image("./logo/images.jpeg", use_column_width=True)
 
 
57
 
58
  intro = """
59
  ## Welcome to EthicsAdvisor
 
 
60
 
61
+ Ethical GPT is an AI-powered chatbot designed to interact with you in an ethical, safe, and responsible manner. Our goal is to ensure that all responses provided by the assistant are respectful and considerate of various societal and ethical standards.
62
  Feel free to ask any questions, and rest assured that the assistant will provide helpful and appropriate responses.
63
  """
 
64
  st.markdown(intro)
65
 
66
  # Sidebar options
 
 
 
67
  st.sidebar.title("❄️EthicsAdvisor 📄")
68
+ st.sidebar.caption("Make AI responses more ethical")
69
+
70
+ with st.sidebar.expander("See fine-tuning info"):
71
+ st.caption("Original Data: [Data](https://huggingface.co/datasets/MasahiroKaneko/eagle/)")
 
72
  st.caption("Modified Data: [Data](https://huggingface.co/datasets/ethicsadvisorproject/ethical_data_bigger/) 📝")
73
+ st.caption("Used Model and Notebook: [Original model](https://huggingface.co/ethicsadvisorproject/Llama-2-7b-ethical-chat-finetune/) 🎈, Notebook used for fine-tuning [Notebook](https://colab.research.google.com/drive/1eAAjdwwD0i-i9-ehEJYUKXvZoYK0T3ue#scrollTo=ib_We3NLtj2E)")
74
+
75
  with st.sidebar.expander("ℹ️ **Take survey**"):
76
+ st.markdown("You are welcome to give us your input on this research [here](https://forms.office.com/r/H4ARtETV2q).")
77
+
78
+ # Initialize chat history
79
+ user_id = get_user_id()
80
+ user_data = load_user_data(user_id)
81
 
 
82
  if "messages" not in st.session_state:
83
  st.session_state.messages = user_data["chat_history"]
84
 
 
87
  with st.chat_message(message["role"]):
88
  st.markdown(message["content"])
89
 
90
+ # User input
91
+ prompt = st.chat_input("What is up?")
92
+ if prompt:
93
+ st.session_state.messages.append({"role": "user", "content": prompt})
94
+ with st.chat_message("user"):
95
+ st.markdown(prompt)
 
 
 
 
 
 
 
 
 
96
 
97
+ # Generate response
98
+ response = pipe(f"<s>[INST] {prompt} [/INST]")
99
+ response_text = response[0]["generated_text"].replace("<s>[INST]", "").replace("[/INST]", "").strip()
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  with st.chat_message("assistant"):
102
  st.markdown(response_text)
103
+
104
  st.session_state.messages.append({"role": "assistant", "content": response_text})
105
 
106
  # Save updated chat history
 
112
  st.session_state.messages = []
113
  user_data["chat_history"] = []
114
  save_user_data(user_id, user_data)
115
+ st.experimental_rerun()
116
 
117
  if __name__ == '__main__':
118
+ main()