brkznb commited on
Commit
aa591fb
Β·
verified Β·
1 Parent(s): 9fab3a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -63
app.py CHANGED
@@ -1,64 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ !pip uninstall accelerate peft bitsandbytes transformers trl -y
2
+ !pip install accelerate peft==0.13.2 bitsandbytes transformers trl==0.12.0
3
+ !pip install huggingface_hub
4
+ !pip install ipywidgets
5
+ !pip install -q gradio
6
+
7
+ import torch
8
+ from trl import SFTTrainer
9
+ from peft import LoraConfig
10
+ from datasets import load_dataset
11
+ from transformers import (AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments, pipeline)
12
+ import ipywidgets as widgets
13
+ from IPython.display import display
14
  import gradio as gr
15
+
16
+ llama_model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path = "aboonaji/llama2finetune-v2",
17
+ quantization_config = BitsAndBytesConfig(load_in_4bit = True, bnb_4bit_compute_dtype = getattr(torch, "float16"), bnb_4bit_quant_type = "nf4"))
18
+ llama_model.config.use_cache = False
19
+ llama_model.config.pretraining_tp = 1
20
+
21
+ llama_tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path = "aboonaji/llama2finetune-v2", trust_remote_code = True)
22
+ llama_tokenizer.pad_token = llama_tokenizer.eos_token
23
+ llama_tokenizer.padding_side = "right"
24
+
25
+ training_arguments = TrainingArguments(output_dir = "./results", per_device_train_batch_size = 1, max_steps = 100)
26
+ llama_sft_trainer = SFTTrainer(model = llama_model,
27
+ args = training_arguments,
28
+ train_dataset = load_dataset(path = "aboonaji/wiki_medical_terms_llam2_format", split = "train"),
29
+ tokenizer = llama_tokenizer,
30
+ peft_config = LoraConfig(task_type = "CAUSAL_LM", r = 16, lora_alpha = 16, lora_dropout = 0.1),
31
+ dataset_text_field = "text")
32
+
33
+ llama_sft_trainer.train()
34
+
35
+ generator = pipeline("text-generation", model=llama_model, tokenizer=llama_tokenizer, max_length=500)
36
+
37
+ # In-memory user database
38
+ user_db = {}
39
+
40
+ # Response function
41
+ def generate_response(prompt):
42
+ response = generator(f"<s>[INST] {prompt} [/INST]")[0]["generated_text"]
43
+ return response
44
+
45
+ # Sign-up and login logic
46
+ def signup_user(new_username, new_password):
47
+ if not new_username or not new_password:
48
+ return "❌ No input. Please provide both username and password."
49
+ if new_username in user_db:
50
+ return "❌ Username already exists."
51
+ user_db[new_username] = new_password
52
+ return "βœ… Account created! Please log in."
53
+
54
+ def login_user(username, password):
55
+ if username in user_db and user_db[username] == password:
56
+ return (
57
+ gr.update(visible=True), # Show chat UI
58
+ gr.update(visible=False), # Hide login UI
59
+ "", # Clear login message
60
+ gr.update(selected=3) # Switch to Chat tab
61
+ )
62
+ return (
63
+ gr.update(visible=False),
64
+ gr.update(visible=True),
65
+ "❌ Invalid credentials",
66
+ gr.update(selected=2)
67
+ )
68
+
69
+ def logout_user():
70
+ return (
71
+ gr.update(visible=False), # Hide chat UI
72
+ gr.update(visible=True), # Show login UI
73
+ gr.update(selected=0) # Switch to Landing tab
74
+ )
75
+
76
+ with gr.Blocks(theme="soft", css="""
77
+ #create-btn button,
78
+ #login-btn button,
79
+ #submit-btn button,
80
+ #logout-btn button {
81
+ font-size: 12px !important;
82
+ padding: 4px 8px !important;
83
+ height: 30px !important;
84
+ width: auto !important;
85
+ min-width: 80px !important;
86
+ }
87
+ """) as demo:
88
+ with gr.Tabs(selected=0, elem_id="tabs") as tabs:
89
+ with gr.Tab("Home"):
90
+ with gr.Column(elem_id="landing-container") as landing_ui:
91
+ gr.Markdown("# 🏠 Welcome to MEDChat AI")
92
+ gr.Markdown("---")
93
+ gr.Markdown("#### πŸ”§ Features:")
94
+ gr.Markdown("- Medical Q&A support\n- Easy-to-use chatbot interface\n- Privacy-focused with local data")
95
+ gr.Markdown("---")
96
+ gr.Markdown("Β© 2025 MEDChat AI | Finetuned by LLaMA 2 | Created for educational purposes")
97
+
98
+ with gr.Tab("Sign Up"):
99
+ with gr.Column() as signup_ui:
100
+ gr.Markdown("### πŸ“ Sign Up")
101
+ new_username = gr.Textbox(label="New Username")
102
+ new_password = gr.Textbox(label="New Password", type="password")
103
+ create_account_btn = gr.Button("Create Account", elem_id="create-btn")
104
+ signup_msg = gr.Markdown()
105
+
106
+ with gr.Tab("Login"):
107
+ with gr.Column(visible=True) as login_ui:
108
+ gr.Markdown("### πŸ” Login")
109
+ username = gr.Textbox(label="Username")
110
+ password = gr.Textbox(label="Password", type="password")
111
+ login_btn = gr.Button("Login", elem_id="login-btn")
112
+ login_msg = gr.Markdown()
113
+
114
+ with gr.Tab("Chat"):
115
+ with gr.Column(visible=False) as chat_ui:
116
+ gr.Markdown("## πŸ’¬ MEDChat AI")
117
+ gr.Markdown("What can I help with today?")
118
+ logout_btn = gr.Button("πŸšͺ Logout", elem_id="logout-btn")
119
+ prompt = gr.Textbox(lines=5, placeholder="Enter your prompt...")
120
+ submit_btn = gr.Button("Submit", elem_id="submit-btn")
121
+ response = gr.Textbox(label="Response")
122
+
123
+ gr.Markdown("### Try one of these:")
124
+ examples = gr.Examples(
125
+ examples=[
126
+ ["What does the immune system do?"],
127
+ ["What is Epistaxis?"],
128
+ ["Do our intestines contain germs?"],
129
+ ["What are allergies?"],
130
+ ["Should I start taking creatine?"],
131
+ ["What are antibiotics?"],
132
+ ["Why do I get sick?"],
133
+ ["What's the difference between bacteria and viruses?"],
134
+ ["Where are some places that germs hide?"],
135
+ ],
136
+ inputs=prompt
137
+ )
138
+
139
+
140
+
141
+ logout_btn.click(fn=logout_user, outputs=[chat_ui, login_ui, tabs])
142
+
143
+ # Tab navigation logic
144
+ to_signup = gr.Button(visible=False)
145
+ to_login = gr.Button(visible=False)
146
+
147
+ to_signup.click(lambda: gr.update(selected=1), outputs=tabs)
148
+ to_login.click(lambda: gr.update(selected=2), outputs=tabs)
149
+ create_account_btn.click(fn=signup_user, inputs=[new_username, new_password], outputs=signup_msg)
150
+ login_btn.click(
151
+ fn=login_user,
152
+ inputs=[username, password],
153
+ outputs=[chat_ui, login_ui, login_msg, tabs]
154
+ )
155
+ submit_btn.click(fn=generate_response, inputs=prompt, outputs=response)
156
+
157
+ # Launch the interface
158
+ demo.launch(share=True)