Replace token input with Hugging Face OAuth authentication

#6
by ferrywuai - opened
Files changed (2) hide show
  1. README.md +31 -28
  2. src/streamlit_app.py +86 -19
README.md CHANGED
@@ -10,49 +10,52 @@ tags:
10
  pinned: false
11
  short_description: Test docker sdk streamlit template
12
  license: mit
 
 
 
13
  ---
14
 
15
  # Welcome to Chatbot!
16
 
17
- The following command installs required packages of the chatbot.
18
 
19
- ```
20
- pip install -r requirements.txt
21
- ```
22
 
23
- The following commands provides API token to the chatbot. Choose from one of them.
24
 
25
- - Login Hugging Face Hub
 
 
 
26
 
27
- ```
28
- hf auth login
29
- ```
30
 
31
- - Set HF_TOKEN environment variable
32
 
33
- ```
34
- export HF_TOKEN=<Your Hugging Face Token>
35
- ```
36
 
37
- The following command runs the chatbot.
38
 
39
- ```
40
- streamlit run src/streamlit_app.py
41
- ```
42
 
43
- Use browser to access the chatbot after you see the following message.
 
 
 
44
 
45
- ```
46
- You can now view your Streamlit app in your browser.
 
 
47
 
48
- Local URL: http://localhost:8501
49
- Network URL: http://172.28.148.72:8501
50
- ```
51
 
52
- Use Crtl+C to stop the chatbot.
 
 
53
 
54
- Logout Hugging Face Hub if you have logged in.
55
 
56
- ```
57
- hf auth logout
58
- ```
 
10
  pinned: false
11
  short_description: Test docker sdk streamlit template
12
  license: mit
13
+ hf_oauth: true
14
+ hf_oauth_scopes:
15
+ - inference-api
16
  ---
17
 
18
  # Welcome to Chatbot!
19
 
20
+ ## Local Setup Instructions
21
 
22
+ To run this app locally, follow these steps:
 
 
23
 
24
+ 1. **Clone the repository**
25
 
26
+ ```bash
27
+ git clone https://huggingface.co/spaces/ferrywuai/streamlit-chatbot-oauth-test
28
+ cd streamlit-chatbot-oauth-test
29
+ ```
30
 
31
+ 2. **Install dependencies**
 
 
32
 
33
+ Make sure you have Python 3.8+ installed, then run:
34
 
35
+ ```bash
36
+ pip install -r requirements.txt
37
+ ```
38
 
39
+ 3. **Set up OAuth credentials**
40
 
41
+ This app requires OAuth credentials from Hugging Face to function properly.
 
 
42
 
43
+ - Visit the [Hugging Face OAuth documentation](https://huggingface.co/docs/hub/oauth)
44
+ - Create a new OAuth App
45
+ - Copy the Client ID and Client Secret
46
+ - Set them as environment variables in your local environment:
47
 
48
+ ```bash
49
+ export OAUTH_CLIENT_ID="your-client-id"
50
+ export OAUTH_CLIENT_SECRET="your-client-secret"
51
+ ```
52
 
53
+ 4. **Run the app**
 
 
54
 
55
+ ```bash
56
+ streamlit run src/streamlit_app.py
57
+ ```
58
 
59
+ 5. **Launch browser**
60
 
61
+ Open <http://localhost:8501> URL to access the app.
 
 
src/streamlit_app.py CHANGED
@@ -1,7 +1,19 @@
1
  import os
 
 
2
 
 
3
  import streamlit as st
4
- from huggingface_hub import HfFolder, InferenceClient
 
 
 
 
 
 
 
 
 
5
 
6
  chat_parameters = {
7
  "system_prompt": "You are a friendly Chatbot.",
@@ -17,6 +29,59 @@ def switch_page():
17
  st.rerun()
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def get_chat_parameters():
21
  with st.sidebar:
22
  chat_parameters["system_prompt"] = st.text_area(
@@ -62,25 +127,27 @@ def get_reponse(client, user_input):
62
 
63
 
64
  def login():
65
- api_token = HfFolder.get_token()
66
- env_token = os.getenv("HF_TOKEN")
67
-
68
- if api_token:
69
- st.session_state.hf_token = api_token
70
- switch_page()
71
- elif env_token:
72
- st.session_state.hf_token = env_token
73
- switch_page()
 
 
 
 
 
 
 
74
  else:
75
- st.title("πŸ” Please input Hugging Face Token")
76
- user_token = st.text_input("HF_TOKEN", type="password")
77
- if st.button("βœ… Login"):
78
- if user_token:
79
- st.session_state.hf_token = user_token
80
- switch_page()
81
- else:
82
- st.session_state.message = st.warning(
83
- "Please enter a valid token.")
84
 
85
 
86
  def chatbot():
 
1
  import os
2
+ import urllib
3
+ import uuid
4
 
5
+ import requests
6
  import streamlit as st
7
+ from huggingface_hub import InferenceClient
8
+
9
+ oauth_parameters = {
10
+ "client_id": "",
11
+ "client_secret": "",
12
+ "redirect_uri": "http://localhost:8501",
13
+ "scope": "openid profile inference-api",
14
+ "auth_uri": "https://huggingface.co/oauth/authorize",
15
+ "token_uri": "https://huggingface.co/oauth/token",
16
+ }
17
 
18
  chat_parameters = {
19
  "system_prompt": "You are a friendly Chatbot.",
 
29
  st.rerun()
30
 
31
 
32
+ def get_oauth_parameters():
33
+ client_id = os.getenv("OAUTH_CLIENT_ID")
34
+ client_secret = os.getenv("OAUTH_CLIENT_SECRET")
35
+
36
+ if not client_id or not client_secret:
37
+ st.warning("OAuth credentials missing.")
38
+ st.markdown(
39
+ "### Missing OAuth Configuration\n\n"
40
+ "To use this app, you need to "
41
+ "set up OAuth credentials from Hugging Face.\n\n"
42
+ "1. Visit [Hugging Face OAuth documentation]"
43
+ "(https://huggingface.co/docs/hub/oauth).\n"
44
+ "2. Create a new OAuth App.\n"
45
+ "3. Copy the **Client ID** and **Client Secret**.\n"
46
+ "4. Set them as environment variables on your system:\n\n"
47
+ "```bash\n"
48
+ "export OAUTH_CLIENT_ID=\"your-client-id\"\n"
49
+ "export OAUTH_CLIENT_SECRET=\"your-client-secret\"\n"
50
+ "```\n\n"
51
+ "Restart the app after setting the variables."
52
+ )
53
+ st.stop()
54
+
55
+ oauth_parameters["client_id"] = client_id
56
+ oauth_parameters["client_secret"] = client_secret
57
+ space_host = os.getenv("SPACE_HOST")
58
+ if space_host:
59
+ oauth_parameters["redirect_uri"] = f"https://{space_host}"
60
+
61
+
62
+ def get_auth_url():
63
+ params = {
64
+ "response_type": "code",
65
+ "client_id": oauth_parameters["client_id"],
66
+ "redirect_uri": oauth_parameters["redirect_uri"],
67
+ "scope": oauth_parameters["scope"],
68
+ "state": uuid.uuid4(),
69
+ }
70
+ return f"{oauth_parameters['auth_uri']}?{urllib.parse.urlencode(params)}"
71
+
72
+
73
+ def get_token(code):
74
+ data = {
75
+ "grant_type": "authorization_code",
76
+ "code": code,
77
+ "redirect_uri": oauth_parameters["redirect_uri"],
78
+ "client_id": oauth_parameters["client_id"],
79
+ "client_secret": oauth_parameters["client_secret"],
80
+ }
81
+ response = requests.post(oauth_parameters["token_uri"], data=data)
82
+ return response.json()
83
+
84
+
85
  def get_chat_parameters():
86
  with st.sidebar:
87
  chat_parameters["system_prompt"] = st.text_area(
 
127
 
128
 
129
  def login():
130
+ st.title("πŸ” Hugging Face OAuth Login")
131
+ get_oauth_parameters()
132
+
133
+ query_params = st.query_params
134
+ code = query_params.get("code")
135
+
136
+ if code:
137
+ token_data = get_token(code)
138
+ access_token = token_data.get("access_token")
139
+
140
+ if access_token:
141
+ st.success("πŸŽ‰ Login successful!")
142
+ st.session_state.hf_token = access_token
143
+ switch_page()
144
+ else:
145
+ st.error("❌ Failed to get access token")
146
  else:
147
+ auth_link = get_auth_url()
148
+ st.markdown(f"""
149
+ <a href="{auth_link}" target="_blank">πŸ” Login with Hugging Face</a>
150
+ """, unsafe_allow_html=True)
 
 
 
 
 
151
 
152
 
153
  def chatbot():