sheetal-chatbot / app.py
shee2205's picture
Update app.py
abf5905 verified
raw
history blame
4.1 kB
import gradio as gr
import json
import os
from datetime import date
from transformers import pipeline
PROFILE_FILE = "about_me.json"
DAILY_FILE = "daily_status.json"
def load_json(path, default):
if os.path.exists(path):
with open(path) as f:
return json.load(f)
return default
profile = load_json(PROFILE_FILE, {})
daily = load_json(DAILY_FILE, {})
def build_context(profile, daily):
recent_days = sorted(daily.keys(), reverse=True)[:7]
daily_lines = "\n".join([f"{d}: {daily[d].get('log','')}" for d in recent_days])
context = (
f"Profile:\n{json.dumps(profile, indent=2)}\n"
f"Recent daily logs:\n{daily_lines}\n"
"You are a helpful assistant. Answer only using the provided information. "
"If you don't know the answer, reply: 'Sheetal hasn't shared that yet!'"
)
return context
def get_llm():
return pipeline(
"text-generation",
model="google/flan-t5-small",
max_new_tokens=128,
do_sample=True,
temperature=0.7,
)
llm = None
def chatbot_qa(user_q):
global llm
if llm is None:
llm = get_llm()
context = build_context(profile, daily)
prompt = f"System: {context}\nUser: {user_q}\nAssistant:"
outputs = llm(prompt, max_new_tokens=128)
answer = outputs[0]["generated_text"].split("Assistant:")[-1].strip()
return answer
def save_profile_and_log(name, city, job, about, freeform):
today = str(date.today())
profile.update({
"name": name,
"city": city,
"job": job,
"about": about
})
save_json(PROFILE_FILE, profile)
daily[today] = {"log": freeform}
save_json(DAILY_FILE, daily)
logs = ""
for d in sorted(daily.keys(), reverse=True)[:5]:
logs += f"**{d}**: {daily[d]['log']}\n"
return (
"βœ… Profile & log updated!",
logs
)
def recent_logs():
logs = ""
for d in sorted(daily.keys(), reverse=True)[:5]:
logs += f"**{d}**: {daily[d]['log']}\n"
return logs
SECRET_CODE = "1234" # Change this to your secret
def build_ui(request: gr.Request):
# Check for secret in URL, e.g., ?admin=1234
query_params = dict(request.query_params)
show_admin = query_params.get("admin", [None])[0] == SECRET_CODE
with gr.Blocks(title="Sheetal's Chatbot") as demo:
gr.Markdown("# 🌸 Sheetal's Personal Chatbot")
gr.Markdown("Ask anything about Sheetal!")
if show_admin:
with gr.Tab("πŸ“ Admin (Sheetal)"):
with gr.Row():
name = gr.Textbox(label="Name", value=profile.get("name", "Sheetal"), max_lines=1)
city = gr.Textbox(label="City", value=profile.get("city", ""), max_lines=1)
job = gr.Textbox(label="Profession", value=profile.get("job", ""), max_lines=1)
about = gr.Textbox(label="About You", value=profile.get("about", ""), lines=2, max_lines=3)
today_log = gr.Textbox(label="What do you want to remember about today?", value=daily.get(str(date.today()), {}).get("log", ""), lines=2, max_lines=3)
save_btn = gr.Button("πŸ’Ύ Save Profile & Today's Log")
admin_status = gr.Markdown("")
logs_output = gr.Markdown(recent_logs())
save_btn.click(
fn=save_profile_and_log,
inputs=[name, city, job, about, today_log],
outputs=[admin_status, logs_output]
)
with gr.Tab("πŸ’¬ Ask About Sheetal"):
user_q = gr.Textbox(label="Type your question here:")
ask_btn = gr.Button("Ask")
answer_box = gr.Textbox(label="Bot answer", interactive=False, lines=2, max_lines=4)
ask_btn.click(
fn=chatbot_qa,
inputs=user_q,
outputs=answer_box
)
return demo
gr.mount_gradio_app(app=build_ui, path="/", root_path="")
# For Hugging Face Spaces, use this launch line:
demo = build_ui
if __name__ == "__main__":
demo.launch()