supp03 commited on
Commit
21eae3f
·
verified ·
1 Parent(s): 0aed123

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -59
app.py CHANGED
@@ -1,64 +1,116 @@
 
 
 
 
 
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 torch
2
+ import pandas as pd
3
+ import re
4
+ import time
5
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
6
  import gradio as gr
7
+
8
+ # Disable torch._dynamo
9
+ import torch._dynamo
10
+ torch._dynamo.disable()
11
+
12
+ # Load model and tokenizer
13
+ model_path = "supp03/E3L-AI-CHATBOT"
14
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
15
+ model = AutoModelForCausalLM.from_pretrained(
16
+ model_path,
17
+ torch_dtype=torch.float16,
18
+ device_map="auto"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  )
20
 
21
+ # Load pipeline
22
+ pipe = pipeline(
23
+ "text-generation",
24
+ model=model,
25
+ tokenizer=tokenizer,
26
+ pad_token_id=tokenizer.eos_token_id
27
+ )
28
+
29
+ # Context memory
30
+ context_memory = {
31
+ "last_question": None,
32
+ "last_answer": None
33
+ }
34
+
35
+ # Main inference function
36
+ def chat(user_input):
37
+ user_input = user_input.strip()
38
+ if not user_input:
39
+ return "Please enter a question."
40
+
41
+ if user_input.lower() == 'exit':
42
+ return "Exiting. Reload the app to start over."
43
+
44
+ exact_answer = get_exact_answer(user_input)
45
+ if exact_answer:
46
+ context_memory["last_question"] = user_input
47
+ context_memory["last_answer"] = exact_answer
48
+ return f"[Exact Match Found]\n\n{exact_answer}"
49
+
50
+ # Determine context reference
51
+ lower_input = user_input.lower()
52
+ refer_prev = any(phrase in lower_input for phrase in [
53
+ "previous question", "previous answer", "elaborate", "detail", "more info", "explain more", "expand on that"
54
+ ])
55
+
56
+ context = ""
57
+ if refer_prev and context_memory["last_question"] and context_memory["last_answer"]:
58
+ context = (
59
+ f"Previous Question: {context_memory['last_question']}\n"
60
+ f"Previous Answer: {context_memory['last_answer']}\n\n"
61
+ "Please elaborate on the previous answer with more details, examples, and explanations to deepen understanding.\n\n"
62
+ )
63
+
64
+ if "steps" in lower_input or "step by step" in lower_input:
65
+ style_instruction = "Organize your response into a clearly numbered step-by-step list (1., 2., 3., ...)."
66
+ elif "how" in lower_input or "ways" in lower_input:
67
+ style_instruction = "Organize your response into practical bullet points."
68
+ else:
69
+ style_instruction = "Write in a natural, conversational paragraph form."
70
+
71
+ generated_prompt = (
72
+ "You are a warm, thoughtful, and emotionally intelligent mentor. "
73
+ "Your job is to provide deeply personalized, practical, and supportive guidance. "
74
+ "Avoid sounding robotic or generic. Respond with empathy, clarity, and human warmth, as if you're speaking directly to the person. "
75
+ f"{style_instruction}\n\n"
76
+ f"{context}"
77
+ f"Question: {user_input}\n\nAnswer:"
78
+ )
79
+
80
+ start_time = time.time()
81
+ with torch.no_grad():
82
+ generated = pipe(
83
+ generated_prompt,
84
+ max_new_tokens=300,
85
+ do_sample=True,
86
+ top_p=0.9,
87
+ temperature=0.7
88
+ )
89
+ elapsed_time = time.time() - start_time
90
+
91
+ output_text = generated[0]["generated_text"]
92
+ match = re.search(r"Answer:\s*(.*)", output_text, re.DOTALL)
93
+ model_answer = match.group(1).strip() if match else output_text.strip()
94
+
95
+ for kw in ["your students", "may also want", "in order to"]:
96
+ if kw in model_answer:
97
+ model_answer = model_answer.split(kw)[0].strip()
98
+ break
99
+
100
+ context_memory["last_question"] = user_input
101
+ context_memory["last_answer"] = model_answer
102
+
103
+ seconds = int(elapsed_time % 60)
104
+ return f"[Response Time]: {seconds}s\n\n{model_answer}"
105
+
106
+ # Gradio UI
107
+ iface = gr.Interface(
108
+ fn=chat,
109
+ inputs=gr.Textbox(label="Ask your question", placeholder="Type your question here..."),
110
+ outputs="markdown",
111
+ title="Gemma Mentor Chatbot",
112
+ description="Ask questions and get warm, supportive, emotionally intelligent responses. Type 'exit' to reset."
113
+ )
114
 
115
  if __name__ == "__main__":
116
+ iface.launch()