Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,9 +3,13 @@ import json
|
|
3 |
import os
|
4 |
from datetime import date
|
5 |
from transformers import pipeline
|
|
|
|
|
|
|
6 |
|
7 |
PROFILE_FILE = "about_me.json"
|
8 |
DAILY_FILE = "daily_status.json"
|
|
|
9 |
|
10 |
def load_json(path, default):
|
11 |
if os.path.exists(path):
|
@@ -17,11 +21,45 @@ def save_json(path, data):
|
|
17 |
with open(path, "w") as f:
|
18 |
json.dump(data, f, indent=2)
|
19 |
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
def build_context(profile, daily):
|
24 |
-
# Combine profile info and last 7 days logs
|
25 |
context = []
|
26 |
for k, v in profile.items():
|
27 |
context.append(f"{k.capitalize()}: {v}")
|
@@ -29,7 +67,6 @@ def build_context(profile, daily):
|
|
29 |
context.append(f"On {d}: {daily[d].get('log','')}")
|
30 |
return "\n".join(context)
|
31 |
|
32 |
-
# QA Pipeline - loads once and is reused
|
33 |
qa_pipeline = pipeline("question-answering", model="deepset/roberta-base-squad2")
|
34 |
|
35 |
def chatbot_qa(user_q):
|
@@ -38,7 +75,7 @@ def chatbot_qa(user_q):
|
|
38 |
result = qa_pipeline(question=user_q, context=context)
|
39 |
answer = result["answer"].strip()
|
40 |
if not answer or answer.lower() in ["empty", ""]:
|
41 |
-
return "
|
42 |
return answer
|
43 |
except Exception as e:
|
44 |
return f"Error: {e}"
|
@@ -54,11 +91,13 @@ def save_profile_and_log(name, city, job, about, freeform):
|
|
54 |
save_json(PROFILE_FILE, profile)
|
55 |
daily[today] = {"log": freeform}
|
56 |
save_json(DAILY_FILE, daily)
|
|
|
|
|
57 |
logs = ""
|
58 |
for d in sorted(daily.keys(), reverse=True)[:5]:
|
59 |
logs += f"**{d}**: {daily[d]['log']}\n"
|
60 |
return (
|
61 |
-
"✅ Profile & log updated!",
|
62 |
logs
|
63 |
)
|
64 |
|
@@ -80,87 +119,50 @@ def show_profile():
|
|
80 |
return json.dumps(profile, indent=2), json.dumps(daily, indent=2)
|
81 |
|
82 |
with gr.Blocks(title="Sheetal's Chatbot") as demo:
|
83 |
-
|
84 |
-
|
85 |
-
"<h1 style='text-align:center; color:#AC3B61;'>🌸 Sheetal's Personal Chatbot 🌸</h1>"
|
86 |
-
"<div style='text-align:center;'>Ask anything about Sheetal!<br>Made with ❤️ on Hugging Face Spaces.</div>"
|
87 |
-
)
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
placeholder="e.g., Who cooked for Sheetal today?",
|
94 |
-
lines=1,
|
95 |
-
scale=6
|
96 |
-
)
|
97 |
-
ask_btn = gr.Button("🔍 Ask", scale=1)
|
98 |
-
answer_box = gr.Textbox(
|
99 |
-
label="🤖 Chatbot Answer",
|
100 |
-
interactive=False,
|
101 |
-
lines=3,
|
102 |
-
max_lines=5,
|
103 |
-
elem_id="answer_box"
|
104 |
-
)
|
105 |
-
gr.Markdown(
|
106 |
-
"<div style='font-size:13px; color:gray;'>"
|
107 |
-
"Tip: The bot only knows what Sheetal has shared in her profile or daily logs.</div>"
|
108 |
-
)
|
109 |
-
ask_btn.click(
|
110 |
-
fn=chatbot_qa,
|
111 |
-
inputs=user_q,
|
112 |
-
outputs=answer_box
|
113 |
-
)
|
114 |
|
115 |
-
with gr.
|
116 |
with gr.Row():
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
name = gr.Textbox(label="Name", value=profile.get("name", "Sheetal"))
|
130 |
-
city = gr.Textbox(label="City", value=profile.get("city", ""))
|
131 |
-
with gr.Row():
|
132 |
-
job = gr.Textbox(label="Profession", value=profile.get("job", ""))
|
133 |
-
about = gr.Textbox(label="About You", value=profile.get("about", ""), lines=2, max_lines=3)
|
134 |
-
today_log = gr.Textbox(label="Daily Note", value=daily.get(str(date.today()), {}).get("log", ""), lines=2, max_lines=4)
|
135 |
-
with gr.Row():
|
136 |
-
save_btn = gr.Button("💾 Save Profile & Today's Log", scale=2)
|
137 |
-
show_btn = gr.Button("📂 Show Current Data", scale=1)
|
138 |
-
admin_status = gr.Markdown()
|
139 |
-
logs_output = gr.Markdown(f"<b>Recent logs:</b>\n{recent_logs()}")
|
140 |
-
profile_out = gr.Textbox(label="Profile JSON", visible=False)
|
141 |
-
daily_out = gr.Textbox(label="Daily Logs JSON", visible=False)
|
142 |
-
|
143 |
-
save_btn.click(
|
144 |
-
fn=save_profile_and_log,
|
145 |
-
inputs=[name, city, job, about, today_log],
|
146 |
-
outputs=[admin_status, logs_output]
|
147 |
-
)
|
148 |
-
show_btn.click(fn=show_profile, outputs=[profile_out, daily_out])
|
149 |
-
|
150 |
-
unlock_panel.click(
|
151 |
-
fn=check_password,
|
152 |
-
inputs=[admin_password],
|
153 |
-
outputs=[admin_panel, password_status]
|
154 |
)
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
165 |
if __name__ == "__main__":
|
166 |
demo.launch()
|
|
|
3 |
import os
|
4 |
from datetime import date
|
5 |
from transformers import pipeline
|
6 |
+
from datasets import load_dataset, Dataset, DatasetDict
|
7 |
+
import huggingface_hub
|
8 |
+
import tempfile
|
9 |
|
10 |
PROFILE_FILE = "about_me.json"
|
11 |
DAILY_FILE = "daily_status.json"
|
12 |
+
HF_DATASET_REPO = "shee2205/bot-data" # CHANGE THIS TO YOUR REPO!
|
13 |
|
14 |
def load_json(path, default):
|
15 |
if os.path.exists(path):
|
|
|
21 |
with open(path, "w") as f:
|
22 |
json.dump(data, f, indent=2)
|
23 |
|
24 |
+
# --- Hugging Face Datasets methods ---
|
25 |
+
def hf_login():
|
26 |
+
# Reads from HF_TOKEN (Spaces env var)
|
27 |
+
token = os.environ.get("HF_TOKEN")
|
28 |
+
huggingface_hub.login(token)
|
29 |
+
|
30 |
+
def hf_load():
|
31 |
+
try:
|
32 |
+
ds = load_dataset(HF_DATASET_REPO, split="train")
|
33 |
+
# Should be 1 row: {profile:..., daily:...}
|
34 |
+
row = ds[0]
|
35 |
+
return json.loads(row["profile"]), json.loads(row["daily"])
|
36 |
+
except Exception as e:
|
37 |
+
print("No HF data found, using empty. Reason:", e)
|
38 |
+
return {}, {}
|
39 |
+
|
40 |
+
def hf_save(profile, daily):
|
41 |
+
# Save current data as a single row
|
42 |
+
# (delete all, upload new version)
|
43 |
+
data = {
|
44 |
+
"profile": [json.dumps(profile)],
|
45 |
+
"daily": [json.dumps(daily)],
|
46 |
+
}
|
47 |
+
# Save locally to a tmp dir for upload
|
48 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
49 |
+
path = os.path.join(tmpdirname, "data.jsonl")
|
50 |
+
with open(path, "w") as f:
|
51 |
+
for i in range(1):
|
52 |
+
f.write(json.dumps({ "profile": data["profile"][i], "daily": data["daily"][i] }) + "\n")
|
53 |
+
ds = Dataset.from_json(path)
|
54 |
+
ds.push_to_hub(HF_DATASET_REPO, private=True, split="train", token=os.environ.get("HF_TOKEN"))
|
55 |
+
|
56 |
+
# --- Load from HF Dataset on startup ---
|
57 |
+
hf_login()
|
58 |
+
profile, daily = hf_load()
|
59 |
+
save_json(PROFILE_FILE, profile)
|
60 |
+
save_json(DAILY_FILE, daily)
|
61 |
|
62 |
def build_context(profile, daily):
|
|
|
63 |
context = []
|
64 |
for k, v in profile.items():
|
65 |
context.append(f"{k.capitalize()}: {v}")
|
|
|
67 |
context.append(f"On {d}: {daily[d].get('log','')}")
|
68 |
return "\n".join(context)
|
69 |
|
|
|
70 |
qa_pipeline = pipeline("question-answering", model="deepset/roberta-base-squad2")
|
71 |
|
72 |
def chatbot_qa(user_q):
|
|
|
75 |
result = qa_pipeline(question=user_q, context=context)
|
76 |
answer = result["answer"].strip()
|
77 |
if not answer or answer.lower() in ["empty", ""]:
|
78 |
+
return "Sheetal hasn't shared that yet!"
|
79 |
return answer
|
80 |
except Exception as e:
|
81 |
return f"Error: {e}"
|
|
|
91 |
save_json(PROFILE_FILE, profile)
|
92 |
daily[today] = {"log": freeform}
|
93 |
save_json(DAILY_FILE, daily)
|
94 |
+
# Save to HF dataset as well
|
95 |
+
hf_save(profile, daily)
|
96 |
logs = ""
|
97 |
for d in sorted(daily.keys(), reverse=True)[:5]:
|
98 |
logs += f"**{d}**: {daily[d]['log']}\n"
|
99 |
return (
|
100 |
+
"✅ Profile & log updated (saved to cloud)!",
|
101 |
logs
|
102 |
)
|
103 |
|
|
|
119 |
return json.dumps(profile, indent=2), json.dumps(daily, indent=2)
|
120 |
|
121 |
with gr.Blocks(title="Sheetal's Chatbot") as demo:
|
122 |
+
gr.Markdown("# 🌸 Sheetal's Personal Chatbot")
|
123 |
+
gr.Markdown("Ask anything about Sheetal!")
|
|
|
|
|
|
|
124 |
|
125 |
+
with gr.Tab("📝 Admin (Sheetal)"):
|
126 |
+
admin_password = gr.Textbox(label="Enter admin password", type="password", max_lines=1)
|
127 |
+
unlock_panel = gr.Button("Unlock Admin Panel")
|
128 |
+
password_status = gr.Textbox(label="Password status", value="", interactive=False, visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
|
130 |
+
with gr.Column(visible=False) as admin_panel:
|
131 |
with gr.Row():
|
132 |
+
name = gr.Textbox(label="Name", value=profile.get("name", "Sheetal"), max_lines=1)
|
133 |
+
city = gr.Textbox(label="City", value=profile.get("city", ""), max_lines=1)
|
134 |
+
job = gr.Textbox(label="Profession", value=profile.get("job", ""), max_lines=1)
|
135 |
+
about = gr.Textbox(label="About You", value=profile.get("about", ""), lines=2, max_lines=3)
|
136 |
+
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)
|
137 |
+
save_btn = gr.Button("💾 Save Profile & Today's Log")
|
138 |
+
admin_status = gr.Markdown("")
|
139 |
+
logs_output = gr.Markdown(recent_logs())
|
140 |
+
save_btn.click(
|
141 |
+
fn=save_profile_and_log,
|
142 |
+
inputs=[name, city, job, about, today_log],
|
143 |
+
outputs=[admin_status, logs_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
)
|
145 |
+
# Debug: show current data
|
146 |
+
show_btn = gr.Button("Show Current Data")
|
147 |
+
profile_out = gr.Textbox(label="Profile JSON")
|
148 |
+
daily_out = gr.Textbox(label="Daily JSON")
|
149 |
+
show_btn.click(fn=show_profile, outputs=[profile_out, daily_out])
|
150 |
+
|
151 |
+
unlock_panel.click(
|
152 |
+
fn=check_password,
|
153 |
+
inputs=[admin_password],
|
154 |
+
outputs=[admin_panel, password_status]
|
155 |
+
)
|
156 |
+
|
157 |
+
with gr.Tab("💬 Ask About Sheetal"):
|
158 |
+
user_q = gr.Textbox(label="Type your question here:")
|
159 |
+
ask_btn = gr.Button("Ask")
|
160 |
+
answer_box = gr.Textbox(label="Bot answer", interactive=False, lines=2, max_lines=4)
|
161 |
+
ask_btn.click(
|
162 |
+
fn=chatbot_qa,
|
163 |
+
inputs=user_q,
|
164 |
+
outputs=answer_box
|
165 |
+
)
|
166 |
|
167 |
if __name__ == "__main__":
|
168 |
demo.launch()
|