jan01 commited on
Commit
7cbd9ad
·
verified ·
1 Parent(s): e8e0b05

Update mindmentor_app.py

Browse files
Files changed (1) hide show
  1. mindmentor_app.py +33 -25
mindmentor_app.py CHANGED
@@ -1,33 +1,42 @@
1
  import streamlit as st
2
  import os
3
  from llama_cpp import Llama
4
- from huggingface_hub import hf_hub_download
5
 
6
  # ------------------------------
7
- # Load Quantized LLM Model
8
  # ------------------------------
9
  @st.cache_resource(show_spinner="🔄 Loading TinyLlama AI Model...")
10
  def load_llm():
11
- try:
 
 
 
 
 
12
  model_path = hf_hub_download(
13
  repo_id="TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF",
14
- filename="tinyllama-1.1b-chat-v1.0.Q4_0.gguf"
15
- )
16
- return Llama(
17
- model_path=model_path,
18
- n_ctx=2048,
19
- n_threads=4,
20
- n_gpu_layers=0,
21
- verbose=False
22
  )
23
- except Exception as e:
24
- st.error(f"❌ Failed to load TinyLlama model: {e}")
25
- st.stop()
26
 
27
- llm = load_llm()
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  # ------------------------------
30
- # Generate Chatbot Response
31
  # ------------------------------
32
  def get_response(message):
33
  prompt = f"""You are MindMentor, an offline AI coach that helps people with stress, emotions, and self-awareness. You are kind, caring, helpful, and positive.
@@ -37,25 +46,25 @@ Assistant:"""
37
  output = llm(prompt=prompt, max_tokens=200, stop=["User:", "\n"])
38
  return output["choices"][0]["text"].strip()
39
  except Exception as e:
40
- return f"⚠️ Error generating response: {e}"
41
 
42
  # ------------------------------
43
- # Streamlit Chat UI
44
  # ------------------------------
45
- st.set_page_config(page_title="🧠 MindMentor - Offline AI Coach", layout="centered")
46
  st.title("🧠 MindMentor - Offline AI Coach")
47
- st.markdown("Your personal mental wellbeing assistant 💬 — all offline and private.")
48
 
49
- # Initialize chat history
50
  if "chat_history" not in st.session_state:
51
  st.session_state.chat_history = []
52
 
53
- # Display previous messages
54
  for msg in st.session_state.chat_history:
55
  with st.chat_message(msg["role"]):
56
  st.markdown(msg["content"])
57
 
58
- # Input box for new user message
59
  user_input = st.chat_input("Talk to MindMentor...")
60
 
61
  if user_input:
@@ -63,10 +72,9 @@ if user_input:
63
  st.chat_message("user").markdown(user_input)
64
  st.session_state.chat_history.append({"role": "user", "content": user_input})
65
 
66
- # Generate and show assistant reply
67
  with st.chat_message("assistant"):
68
  with st.spinner("Thinking..."):
69
  reply = get_response(user_input)
70
  st.markdown(reply)
71
  st.session_state.chat_history.append({"role": "assistant", "content": reply})
72
-
 
1
  import streamlit as st
2
  import os
3
  from llama_cpp import Llama
 
4
 
5
  # ------------------------------
6
+ # Load the Quantized LLM Model
7
  # ------------------------------
8
  @st.cache_resource(show_spinner="🔄 Loading TinyLlama AI Model...")
9
  def load_llm():
10
+ local_dir = "models"
11
+ filename = "tinyllama-1.1b-chat-v1.0.Q4_0.gguf"
12
+ model_path = os.path.join(local_dir, filename)
13
+
14
+ if not os.path.exists(model_path):
15
+ from huggingface_hub import hf_hub_download
16
  model_path = hf_hub_download(
17
  repo_id="TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF",
18
+ filename=filename,
19
+ local_dir=local_dir,
20
+ local_dir_use_symlinks=False
 
 
 
 
 
21
  )
 
 
 
22
 
23
+ return Llama(
24
+ model_path=model_path,
25
+ n_ctx=1024, # Use 1024 context to reduce memory usage on Spaces
26
+ n_threads=4,
27
+ n_gpu_layers=0,
28
+ verbose=False
29
+ )
30
+
31
+ # Initialize LLM
32
+ try:
33
+ llm = load_llm()
34
+ except Exception as e:
35
+ st.error(f"❌ Failed to load TinyLlama: {e}")
36
+ st.stop()
37
 
38
  # ------------------------------
39
+ # Function to Get Chatbot Reply
40
  # ------------------------------
41
  def get_response(message):
42
  prompt = f"""You are MindMentor, an offline AI coach that helps people with stress, emotions, and self-awareness. You are kind, caring, helpful, and positive.
 
46
  output = llm(prompt=prompt, max_tokens=200, stop=["User:", "\n"])
47
  return output["choices"][0]["text"].strip()
48
  except Exception as e:
49
+ return f"⚠️ Oops! Model failed to respond: {e}"
50
 
51
  # ------------------------------
52
+ # Streamlit UI
53
  # ------------------------------
54
+ st.set_page_config(page_title="MindMentor AI Chatbot", layout="centered")
55
  st.title("🧠 MindMentor - Offline AI Coach")
56
+ st.markdown("Your personal mental wellbeing assistant 💬 — all offline!")
57
 
58
+ # Session state
59
  if "chat_history" not in st.session_state:
60
  st.session_state.chat_history = []
61
 
62
+ # Show chat history
63
  for msg in st.session_state.chat_history:
64
  with st.chat_message(msg["role"]):
65
  st.markdown(msg["content"])
66
 
67
+ # Input box
68
  user_input = st.chat_input("Talk to MindMentor...")
69
 
70
  if user_input:
 
72
  st.chat_message("user").markdown(user_input)
73
  st.session_state.chat_history.append({"role": "user", "content": user_input})
74
 
75
+ # Generate assistant reply
76
  with st.chat_message("assistant"):
77
  with st.spinner("Thinking..."):
78
  reply = get_response(user_input)
79
  st.markdown(reply)
80
  st.session_state.chat_history.append({"role": "assistant", "content": reply})