shee2205 commited on
Commit
a4de076
Β·
verified Β·
1 Parent(s): 86b01f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -63
app.py CHANGED
@@ -1,64 +1,136 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ 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):
12
+ with open(path) as f:
13
+ return json.load(f)
14
+ return default
15
+
16
+ def save_json(path, data):
17
+ with open(path, "w") as f:
18
+ json.dump(data, f, indent=2)
19
+
20
+ profile = load_json(PROFILE_FILE, {})
21
+ daily = load_json(DAILY_FILE, {})
22
+
23
+ def build_context(profile, daily):
24
+ recent_days = sorted(daily.keys(), reverse=True)[:7]
25
+ daily_lines = "\n".join([f"{d}: {daily[d].get('log','')}" for d in recent_days])
26
+ context = (
27
+ f"Profile:\n{json.dumps(profile, indent=2)}\n"
28
+ f"Recent daily logs:\n{daily_lines}\n"
29
+ "You are a helpful assistant. Answer only using the provided information. "
30
+ "If you don't know the answer, reply: 'Sheetal hasn't shared that yet!'"
31
+ )
32
+ return context
33
+
34
+ def get_llm():
35
+ return pipeline(
36
+ "text-generation",
37
+ model="HuggingFaceH4/zephyr-7b-beta",
38
+ max_new_tokens=256,
39
+ do_sample=True,
40
+ temperature=0.7,
41
+ trust_remote_code=True,
42
+ )
43
+
44
+ llm = None
45
+
46
+ def chatbot_qa(user_q):
47
+ global llm
48
+ if llm is None:
49
+ llm = get_llm()
50
+ context = build_context(profile, daily)
51
+ prompt = f"System: {context}\nUser: {user_q}\nAssistant:"
52
+ outputs = llm(prompt, max_new_tokens=256)
53
+ answer = outputs[0]["generated_text"].split("Assistant:")[-1].strip()
54
+ return answer
55
+
56
+ def update_profile(name, city, job, about):
57
+ profile.update({
58
+ "name": name,
59
+ "city": city,
60
+ "job": job,
61
+ "about": about
62
+ })
63
+ save_json(PROFILE_FILE, profile)
64
+ return "Profile updated!"
65
+
66
+ def update_daily_log(freeform):
67
+ today = str(date.today())
68
+ daily[today] = {"log": freeform}
69
+ save_json(DAILY_FILE, daily)
70
+ return f"Today's log saved! ({today})"
71
+
72
+ def get_profile_defaults():
73
+ return (
74
+ profile.get("name", "Sheetal"),
75
+ profile.get("city", ""),
76
+ profile.get("job", ""),
77
+ profile.get("about", "")
78
+ )
79
+
80
+ def get_today_log():
81
+ today = str(date.today())
82
+ return daily.get(today, {}).get("log", "")
83
+
84
+ def recent_logs():
85
+ logs = ""
86
+ for d in sorted(daily.keys(), reverse=True)[:5]:
87
+ logs += f"**{d}**: {daily[d]['log']}\n"
88
+ return logs
89
+
90
+ with gr.Blocks(title="Sheetal's Personal Chatbot") as demo:
91
+ gr.Markdown("# 🌸 Sheetal's Personal Chatbot")
92
+
93
+ with gr.Tab("πŸ“ Admin (Sheetal)"):
94
+ gr.Markdown("### Edit Your Profile")
95
+ with gr.Row():
96
+ name = gr.Textbox(label="Name", value=profile.get("name", "Sheetal"))
97
+ city = gr.Textbox(label="City", value=profile.get("city", ""))
98
+ job = gr.Textbox(label="Profession", value=profile.get("job", ""))
99
+ about = gr.Textbox(label="A few lines about you", value=profile.get("about", ""))
100
+ save_profile_btn = gr.Button("Save Profile")
101
+ profile_output = gr.Textbox(label="", interactive=False)
102
+
103
+ save_profile_btn.click(
104
+ fn=update_profile,
105
+ inputs=[name, city, job, about],
106
+ outputs=profile_output
107
+ )
108
+
109
+ gr.Markdown("---")
110
+ gr.Markdown("### 🌱 Add Your Daily Status (free text!)")
111
+ today_log = gr.Textbox(label="What do you want to remember about today?", value=get_today_log())
112
+ save_log_btn = gr.Button("Save Today's Log")
113
+ log_output = gr.Textbox(label="", interactive=False)
114
+
115
+ save_log_btn.click(
116
+ fn=update_daily_log,
117
+ inputs=today_log,
118
+ outputs=log_output
119
+ )
120
+
121
+ gr.Markdown("#### πŸ“… Recent Logs")
122
+ recent_logs_box = gr.Markdown(recent_logs())
123
+
124
+ with gr.Tab("πŸ’¬ Ask About Sheetal"):
125
+ gr.Markdown("### πŸ’¬ Ask Anything About Sheetal")
126
+ user_q = gr.Textbox(label="Type your question here:")
127
+ ask_btn = gr.Button("Ask")
128
+ answer_box = gr.Textbox(label="Bot answer", interactive=False)
129
+
130
+ ask_btn.click(
131
+ fn=chatbot_qa,
132
+ inputs=user_q,
133
+ outputs=answer_box
134
+ )
135
+
136
+ demo.launch()