Repository navigation
Expand file tree
/
Copy pathComputerScience.py
More file actions
228 lines (193 loc) Β· 9.94 KB
/
Copy pathComputerScience.py
File metadata and controls
228 lines (193 loc) Β· 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import streamlit as st
import anthropic
import base64
import io
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
# ββ Page config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.set_page_config(page_title="AI Chatbot", page_icon="π€")
st.title("π€ AI Chatbot")
st.caption("Powered by Claude")
# ββ API client ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
API_KEY = st.secrets["ANTHROPIC_API_KEY"]
except Exception:
st.error("β οΈ API key not found. Go to Manage App β Settings β Secrets and add your ANTHROPIC_API_KEY.")
st.stop()
client = anthropic.Anthropic(api_key=API_KEY)
# ββ PDF export helper βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def generate_pdf(messages):
buffer = io.BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=letter,
rightMargin=50, leftMargin=50,
topMargin=60, bottomMargin=40)
styles = getSampleStyleSheet()
title_style = ParagraphStyle("Title", parent=styles["Title"],
textColor=colors.HexColor("#1a1a2e"), fontSize=20)
user_style = ParagraphStyle("User", parent=styles["Normal"],
textColor=colors.HexColor("#0f3460"),
fontSize=11, spaceAfter=4,
fontName="Helvetica-Bold")
bot_style = ParagraphStyle("Bot", parent=styles["Normal"],
textColor=colors.HexColor("#16213e"),
fontSize=11, spaceAfter=4)
meta_style = ParagraphStyle("Meta", parent=styles["Normal"],
textColor=colors.grey, fontSize=8)
story = []
story.append(Paragraph("π€ AI Chatbot β Conversation Export", title_style))
story.append(Paragraph(f"Exported on {datetime.now().strftime('%Y-%m-%d %H:%M')}", meta_style))
story.append(Spacer(1, 20))
for msg in messages:
if isinstance(msg["content"], list):
text = next((b["text"] for b in msg["content"] if b.get("type") == "text"), "[image]")
else:
text = msg["content"]
# Escape special XML chars for ReportLab
text = text.replace("&", "&").replace("<", "<").replace(">", ">")
if msg["role"] == "user":
story.append(Paragraph("You:", user_style))
story.append(Paragraph(text, bot_style))
else:
story.append(Paragraph("Claude:", user_style))
story.append(Paragraph(text, bot_style))
story.append(Spacer(1, 10))
doc.build(story)
buffer.seek(0)
return buffer.read()
# ββ Sidebar settings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with st.sidebar:
st.header("βοΈ Settings")
# Persona selector
persona = st.selectbox(
"Chatbot Persona",
["General Assistant", "CS Tutor", "Creative Writer", "Joke Bot", "βοΈ Custom"]
)
PERSONAS = {
"General Assistant": "You are a helpful and friendly assistant.",
"CS Tutor": "You are a computer science tutor. Explain concepts clearly and simply, using analogies and short code examples where helpful.",
"Creative Writer": "You are a creative writing assistant. Help the user craft vivid, imaginative stories and ideas.",
"Joke Bot": "You are a comedian. Respond to everything with wit and humour, and include a relevant joke when appropriate.",
}
if persona == "βοΈ Custom":
custom_prompt = st.text_area(
"Write your own system prompt:",
placeholder='e.g. "You are a pirate who only speaks in rhymes."',
height=120,
)
base_system_prompt = custom_prompt if custom_prompt.strip() else "You are a helpful assistant."
if not custom_prompt.strip():
st.caption("βΉοΈ Using default prompt until you write one above.")
else:
base_system_prompt = PERSONAS[persona]
st.divider()
# Language selector
st.subheader("π Response Language")
language = st.selectbox(
"Reply in:",
["English", "Spanish", "French", "German", "Italian",
"Portuguese", "Japanese", "Chinese", "Arabic", "Hindi"]
)
system_prompt = base_system_prompt if language == "English" else \
base_system_prompt + f" Always respond in {language}, regardless of what language the user writes in."
st.divider()
# Image upload
st.subheader("πΌοΈ Image Upload")
uploaded_image = st.file_uploader(
"Attach an image to your next message:",
type=["png", "jpg", "jpeg", "gif", "webp"],
)
if uploaded_image:
st.image(uploaded_image, caption="Image ready to send", use_container_width=True)
st.divider()
# ββ PDF Export button βββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.subheader("π Export Chat")
if st.session_state.get("messages"):
pdf_bytes = generate_pdf(st.session_state.messages)
st.download_button(
label="β¬οΈ Download as PDF",
data=pdf_bytes,
file_name=f"chat_export_{datetime.now().strftime('%Y%m%d_%H%M')}.pdf",
mime="application/pdf",
)
else:
st.caption("Start chatting to enable PDF export.")
st.divider()
if st.button("ποΈ Clear Chat"):
st.session_state.messages = []
st.rerun()
# ββ Session state βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if "messages" not in st.session_state:
st.session_state.messages = []
# ββ Text-to-speech helper βββββββββββββββββββββββββββββββββββββββββββββββββββββ
def tts_button(text, key):
"""Renders a speak button using browser Web Speech API via an HTML component."""
safe_text = text.replace("`", "").replace('"', """).replace("\n", " ")
st.components.v1.html(f"""
<button onclick="
var u = new SpeechSynthesisUtterance('{safe_text}');
window.speechSynthesis.speak(u);
" style="
background:#f0f2f6; border:1px solid #ccc; border-radius:6px;
padding:4px 10px; cursor:pointer; font-size:13px;
">π Read aloud</button>
""", height=40)
# ββ Display existing messages βββββββββββββββββββββββββββββββββββββββββββββββββ
for i, msg in enumerate(st.session_state.messages):
with st.chat_message(msg["role"]):
if isinstance(msg["content"], list):
for block in msg["content"]:
if block.get("type") == "text":
st.markdown(block["text"])
st.caption("π Image was attached to this message")
else:
st.markdown(msg["content"])
# TTS button on assistant messages
if msg["role"] == "assistant":
tts_button(msg["content"], key=f"tts_{i}")
# ββ Handle new user input βββββββββββββββββββββββββββββββββββββββββββββββββββββ
if prompt := st.chat_input("Type a message..."):
if uploaded_image:
image_bytes = uploaded_image.read()
image_b64 = base64.standard_b64encode(image_bytes).decode("utf-8")
message_content = [
{"type": "image", "source": {"type": "base64",
"media_type": uploaded_image.type, "data": image_b64}},
{"type": "text", "text": prompt},
]
else:
message_content = prompt
st.session_state.messages.append({"role": "user", "content": message_content})
with st.chat_message("user"):
st.markdown(prompt)
if uploaded_image:
st.caption("π Image attached")
# Streaming response
with st.chat_message("assistant"):
response_placeholder = st.empty()
full_reply = ""
try:
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1000,
system=system_prompt,
messages=st.session_state.messages,
) as stream:
for text_chunk in stream.text_stream:
full_reply += text_chunk
response_placeholder.markdown(full_reply + "β")
response_placeholder.markdown(full_reply)
except anthropic.AuthenticationError:
full_reply = "β οΈ Invalid API key. Please check your Streamlit Secrets."
response_placeholder.markdown(full_reply)
except anthropic.RateLimitError:
full_reply = "β οΈ Rate limit hit. Please wait a moment and try again."
response_placeholder.markdown(full_reply)
except Exception as e:
full_reply = f"β οΈ Unexpected error: {e}"
response_placeholder.markdown(full_reply)
# TTS button for the new response
tts_button(full_reply, key=f"tts_new")
st.session_state.messages.append({"role": "assistant", "content": full_reply})