akhilsu commited on
Commit
3e0bc35
·
verified ·
1 Parent(s): 64313a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -55
app.py CHANGED
@@ -1,71 +1,83 @@
1
  import streamlit as st
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
 
4
 
5
- # Load the tokenizer and model
6
- model_name = "meta-llama/Llama-3.2-1B-Instruct"
7
- tokenizer = AutoTokenizer.from_pretrained(model_name)
8
- model = AutoModelForCausalLM.from_pretrained(model_name)
9
- model.to('cuda' if torch.cuda.is_available() else 'cpu') # Move model to GPU if available
10
 
11
- # Streamlit app setup
12
- st.set_page_config(
13
- page_title="AI Chatbot",
14
- page_icon="🤖",
15
- layout="wide",
16
- initial_sidebar_state="expanded",
17
- )
 
 
 
18
 
19
- # Sidebar
20
- st.sidebar.title("Chatbot Settings")
21
- max_length = st.sidebar.slider("Response Length", min_value=50, max_value=512, value=100)
22
- temperature = st.sidebar.slider("Temperature", min_value=0.5, max_value=1.5, value=0.95)
23
- st.sidebar.markdown("Adjust the response settings for the chatbot.")
 
 
24
 
25
- # Main page
26
- st.title("🤖 Chat with AI")
27
- st.markdown("Welcome to the interactive AI chatbot. Start a conversation by typing below:")
 
 
28
 
29
- # Chat container
30
- if "conversation" not in st.session_state:
31
- st.session_state.conversation = []
32
 
33
- def generate_response(user_input, history=[], max_new_tokens=512, temperature=0.95):
34
- # Prepare the conversation history
35
- conversation = [{"role": "user", "content": msg} for msg in history]
36
- conversation.append({"role": "user", "content": user_input})
37
 
38
- # Tokenize the input
39
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
 
 
40
 
41
- # Generate response
42
- outputs = model.generate(
43
- input_ids,
44
- max_new_tokens=max_new_tokens,
45
- do_sample=True,
46
- temperature=temperature,
47
- eos_token_id=tokenizer.eos_token_id
48
- )
49
 
50
- # Decode and return the response
51
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
52
- return response.split("assistant")[1]
 
 
 
 
 
53
 
54
- def add_to_conversation(user_input, bot_response):
55
- st.session_state.conversation.append({"user": user_input, "bot": bot_response})
 
56
 
57
- # User input
58
- user_input = st.text_input("You:", "")
59
- if st.button("Send") and user_input:
60
- bot_response = generate_response(user_input, max_new_tokens=max_length, temperature=temperature)
61
- add_to_conversation(user_input, bot_response)
62
- user_input = "" # Clear the input field
63
 
64
- # Display conversation
65
- for chat in st.session_state.conversation:
66
- st.markdown(f"**You:** {chat['user']}")
67
- st.markdown(f"**Bot:** {chat['bot']}")
 
 
68
 
69
- # Footer
70
- st.markdown("---")
71
- st.markdown("Developed by Akhil Sudhakaran")
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
+ import os
5
 
6
+ # Retrieve the Hugging Face token from environment variables
7
+ HF_TOKEN = os.environ.get("GColab", None)
 
 
 
8
 
9
+ # Ensure the token is provided
10
+ if HF_TOKEN is None:
11
+ st.error("Hugging Face token is not set. Please set the HF_TOKEN environment variable.")
12
+ else:
13
+ # Load the tokenizer and model
14
+ model_name = "meta-llama/Llama-3.2-1B-Instruct"
15
+ try:
16
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=HF_TOKEN)
17
+ model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=HF_TOKEN)
18
+ model.to('cuda' if torch.cuda.is_available() else 'cpu') # Move model to GPU if available
19
 
20
+ # Streamlit app setup
21
+ st.set_page_config(
22
+ page_title="AI Chatbot",
23
+ page_icon="🤖",
24
+ layout="wide",
25
+ initial_sidebar_state="expanded",
26
+ )
27
 
28
+ # Sidebar
29
+ st.sidebar.title("Chatbot Settings")
30
+ max_length = st.sidebar.slider("Response Length", min_value=50, max_value=512, value=100)
31
+ temperature = st.sidebar.slider("Temperature", min_value=0.5, max_value=1.5, value=0.95)
32
+ st.sidebar.markdown("Adjust the response settings for the chatbot.")
33
 
34
+ # Main page
35
+ st.title("🤖 Chat with AI")
36
+ st.markdown("Welcome to the interactive AI chatbot. Start a conversation by typing below:")
37
 
38
+ # Chat container
39
+ if "conversation" not in st.session_state:
40
+ st.session_state.conversation = []
 
41
 
42
+ def generate_response(user_input, history=[], max_new_tokens=512, temperature=0.95):
43
+ # Prepare the conversation history
44
+ conversation = [{"role": "user", "content": msg} for msg in history]
45
+ conversation.append({"role": "user", "content": user_input})
46
 
47
+ # Tokenize the input
48
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
 
 
 
 
 
 
49
 
50
+ # Generate response
51
+ outputs = model.generate(
52
+ input_ids,
53
+ max_new_tokens=max_new_tokens,
54
+ do_sample=True,
55
+ temperature=temperature,
56
+ eos_token_id=tokenizer.eos_token_id
57
+ )
58
 
59
+ # Decode and return the response
60
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
61
+ return response.split("assistant")[1]
62
 
63
+ def add_to_conversation(user_input, bot_response):
64
+ st.session_state.conversation.append({"user": user_input, "bot": bot_response})
 
 
 
 
65
 
66
+ # User input
67
+ user_input = st.text_input("You:", "")
68
+ if st.button("Send") and user_input:
69
+ bot_response = generate_response(user_input, max_new_tokens=max_length, temperature=temperature)
70
+ add_to_conversation(user_input, bot_response)
71
+ user_input = "" # Clear the input field
72
 
73
+ # Display conversation
74
+ for chat in st.session_state.conversation:
75
+ st.markdown(f"**You:** {chat['user']}")
76
+ st.markdown(f"**Bot:** {chat['bot']}")
77
+
78
+ # Footer
79
+ st.markdown("---")
80
+ st.markdown("Developed by Akhil Sudhakaran")
81
+
82
+ except Exception as e:
83
+ st.error(f"An error occurred: {e}")