Spaces:
Sleeping
Sleeping
Update app.py
#1
by
MuhammmadRizwanRizwan
- opened
app.py
CHANGED
@@ -1,11 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
def respond(
|
11 |
message,
|
@@ -14,20 +108,25 @@ def respond(
|
|
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,
|
@@ -35,30 +134,218 @@ def respond(
|
|
35 |
top_p=top_p,
|
36 |
):
|
37 |
token = message.choices[0].delta.content
|
|
|
|
|
|
|
|
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 |
+
# """
|
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()
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
import gradio as gr
|
73 |
from huggingface_hub import InferenceClient
|
74 |
+
import time
|
75 |
+
import random
|
76 |
+
from datetime import datetime
|
77 |
+
|
78 |
+
# Theme and styling constants
|
79 |
+
THEME = gr.themes.Soft(
|
80 |
+
primary_hue="indigo",
|
81 |
+
secondary_hue="blue",
|
82 |
+
neutral_hue="slate",
|
83 |
+
radius_size=gr.themes.sizes.radius_sm,
|
84 |
+
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
|
85 |
+
)
|
86 |
|
87 |
+
# Configuration
|
88 |
+
MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
|
89 |
+
DEFAULT_SYSTEM_MSG = "You are a helpful, friendly, and knowledgeable AI assistant."
|
|
|
90 |
|
91 |
+
# Initialize the client
|
92 |
+
client = InferenceClient(MODEL_ID)
|
93 |
+
|
94 |
+
def format_history(history):
|
95 |
+
"""Helper function to format chat history for display"""
|
96 |
+
formatted = []
|
97 |
+
for user_msg, ai_msg in history:
|
98 |
+
if user_msg:
|
99 |
+
formatted.append({"role": "user", "content": user_msg})
|
100 |
+
if ai_msg:
|
101 |
+
formatted.append({"role": "assistant", "content": ai_msg})
|
102 |
+
return formatted
|
103 |
|
104 |
def respond(
|
105 |
message,
|
|
|
108 |
max_tokens,
|
109 |
temperature,
|
110 |
top_p,
|
111 |
+
model_id,
|
112 |
+
typing_animation=True
|
113 |
):
|
114 |
+
"""Generate response from the model with typing animation effect"""
|
115 |
+
# Format messages for the API
|
116 |
messages = [{"role": "system", "content": system_message}]
|
|
|
117 |
for val in history:
|
118 |
if val[0]:
|
119 |
messages.append({"role": "user", "content": val[0]})
|
120 |
if val[1]:
|
121 |
messages.append({"role": "assistant", "content": val[1]})
|
|
|
122 |
messages.append({"role": "user", "content": message})
|
123 |
+
|
124 |
+
# Use the selected model
|
125 |
+
inference_client = InferenceClient(model_id)
|
126 |
+
|
127 |
+
# Generate response with typing animation
|
128 |
response = ""
|
129 |
+
for message in inference_client.chat_completion(
|
|
|
130 |
messages,
|
131 |
max_tokens=max_tokens,
|
132 |
stream=True,
|
|
|
134 |
top_p=top_p,
|
135 |
):
|
136 |
token = message.choices[0].delta.content
|
137 |
+
if token:
|
138 |
+
response += token
|
139 |
+
# If typing animation is enabled, add a small random delay
|
140 |
+
if typing_animation:
|
141 |
+
time.sleep(random.uniform(0.01, 0.03))
|
142 |
+
yield response
|
143 |
|
144 |
+
def create_interface():
|
145 |
+
"""Create and configure the Gradio interface"""
|
146 |
+
# Available models dropdown
|
147 |
+
models = [
|
148 |
+
"HuggingFaceH4/zephyr-7b-beta",
|
149 |
+
"mistralai/Mistral-7B-Instruct-v0.2",
|
150 |
+
"meta-llama/Llama-2-7b-chat-hf",
|
151 |
+
"gpt2" # Fallback for quick testing
|
152 |
+
]
|
153 |
+
|
154 |
+
# Custom CSS for better styling
|
155 |
+
css = """
|
156 |
+
.gradio-container {
|
157 |
+
min-height: 100vh;
|
158 |
+
}
|
159 |
+
.message-bubble {
|
160 |
+
padding: 10px 15px;
|
161 |
+
border-radius: 12px;
|
162 |
+
margin-bottom: 8px;
|
163 |
+
}
|
164 |
+
.user-bubble {
|
165 |
+
background-color: #e9f5ff;
|
166 |
+
margin-left: 20px;
|
167 |
+
}
|
168 |
+
.bot-bubble {
|
169 |
+
background-color: #f0f4f9;
|
170 |
+
margin-right: 20px;
|
171 |
+
}
|
172 |
+
.timestamp {
|
173 |
+
font-size: 0.7em;
|
174 |
+
color: #888;
|
175 |
+
margin-top: 2px;
|
176 |
+
}
|
177 |
+
"""
|
178 |
+
|
179 |
+
with gr.Blocks(theme=THEME, css=css) as demo:
|
180 |
+
gr.Markdown("# 🤖 Enhanced AI Chat Interface")
|
181 |
+
gr.Markdown("Chat with state-of-the-art language models from Hugging Face")
|
182 |
+
|
183 |
+
with gr.Row():
|
184 |
+
with gr.Column(scale=3):
|
185 |
+
chatbot = gr.Chatbot(
|
186 |
+
label="Conversation",
|
187 |
+
bubble_full_width=False,
|
188 |
+
height=600,
|
189 |
+
avatar_images=("👤", "🤖"),
|
190 |
+
show_copy_button=True
|
191 |
+
)
|
192 |
+
|
193 |
+
with gr.Row():
|
194 |
+
msg = gr.Textbox(
|
195 |
+
placeholder="Type your message here...",
|
196 |
+
show_label=False,
|
197 |
+
container=False,
|
198 |
+
scale=9
|
199 |
+
)
|
200 |
+
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
201 |
+
|
202 |
+
with gr.Accordion("Conversation Summary", open=False):
|
203 |
+
summary = gr.Textbox(label="Key points from this conversation", lines=3, interactive=False)
|
204 |
+
summary_btn = gr.Button("Generate Summary", variant="secondary")
|
205 |
+
|
206 |
+
with gr.Column(scale=1):
|
207 |
+
with gr.Accordion("Model Settings", open=True):
|
208 |
+
model_selection = gr.Dropdown(
|
209 |
+
models,
|
210 |
+
value=MODEL_ID,
|
211 |
+
label="Select Model",
|
212 |
+
info="Choose which AI model to chat with"
|
213 |
+
)
|
214 |
+
|
215 |
+
system_msg = gr.Textbox(
|
216 |
+
value=DEFAULT_SYSTEM_MSG,
|
217 |
+
label="System Message",
|
218 |
+
info="Instructions that define how the AI behaves",
|
219 |
+
lines=3
|
220 |
+
)
|
221 |
+
|
222 |
+
max_tokens = gr.Slider(
|
223 |
+
minimum=1,
|
224 |
+
maximum=2048,
|
225 |
+
value=512,
|
226 |
+
step=1,
|
227 |
+
label="Max New Tokens",
|
228 |
+
info="Maximum length of generated response"
|
229 |
+
)
|
230 |
+
|
231 |
+
with gr.Row():
|
232 |
+
with gr.Column():
|
233 |
+
temperature = gr.Slider(
|
234 |
+
minimum=0.1,
|
235 |
+
maximum=2.0,
|
236 |
+
value=0.7,
|
237 |
+
step=0.1,
|
238 |
+
label="Temperature",
|
239 |
+
info="Higher = more creative, Lower = more focused"
|
240 |
+
)
|
241 |
+
|
242 |
+
with gr.Column():
|
243 |
+
top_p = gr.Slider(
|
244 |
+
minimum=0.1,
|
245 |
+
maximum=1.0,
|
246 |
+
value=0.95,
|
247 |
+
step=0.05,
|
248 |
+
label="Top-p",
|
249 |
+
info="Controls randomness in token selection"
|
250 |
+
)
|
251 |
+
|
252 |
+
typing_effect = gr.Checkbox(
|
253 |
+
label="Enable Typing Animation",
|
254 |
+
value=True,
|
255 |
+
info="Show realistic typing animation"
|
256 |
+
)
|
257 |
+
|
258 |
+
with gr.Accordion("Tools", open=False):
|
259 |
+
clear_btn = gr.Button("Clear Conversation", variant="secondary")
|
260 |
+
export_btn = gr.Button("Export Chat History", variant="secondary")
|
261 |
+
chat_download = gr.File(label="Download", interactive=False, visible=False)
|
262 |
+
|
263 |
+
# Event handlers
|
264 |
+
msg_submit = msg.submit(
|
265 |
+
fn=respond,
|
266 |
+
inputs=[msg, chatbot, system_msg, max_tokens, temperature, top_p, model_selection, typing_effect],
|
267 |
+
outputs=[chatbot],
|
268 |
+
queue=True
|
269 |
+
)
|
270 |
+
|
271 |
+
submit_click = submit_btn.click(
|
272 |
+
fn=respond,
|
273 |
+
inputs=[msg, chatbot, system_msg, max_tokens, temperature, top_p, model_selection, typing_effect],
|
274 |
+
outputs=[chatbot],
|
275 |
+
queue=True
|
276 |
+
)
|
277 |
+
|
278 |
+
# Clear the input field after sending
|
279 |
+
msg_submit.then(lambda: "", None, msg)
|
280 |
+
submit_click.then(lambda: "", None, msg)
|
281 |
+
|
282 |
+
# Clear chat history
|
283 |
+
def clear_history():
|
284 |
+
return None
|
285 |
+
|
286 |
+
clear_btn.click(
|
287 |
+
fn=clear_history,
|
288 |
+
inputs=[],
|
289 |
+
outputs=[chatbot]
|
290 |
+
)
|
291 |
+
|
292 |
+
# Export chat history
|
293 |
+
def export_history(history):
|
294 |
+
if not history:
|
295 |
+
return None
|
296 |
+
|
297 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
298 |
+
filename = f"chat_history_{timestamp}.txt"
|
299 |
+
|
300 |
+
with open(filename, "w") as f:
|
301 |
+
f.write("# Chat History\n\n")
|
302 |
+
f.write(f"Exported on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
|
303 |
+
|
304 |
+
for user_msg, ai_msg in history:
|
305 |
+
f.write(f"## User\n{user_msg}\n\n")
|
306 |
+
f.write(f"## AI\n{ai_msg}\n\n")
|
307 |
+
f.write("---\n\n")
|
308 |
+
|
309 |
+
return filename
|
310 |
+
|
311 |
+
export_btn.click(
|
312 |
+
fn=export_history,
|
313 |
+
inputs=[chatbot],
|
314 |
+
outputs=[chat_download],
|
315 |
+
queue=False
|
316 |
+
).then(
|
317 |
+
lambda: gr.update(visible=True),
|
318 |
+
None,
|
319 |
+
[chat_download]
|
320 |
+
)
|
321 |
+
|
322 |
+
# Generate conversation summary (simplified implementation)
|
323 |
+
def generate_summary(history):
|
324 |
+
if not history or len(history) < 2:
|
325 |
+
return "Not enough conversation to summarize yet."
|
326 |
+
|
327 |
+
# In a real application, you might want to send this to the model
|
328 |
+
# Here we're just creating a simple summary
|
329 |
+
topics = []
|
330 |
+
for user_msg, _ in history:
|
331 |
+
if user_msg and len(user_msg.split()) > 3: # Simple heuristic
|
332 |
+
topics.append(user_msg.split()[0:3])
|
333 |
+
|
334 |
+
if topics:
|
335 |
+
return f"This conversation covered {len(history)} exchanges about various topics."
|
336 |
+
else:
|
337 |
+
return "Brief conversation with no clear topics."
|
338 |
+
|
339 |
+
summary_btn.click(
|
340 |
+
fn=generate_summary,
|
341 |
+
inputs=[chatbot],
|
342 |
+
outputs=[summary]
|
343 |
+
)
|
344 |
+
|
345 |
+
return demo
|
346 |
|
347 |
+
# Create and launch the interface
|
348 |
+
demo = create_interface()
|
349 |
|
350 |
if __name__ == "__main__":
|
351 |
+
demo.launch(share=False, debug=False)
|