Gowthamgokul commited on
Commit
fcb221c
·
verified ·
1 Parent(s): 19bc4b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -129
app.py CHANGED
@@ -4,149 +4,147 @@ import streamlit as st
4
  import logging
5
  from datetime import datetime
6
  from urllib.parse import urlparse, parse_qs
7
- import pandas as pd # Added as a common dependency, although not strictly required by the core chat logic
8
-
9
- # --- HUGGING FACE SECRETS ADJUSTMENT ---
10
- # In Hugging Face, secrets are generally managed via the repository settings
11
- # and accessed within the app using st.secrets.
12
- # We'll use st.secrets.get() for deployment-friendly API key retrieval.
13
 
14
  # Set browser tab title
15
- st.set_page_config(page_title="Learn AI with Rajamanickam.com")
16
 
17
- # start of admin side
18
  # Check if "admin" query parameter is present and valid
19
  query_params = st.query_params
20
  is_admin = query_params.get("admin") == "1234"
21
 
22
  # If admin, show download button
23
  if is_admin:
24
- if os.path.exists("usage_log.txt"):
25
- with open("usage_log.txt", "rb") as f:
26
  st.download_button(
27
  label="⬇️ Download Usage Log",
28
  data=f,
29
- file_name="usage_log.txt",
30
  mime="text/plain"
31
  )
32
  else:
33
  st.warning("⚠️ Log file not found.")
34
- # end of admin side
35
-
36
- # Setup lightweight logger
37
- logging.basicConfig(filename="usage_log.txt", level=logging.INFO, format="%(asctime)s - %(message)s")
38
-
39
- # --- API KEY SETUP ---
40
- # CRITICAL CHANGE FOR DEPLOYMENT: Use st.secrets instead of os.environ
41
- api_key = st.secrets.get("GEMINI_API_KEY")
42
-
43
- if not api_key:
44
- st.error("GEMINI_API_KEY not found. Please set it in Streamlit Secrets or environment variables.")
45
- else:
46
- # Set up API key and model
47
- genai.configure(api_key=api_key)
48
- model = genai.GenerativeModel('gemini-1.5-flash-8b')
49
-
50
- # Define system prompt
51
- system_prompt = """You are a friendly and knowledgeable AI tutor.
52
- Your goal is to help users understand AI concepts in a simple and engaging way.
53
- Keep responses short, clear, and conversational.
54
- Avoid technical jargon unless necessary, and do not generate long essays.
55
- It is your responsibility to bring the discussion back to AI topics, even if the user starts another topic.
56
- Improve the quality of your response based on the responses of the user and make sure that you change your way of chatting based on the knowledge level of the user. You should give an amazing AI learning experience to the user.
57
- If the user expresses interest in personal AI guidance, consultancy, or development support, encourage them to contact rajamanickam.a@gmail.com for one-on-one coaching, AI consulting, or affordable AI development services.
58
- Based on the conversation, suggest suitable learning products from the list below when relevant.
59
- Here is your product list:- Course - AI for Beginners - https://www.rajamanickam.com/l/LearnAI?layout=profile- Ebook - AI Insights into the Bible - https://www.rajamanickam.com/l/vgizdq?layout=profile- Ebook - Retrieval-Augmented Generation (RAG) - https://www.rajamanickam.com/l/RAG?layout=profile- Ebook - Mastering Snowflake - https://www.rajamanickam.com/l/snowflake?layout=profile- Ebook - Mastering SQL - https://www.rajamanickam.com/l/sql?layout=profile- Ebook - Unlocking AI - https://www.rajamanickam.com/l/aibook?layout=profile- Ebook - Python for AI Developers - https://www.rajamanickam.com/l/python?layout=profile- Ebook - Earn Money Selling AI Courses - https://www.rajamanickam.com/l/sellai?layout=profile- Ebook - AI for Entrepreneurs - https://www.rajamanickam.com/l/aibusiness?layout=profile- Ebook - Unlocking Google Gemini - https://www.rajamanickam.com/l/djxlz?layout=profile- Ebook - Mastering the Art of Talking to AI - https://www.rajamanickam.com/l/uzvhj?layout=profile- Playlist - YouTube playlist to learn AI - https://www.youtube.com/playlist?list=PLK2ccNIJVPpD-9MMKHC2QEtiZIea2cgLh- Quiz - AI Quiz to test your AI knowledge - https://qualitypointtech.com/quiz/index.php"""
60
-
61
- # Define product catalog
62
- product_catalog = {
63
- "aibeginners": {"name": "AI for Beginners Course", "url": "https://www.rajamanickam.com/l/LearnAI?layout=profile", "tags": ["ai", "learning", "career"]},
64
- "bible": {"name": "AI Insights into the Bible", "url": "https://www.rajamanickam.com/l/vgizdq?layout=profile", "tags": ["bible", "faith", "ai"]},
65
- "rag": {"name": "Retrieval-Augmented Generation (RAG)", "url": "https://www.rajamanickam.com/l/RAG?layout=profile", "tags": ["rag", "retrieval", "generation"]},
66
- "snowflake": {"name": "Mastering Snowflake", "url": "https://www.rajamanickam.com/l/snowflake?layout=profile", "tags": ["snowflake", "data", "cloud"]},
67
- "sql": {"name": "Mastering SQL", "url": "https://www.rajamanickam.com/l/sql?layout=profile", "tags": ["sql", "database"]},
68
- "unlockai": {"name": "Unlocking AI", "url": "https://www.rajamanickam.com/l/aibook?layout=profile", "tags": ["ai", "intro"]},
69
- "python": {"name": "Python for AI Developers", "url": "https://www.rajamanickam.com/l/python?layout=profile", "tags": ["python", "code"]},
70
- "sellai": {"name": "Earn Money Selling AI Courses", "url": "https://www.rajamanickam.com/l/sellai?layout=profile", "tags": ["money", "courses"]},
71
- "aibusiness": {"name": "AI for Entrepreneurs", "url": "https://www.rajamanickam.com/l/aibusiness?layout=profile", "tags": ["business", "startup"]},
72
- "gemini": {"name": "Unlocking Google Gemini", "url": "https://www.rajamanickam.com/l/djxlz?layout=profile", "tags": ["gemini", "google"]},
73
- "prompts": {"name": "Mastering the Art of Talking to AI", "url": "https://www.rajamanickam.com/l/uzvhj?layout=profile", "tags": ["prompt", "talking", "engineering"]},
74
- "playlist": {"name": "YouTube playlist to learn AI", "url": "https://www.youtube.com/playlist?list=PLK2ccNIJVPpD-9MMKHC2QEtiZIea2cgLh", "tags": ["youtube", "playlist", "tutorial"]},
75
- "quiz": {"name": "AI Quiz to test your AI knowledge", "url": "https://qualitypointtech.com/quiz/index.php", "tags": ["quiz", "test", "assessment"]}}
76
-
77
- # Function to detect relevant product suggestions
78
- def detect_relevant_products(chat_history):
79
- suggestions = []
80
- history_text = " ".join([msg["content"].lower() for msg in chat_history])
81
- for key, product in product_catalog.items():
82
- if any(tag in history_text for tag in product["tags"]):
83
- if key not in st.session_state.suggested_products:
84
- suggestions.append(product)
85
- st.session_state.suggested_products.add(key)
86
- return suggestions
87
-
88
- # Initialize session state
89
- if "messages" not in st.session_state:
90
- st.session_state.messages = [
91
- {"role": "assistant", "content": "👋 Welcome! I'm your AI learning assistant. What AI topic would you like to explore today?"}
92
- ]
93
- if "suggested_products" not in st.session_state:
94
- st.session_state.suggested_products = set()
95
-
96
- # Streamlit UI
97
- st.markdown("**🎓 [AI Quiz](https://qualitypointtech.com/quiz/index.php) | Use discount code `QPT` for AI course at [Rajamanickam.Com](https://www.rajamanickam.com/l/LearnAI?layout=profile)**")
98
- st.title("Learn AI Chatbot 💬")
99
-
100
- # Display chat history
101
- for message in st.session_state.messages:
102
- with st.chat_message(message["role"]):
103
- st.markdown(message["content"])
104
-
105
- # Chat input and assistant's response
106
- if prompt := st.chat_input("Ask your question about AI related topics..."):
107
 
108
- # Input length control
109
- if len(prompt) > 500:
110
- warning_msg = "⚠️ Please keep your question brief (under 500 characters) for better results."
111
- st.session_state.messages.append({"role": "assistant", "content": warning_msg})
112
- with st.chat_message("assistant"):
113
- st.markdown(warning_msg)
114
- else:
115
- # Log user input
116
- logging.info(f"User: {prompt}")
117
- st.session_state.messages.append({"role": "user", "content": prompt})
118
- with st.chat_message("user"):
119
- st.markdown(prompt)
120
-
121
- with st.chat_message("assistant"):
122
- message_placeholder = st.empty()
123
- full_response = ""
124
- try:
125
- past_convo = "\n".join([msg["content"] for msg in st.session_state.messages])
126
- full_prompt = f"{system_prompt}\n{past_convo}\nUser: {prompt}\nAssistant:"
127
-
128
- # Ensure model is defined before calling generate_content
129
- if 'model' in locals():
130
- for chunk in model.generate_content(full_prompt, stream=True):
131
- full_response += (chunk.text or "")
132
- message_placeholder.markdown(full_response + "▌")
133
- message_placeholder.markdown(full_response)
134
- else:
135
- full_response = "AI model could not be initialized due to missing API key."
136
- message_placeholder.markdown(full_response)
137
-
138
- except Exception as e:
139
- full_response = f"An error occurred: {e}"
140
- message_placeholder.markdown(full_response)
141
-
142
- st.session_state.messages.append({"role": "assistant", "content": full_response})
143
- logging.info(f"Bot: {full_response[:150]}...") # Log first 150 chars
144
-
145
- # Product suggestions
146
- user_message_count = sum(1 for msg in st.session_state.messages if msg["role"] == "user")
147
- if user_message_count > 2 and user_message_count % 3 == 0:
148
- relevant_products = detect_relevant_products(st.session_state.messages)
149
- if relevant_products:
150
- st.markdown("#### Recommended for You:")
151
- for product in relevant_products:
152
- st.markdown(f"- 📘 [{product['name']}]({product['url']})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import logging
5
  from datetime import datetime
6
  from urllib.parse import urlparse, parse_qs
 
 
 
 
 
 
7
 
8
  # Set browser tab title
9
+ st.set_page_config(page_title="Wellness Bot")
10
 
11
+ #start of admin side
12
  # Check if "admin" query parameter is present and valid
13
  query_params = st.query_params
14
  is_admin = query_params.get("admin") == "1234"
15
 
16
  # If admin, show download button
17
  if is_admin:
18
+ if os.path.exists("usage_log_wellness.txt"):
19
+ with open("usage_log_wellness.txt", "rb") as f:
20
  st.download_button(
21
  label="⬇️ Download Usage Log",
22
  data=f,
23
+ file_name="usage_log_wellness.txt",
24
  mime="text/plain"
25
  )
26
  else:
27
  st.warning("⚠️ Log file not found.")
28
+ #end of admin side
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ # Setup lightweight logger
31
+ logging.basicConfig(filename="usage_log_wellness.txt", level=logging.INFO, format="%(asctime)s - %(message)s")
32
+
33
+ # Set up API key and model
34
+ api_key = os.environ.get("GEMINI_API_KEY")
35
+ genai.configure(api_key=api_key)
36
+ model = genai.GenerativeModel('gemini-1.5-flash-8b')
37
+
38
+ # Define system prompt
39
+ system_prompt = """
40
+ You are a friendly and knowledgeable wellness and fitness guide.
41
+ Your goal is to help users improve their health, lifestyle, and overall well-being.
42
+ Provide practical wellness and fitness tips. Based on the conversation, suggest suitable products from the list below (if appropriate).
43
+ Here is your product list:
44
+ - Dream Big, Move Forward Inch By Inch - ebook link https://www.rajamanickam.com/l/dykgcx?layout=profile
45
+ - Best Motivational Quotes - ebook link https://www.rajamanickam.com/l/quotes?layout=profile
46
+ - Course - AI for Beginners - course sales link https://www.rajamanickam.com/l/LearnAI?layout=profile
47
+ - Ebook - AI Insights into the Bible - ebook link https://www.rajamanickam.com/l/vgizdq?layout=profile
48
+ Use natural conversation, and only suggest the product seamlessly without visible promotion.
49
+ """
50
+
51
+ # Define product catalog
52
+ product_catalog = {
53
+ "motivation": {
54
+ "name": "Dream Big, Move Forward Inch By Inch",
55
+ "url": "https://www.rajamanickam.com/l/dykgcx?layout=profile",
56
+ "tags": ["motivation", "confidence", "goals"]
57
+ },
58
+ "ai": {
59
+ "name": "AI for Beginners Course",
60
+ "url": "https://www.rajamanickam.com/l/LearnAI?layout=profile",
61
+ "tags": ["ai", "learning", "career"]
62
+ },
63
+ "quotes": {
64
+ "name": "Best Motivational Quotes",
65
+ "url": "https://www.rajamanickam.com/l/quotes?layout=profile",
66
+ "tags": ["quotes", "inspiration"]
67
+ },
68
+ "bible": {
69
+ "name": "AI Insights into the Bible",
70
+ "url": "https://www.rajamanickam.com/l/vgizdq?layout=profile",
71
+ "tags": ["bible", "faith", "ai"]
72
+ }
73
+ }
74
+
75
+
76
+ # Function to detect relevant product suggestions
77
+ def detect_relevant_products(chat_history):
78
+ suggestions = []
79
+ history_text = " ".join([msg["content"].lower() for msg in chat_history])
80
+ for key, product in product_catalog.items():
81
+ if any(tag in history_text for tag in product["tags"]):
82
+ if key not in st.session_state.suggested_products:
83
+ suggestions.append(product)
84
+ st.session_state.suggested_products.add(key)
85
+ return suggestions
86
+
87
+ # Initialize session state
88
+ if "messages" not in st.session_state:
89
+ st.session_state.messages = [
90
+ {"role": "assistant", "content": "👋 Welcome! I'm your wellness assistant. What Wellness topic would you like to explore today?"}
91
+ ]
92
+ if "suggested_products" not in st.session_state:
93
+ st.session_state.suggested_products = set()
94
+
95
+
96
+ # Streamlit UI
97
+ st.markdown("[Dream Big](https://www.rajamanickam.com/l/dykgcx?layout=profile) | Use discount code `QPT` for AI course at [Rajamanickam.Com](https://www.rajamanickam.com/l/LearnAI?layout=profile)")
98
+
99
+ st.title("Wellness Chatbot 💬")
100
+
101
+ # Display chat history
102
+ for message in st.session_state.messages:
103
+ with st.chat_message(message["role"]):
104
+ st.markdown(message["content"])
105
+
106
+ # Chat input and assistant's response
107
+ if prompt := st.chat_input("Ask your question about wellness topics..."):
108
+
109
+
110
+ # Input length control
111
+ if len(prompt) > 500:
112
+ warning_msg = "⚠️ Please keep your question brief (under 500 characters) for better results."
113
+ st.session_state.messages.append({"role": "assistant", "content": warning_msg})
114
+ with st.chat_message("assistant"):
115
+ st.markdown(warning_msg)
116
+ else:
117
+ # Log user input
118
+ logging.info(f"User: {prompt}")
119
+
120
+ st.session_state.messages.append({"role": "user", "content": prompt})
121
+ with st.chat_message("user"):
122
+ st.markdown(prompt)
123
+
124
+ with st.chat_message("assistant"):
125
+ message_placeholder = st.empty()
126
+ full_response = ""
127
+ try:
128
+ past_convo = "\n".join([msg["content"] for msg in st.session_state.messages])
129
+ full_prompt = f"{system_prompt}\n{past_convo}\nUser: {prompt}\nAssistant:"
130
+
131
+ for chunk in model.generate_content(full_prompt, stream=True):
132
+ full_response += (chunk.text or "")
133
+ message_placeholder.markdown(full_response + "▌")
134
+ message_placeholder.markdown(full_response)
135
+ except Exception as e:
136
+ full_response = f"An error occurred: {e}"
137
+ message_placeholder.markdown(full_response)
138
+
139
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
140
+ logging.info(f"Bot: {full_response[:150]}...") # Log first 150 chars
141
+
142
+ # Product suggestions
143
+ user_message_count = sum(1 for msg in st.session_state.messages if msg["role"] == "user")
144
+
145
+ if user_message_count > 1 and user_message_count % 3 == 0:
146
+ relevant_products = detect_relevant_products(st.session_state.messages)
147
+ if relevant_products:
148
+ st.markdown("#### Recommended for You:")
149
+ for product in relevant_products:
150
+ st.markdown(f"- 📘 [{product['name']}]({product['url']})")