Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,125 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
def
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
8 |
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import re, os, warnings
|
4 |
+
from langchain import PromptTemplate, LLMChain
|
5 |
+
from langchain.llms.base import LLM
|
6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, GenerationConfig
|
7 |
+
from peft import LoraConfig, get_peft_model, PeftConfig, PeftModel
|
8 |
+
warnings.filterwarnings("ignore")
|
9 |
|
10 |
+
def init_model_and_tokenizer(PEFT_MODEL):
|
11 |
+
config = PeftConfig.from_pretrained(PEFT_MODEL)
|
12 |
+
bnb_config = BitsAndBytesConfig(
|
13 |
+
load_in_4bit=True,
|
14 |
+
bnb_4bit_quant_type="nf4",
|
15 |
+
bnb_4bit_use_double_quant=True,
|
16 |
+
bnb_4bit_compute_dtype=torch.float16,
|
17 |
+
)
|
18 |
|
19 |
+
peft_base_model = AutoModelForCausalLM.from_pretrained(
|
20 |
+
config.base_model_name_or_path,
|
21 |
+
return_dict=True,
|
22 |
+
quantization_config=bnb_config,
|
23 |
+
device_map="auto",
|
24 |
+
trust_remote_code=True,
|
25 |
+
)
|
26 |
+
|
27 |
+
peft_model = PeftModel.from_pretrained(peft_base_model, PEFT_MODEL)
|
28 |
+
|
29 |
+
peft_tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
|
30 |
+
peft_tokenizer.pad_token = peft_tokenizer.eos_token
|
31 |
+
|
32 |
+
return peft_model, peft_tokenizer
|
33 |
+
|
34 |
+
def init_llm_chain(peft_model, peft_tokenizer):
|
35 |
+
class CustomLLM(LLM):
|
36 |
+
def _call(self, prompt: str, stop=None, run_manager=None) -> str:
|
37 |
+
device = "cuda:0"
|
38 |
+
peft_encoding = peft_tokenizer(prompt, return_tensors="pt").to(device)
|
39 |
+
peft_outputs = peft_model.generate(input_ids=peft_encoding.input_ids, generation_config=GenerationConfig(max_new_tokens=256, pad_token_id = peft_tokenizer.eos_token_id, \
|
40 |
+
eos_token_id = peft_tokenizer.eos_token_id, attention_mask = peft_encoding.attention_mask, \
|
41 |
+
temperature=0.4, top_p=0.6, repetition_penalty=1.3, num_return_sequences=1,))
|
42 |
+
peft_text_output = peft_tokenizer.decode(peft_outputs[0], skip_special_tokens=True)
|
43 |
+
return peft_text_output
|
44 |
+
|
45 |
+
@property
|
46 |
+
def _llm_type(self) -> str:
|
47 |
+
return "custom"
|
48 |
+
|
49 |
+
llm = CustomLLM()
|
50 |
+
|
51 |
+
template = """Answer the following question truthfully.
|
52 |
+
If you don't know the answer, respond 'Sorry, I don't know the answer to this question.'.
|
53 |
+
If the question is too complex, respond 'Kindly, consult a psychiatrist for further queries.'.
|
54 |
+
|
55 |
+
Example Format:
|
56 |
+
<HUMAN>: question here
|
57 |
+
<ASSISTANT>: answer here
|
58 |
+
|
59 |
+
Begin!
|
60 |
+
|
61 |
+
<HUMAN>: {query}
|
62 |
+
<ASSISTANT>:"""
|
63 |
+
|
64 |
+
prompt = PromptTemplate(template=template, input_variables=["query"])
|
65 |
+
llm_chain = LLMChain(prompt=prompt, llm=llm)
|
66 |
+
|
67 |
+
return llm_chain
|
68 |
+
|
69 |
+
def user(user_message, history):
|
70 |
+
return "", history + [[user_message, None]]
|
71 |
+
|
72 |
+
def bot(history):
|
73 |
+
if len(history) >= 2:
|
74 |
+
query = history[-2][0] + "\n" + history[-2][1] + "\nHere, is the next QUESTION: " + history[-1][0]
|
75 |
+
else:
|
76 |
+
query = history[-1][0]
|
77 |
+
|
78 |
+
bot_message = llm_chain.run(query)
|
79 |
+
bot_message = post_process_chat(bot_message)
|
80 |
+
|
81 |
+
history[-1][1] = ""
|
82 |
+
history[-1][1] += bot_message
|
83 |
+
return history
|
84 |
+
|
85 |
+
def post_process_chat(bot_message):
|
86 |
+
try:
|
87 |
+
bot_message = re.findall(r"<ASSISTANT>:.*?Begin!", bot_message, re.DOTALL)[1]
|
88 |
+
except IndexError:
|
89 |
+
pass
|
90 |
+
|
91 |
+
bot_message = re.split(r'<ASSISTANT>\:?\s?', bot_message)[-1].split("Begin!")[0]
|
92 |
+
|
93 |
+
bot_message = re.sub(r"^(.*?\.)(?=\n|$)", r"\1", bot_message, flags=re.DOTALL)
|
94 |
+
try:
|
95 |
+
bot_message = re.search(r"(.*\.)", bot_message, re.DOTALL).group(1)
|
96 |
+
except AttributeError:
|
97 |
+
pass
|
98 |
+
|
99 |
+
bot_message = re.sub(r"\n\d.$", "", bot_message)
|
100 |
+
bot_message = re.split(r"(Goodbye|Take care|Best Wishes)", bot_message, flags=re.IGNORECASE)[0].strip()
|
101 |
+
bot_message = bot_message.replace("\n\n", "\n")
|
102 |
+
|
103 |
+
return bot_message
|
104 |
+
|
105 |
+
model = "heliosbrahma/falcon-7b-sharded-bf16-finetuned-mental-health-conversational"
|
106 |
+
peft_model, peft_tokenizer = init_model_and_tokenizer(PEFT_MODEL = model)
|
107 |
+
|
108 |
+
with gr.Blocks() as interface:
|
109 |
+
gr.HTML("""<h1>Welcome to Mental Health Conversational AI</h1>""")
|
110 |
+
gr.Markdown(
|
111 |
+
"""Chatbot specifically designed to provide psychoeducation, offer non-judgemental and empathetic support, self-assessment and monitoring.<br>
|
112 |
+
Get instant response for any mental health related queries. If the chatbot seems you need external support, then it will respond appropriately.<br>"""
|
113 |
+
)
|
114 |
+
|
115 |
+
chatbot = gr.Chatbot()
|
116 |
+
query = gr.Textbox(label="Type your query here, then press 'enter' and scroll up for response")
|
117 |
+
clear = gr.Button(value="Clear Chat History!")
|
118 |
+
clear.style(size="sm")
|
119 |
+
|
120 |
+
llm_chain = init_llm_chain(peft_model, peft_tokenizer)
|
121 |
+
|
122 |
+
query.submit(user, [query, chatbot], [query, chatbot], queue=False).then(bot, chatbot, chatbot)
|
123 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
124 |
+
|
125 |
+
interface.queue().launch()
|