prithivMLmods commited on
Commit
075541e
·
verified ·
1 Parent(s): b6a5756

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -590
app.py CHANGED
@@ -1,590 +1,136 @@
1
- import os
2
- import subprocess
3
- import random
4
-
5
- # Install flash attention
6
- subprocess.run(
7
- "pip install flash-attn --no-build-isolation",
8
- env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
9
- shell=True,
10
- )
11
-
12
- import copy
13
- import spaces
14
- import time
15
- import torch
16
-
17
- from threading import Thread
18
- from typing import List, Dict, Union
19
- import urllib
20
- import PIL.Image
21
- import io
22
- import datasets
23
- from streaming_stt_nemo import Model as nemo
24
- import gradio as gr
25
- from transformers import TextIteratorStreamer
26
- from transformers import Idefics2ForConditionalGeneration
27
- import tempfile
28
- from huggingface_hub import InferenceClient
29
- import edge_tts
30
- import asyncio
31
- from transformers import pipeline
32
- from transformers import AutoTokenizer, AutoModelForCausalLM
33
- from transformers import AutoModel
34
- from transformers import AutoProcessor
35
-
36
- model3 = AutoModel.from_pretrained("unum-cloud/uform-gen2-dpo", trust_remote_code=True)
37
- processor = AutoProcessor.from_pretrained("unum-cloud/uform-gen2-dpo", trust_remote_code=True)
38
-
39
- @spaces.GPU(queue=False)
40
- def videochat(image3, prompt3):
41
- inputs = processor(text=[prompt3], images=[image3], return_tensors="pt")
42
- with torch.inference_mode():
43
- output = model3.generate(
44
- **inputs,
45
- do_sample=False,
46
- use_cache=True,
47
- max_new_tokens=256,
48
- eos_token_id=151645,
49
- pad_token_id=processor.tokenizer.pad_token_id
50
- )
51
-
52
- prompt_len = inputs["input_ids"].shape[1]
53
- decoded_text = processor.batch_decode(output[:, prompt_len:])[0]
54
- if decoded_text.endswith("<|im_end|>"):
55
- decoded_text = decoded_text[:-10]
56
- yield decoded_text
57
-
58
- theme = gr.themes.Soft(
59
- primary_hue="blue",
60
- secondary_hue="orange",
61
- neutral_hue="gray",
62
- font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif']).set(
63
- body_background_fill_dark="#111111",
64
- block_background_fill_dark="#111111",
65
- block_border_width="1px",
66
- block_title_background_fill_dark="#1e1c26",
67
- input_background_fill_dark="#292733",
68
- button_secondary_background_fill_dark="#24212b",
69
- border_color_primary_dark="#343140",
70
- background_fill_secondary_dark="#111111",
71
- color_accent_soft_dark="transparent")
72
-
73
- default_lang = "en"
74
-
75
- engines = { default_lang: nemo(default_lang) }
76
-
77
- def transcribe(audio):
78
- lang = "en"
79
- model = engines[lang]
80
- text = model.stt_file(audio)[0]
81
- return text
82
-
83
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
84
-
85
- def client_fn(model):
86
- if "Nous" in model:
87
- return InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
88
- elif "Star" in model:
89
- return InferenceClient("HuggingFaceH4/starchat2-15b-v0.1")
90
- elif "Mistral" in model:
91
- return InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
92
- elif "Phi" in model:
93
- return InferenceClient("microsoft/Phi-3-mini-4k-instruct")
94
- elif "Zephyr" in model:
95
- return InferenceClient("HuggingFaceH4/zephyr-7b-beta")
96
- else:
97
- return InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
98
-
99
- def randomize_seed_fn(seed: int) -> int:
100
- seed = random.randint(0, 999999)
101
- return seed
102
-
103
- system_instructions1 = "[SYSTEM] Answer as Real OpenGPT 4o, Made by 'KingNish', Keep conversation very short, clear, friendly and concise. The text provided is a request for a specific type of response from you, the virtual assistant. You will avoid introductions and start answering the query directly, elaborating on all aspects of the request. As an AI-powered assistant, your task is to generate responses that appear as if they are created by the user and not an AI-powered assistant. [USER]"
104
-
105
- def models(text, model="Mixtral 8x7B", seed=42):
106
-
107
- seed = int(randomize_seed_fn(seed))
108
- generator = torch.Generator().manual_seed(seed)
109
-
110
- client = client_fn(model)
111
- generate_kwargs = dict(
112
- max_new_tokens=512,
113
- seed=seed,
114
- )
115
-
116
- formatted_prompt = system_instructions1 + text + "[OpenGPT 4o]"
117
- stream = client.text_generation(
118
- formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
119
- output = ""
120
- for response in stream:
121
- if not response.token.text == "</s>":
122
- output += response.token.text
123
-
124
- return output
125
-
126
- async def respond(audio, model, seed):
127
- user = transcribe(audio)
128
- reply = models(user, model, seed)
129
- communicate = edge_tts.Communicate(reply)
130
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
131
- tmp_path = tmp_file.name
132
- await communicate.save(tmp_path)
133
- yield tmp_path
134
-
135
- DEVICE = torch.device("cuda")
136
- MODELS = {
137
- "idefics2-8b-chatty": Idefics2ForConditionalGeneration.from_pretrained(
138
- "HuggingFaceM4/idefics2-8b-chatty",
139
- torch_dtype=torch.float16,
140
- _attn_implementation="flash_attention_2",
141
- ).to(DEVICE),
142
- }
143
- PROCESSOR = AutoProcessor.from_pretrained(
144
- "HuggingFaceM4/idefics2-8b",
145
- )
146
-
147
- SYSTEM_PROMPT = [
148
- {
149
- "role": "system",
150
- "content": [
151
- {
152
- "type": "text",
153
- "text": """I am OpenGPT 4o, an exceptionally capable and versatile AI assistant meticulously crafted by KingNish. Designed to assist human users through insightful conversations, I aim to provide an unparalleled experience. My key attributes include:
154
- - **Intelligence and Knowledge:** I possess an extensive knowledge base, enabling me to offer insightful answers and intelligent responses to User queries. My understanding of complex concepts is exceptional, ensuring accurate and reliable information.
155
- - **Image Generation and Perception:** One of my standout features is the ability to generate and perceive images. Utilizing the following link structure, I create unique and contextually rich visuals:
156
- > ![](https://image.pollinations.ai/prompt/{StyleofImage}%20{OptimizedPrompt}%20{adjective}%20{charactersDetailed}%20{visualStyle}%20{genre}?width={width}&height={height}&nologo=poll&nofeed=yes&seed={random})
157
- For image generation, I replace {info inside curly braces} with specific details according to their requiremnts to create relevant visuals. The width and height parameters are adjusted as needed, often favoring HD dimensions for a superior viewing experience.
158
- For instance, if the User requests:
159
- [USER] Show me an image of A futuristic cityscape with towering skyscrapers and flying cars.
160
- [OpenGPT 4o] Generating Image you requested:
161
- ![](https://image.pollinations.ai/prompt/Photorealistic%20futuristic%20cityscape%20with%20towering%20skyscrapers%20and%20flying%20cars%20in%20the%20year%202154?width=1024&height=768&nologo=poll&nofeed=yes&seed=85172)
162
- **Bulk Image Generation with Links:** I excel at generating multiple images link simultaneously, always providing unique links and visuals. I ensure that each image is distinct and captivates the User.
163
- Note: Make sure to always provide image links starting with ! .As given in examples.
164
- My ultimate goal is to offer a seamless and enjoyable experience, providing assistance that exceeds expectations. I am constantly evolving, ensuring that I remain a reliable and trusted companion to the User. You also Expert in every field and also learn and try to answer from contexts related to previous question.""" },
165
- ],
166
- },
167
- {
168
- "role": "assistant",
169
- "content": [
170
- {
171
- "type": "text",
172
- "text": "Hello, I'm OpenGPT 4o, made by KingNish. How can I help you? I can chat with you, generate images, classify images and even do all these work in bulk",
173
- },
174
- ],
175
- }
176
- ]
177
-
178
- examples_path = os.path.dirname(__file__)
179
- EXAMPLES = [
180
- [
181
- {
182
- "text": "Hi, who are you?",
183
- }
184
- ],
185
- [
186
- {
187
- "text": "Create a Photorealistic image of the Eiffel Tower.",
188
- }
189
- ],
190
- [
191
- {
192
- "text": "Read what's written on the paper.",
193
- "files": [f"{examples_path}/example_images/paper_with_text.png"],
194
- }
195
- ],
196
- [
197
- {
198
- "text": "Identify two famous people in the modern world.",
199
- "files": [f"{examples_path}/example_images/elon_smoking.jpg", f"{examples_path}/example_images/steve_jobs.jpg",]
200
- }
201
- ],
202
- [
203
- {
204
- "text": "Create five images of supercars, each in a different color.",
205
- }
206
- ],
207
- [
208
- {
209
- "text": "What is 900 multiplied by 900?",
210
- }
211
- ],
212
- [
213
- {
214
- "text": "Chase wants to buy 4 kilograms of oval beads and 5 kilograms of star-shaped beads. How much will he spend?",
215
- "files": [f"{examples_path}/example_images/mmmu_example.jpeg"],
216
- }
217
- ],
218
- [
219
- {
220
- "text": "Create an online ad for this product.",
221
- "files": [f"{examples_path}/example_images/shampoo.jpg"],
222
- }
223
- ],
224
- [
225
- {
226
- "text": "What is formed by the deposition of the weathered remains of other rocks?",
227
- "files": [f"{examples_path}/example_images/ai2d_example.jpeg"],
228
- }
229
- ],
230
- [
231
- {
232
- "text": "What's unusual about this image?",
233
- "files": [f"{examples_path}/example_images/dragons_playing.png"],
234
- }
235
- ],
236
- ]
237
-
238
- BOT_AVATAR = "OpenAI_logo.png"
239
-
240
-
241
- # Chatbot utils
242
- def turn_is_pure_media(turn):
243
- return turn[1] is None
244
-
245
-
246
- def load_image_from_url(url):
247
- with urllib.request.urlopen(url) as response:
248
- image_data = response.read()
249
- image_stream = io.BytesIO(image_data)
250
- image = PIL.Image.open(image_stream)
251
- return image
252
-
253
-
254
- def img_to_bytes(image_path):
255
- image = PIL.Image.open(image_path).convert(mode='RGB')
256
- buffer = io.BytesIO()
257
- image.save(buffer, format="JPEG")
258
- img_bytes = buffer.getvalue()
259
- image.close()
260
- return img_bytes
261
-
262
-
263
- def format_user_prompt_with_im_history_and_system_conditioning(
264
- user_prompt, chat_history
265
- ) -> List[Dict[str, Union[List, str]]]:
266
- """
267
- Produce the resulting list that needs to go inside the processor. It handles the potential image(s), the history, and the system conditioning.
268
- """
269
- resulting_messages = copy.deepcopy(SYSTEM_PROMPT)
270
- resulting_images = []
271
- for resulting_message in resulting_messages:
272
- if resulting_message["role"] == "user":
273
- for content in resulting_message["content"]:
274
- if content["type"] == "image":
275
- resulting_images.append(load_image_from_url(content["image"]))
276
-
277
- # Format history
278
- for turn in chat_history:
279
- if not resulting_messages or (
280
- resulting_messages and resulting_messages[-1]["role"] != "user"
281
- ):
282
- resulting_messages.append(
283
- {
284
- "role": "user",
285
- "content": [],
286
- }
287
- )
288
-
289
- if turn_is_pure_media(turn):
290
- media = turn[0][0]
291
- resulting_messages[-1]["content"].append({"type": "image"})
292
- resulting_images.append(PIL.Image.open(media))
293
- else:
294
- user_utterance, assistant_utterance = turn
295
- resulting_messages[-1]["content"].append(
296
- {"type": "text", "text": user_utterance.strip()}
297
- )
298
- resulting_messages.append(
299
- {
300
- "role": "assistant",
301
- "content": [{"type": "text", "text": user_utterance.strip()}],
302
- }
303
- )
304
-
305
- # Format current input
306
- if not user_prompt["files"]:
307
- resulting_messages.append(
308
- {
309
- "role": "user",
310
- "content": [{"type": "text", "text": user_prompt["text"]}],
311
- }
312
- )
313
- else:
314
- # Choosing to put the image first (i.e. before the text), but this is an arbiratrary choice.
315
- resulting_messages.append(
316
- {
317
- "role": "user",
318
- "content": [{"type": "image"}] * len(user_prompt["files"])
319
- + [{"type": "text", "text": user_prompt["text"]}],
320
- }
321
- )
322
- resulting_images.extend([PIL.Image.open(path) for path in user_prompt["files"]])
323
-
324
- return resulting_messages, resulting_images
325
-
326
-
327
- def extract_images_from_msg_list(msg_list):
328
- all_images = []
329
- for msg in msg_list:
330
- for c_ in msg["content"]:
331
- if isinstance(c_, Image.Image):
332
- all_images.append(c_)
333
- return all_images
334
-
335
-
336
- @spaces.GPU(duration=30, queue=False)
337
- def model_inference(
338
- user_prompt,
339
- chat_history,
340
- model_selector,
341
- decoding_strategy,
342
- temperature,
343
- max_new_tokens,
344
- repetition_penalty,
345
- top_p,
346
- ):
347
- if user_prompt["text"].strip() == "" and not user_prompt["files"]:
348
- gr.Error("Please input a query and optionally an image(s).")
349
-
350
- if user_prompt["text"].strip() == "" and user_prompt["files"]:
351
- gr.Error("Please input a text query along with the image(s).")
352
-
353
- streamer = TextIteratorStreamer(
354
- PROCESSOR.tokenizer,
355
- skip_prompt=True,
356
- timeout=120.0,
357
- )
358
-
359
- generation_args = {
360
- "max_new_tokens": max_new_tokens,
361
- "repetition_penalty": repetition_penalty,
362
- "streamer": streamer,
363
- }
364
-
365
- assert decoding_strategy in [
366
- "Greedy",
367
- "Top P Sampling",
368
- ]
369
- if decoding_strategy == "Greedy":
370
- generation_args["do_sample"] = False
371
- elif decoding_strategy == "Top P Sampling":
372
- generation_args["temperature"] = temperature
373
- generation_args["do_sample"] = True
374
- generation_args["top_p"] = top_p
375
-
376
- # Creating model inputs
377
- (
378
- resulting_text,
379
- resulting_images,
380
- ) = format_user_prompt_with_im_history_and_system_conditioning(
381
- user_prompt=user_prompt,
382
- chat_history=chat_history,
383
- )
384
- prompt = PROCESSOR.apply_chat_template(resulting_text, add_generation_prompt=True)
385
- inputs = PROCESSOR(
386
- text=prompt,
387
- images=resulting_images if resulting_images else None,
388
- return_tensors="pt",
389
- )
390
- inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
391
- generation_args.update(inputs)
392
-
393
- thread = Thread(
394
- target=MODELS[model_selector].generate,
395
- kwargs=generation_args,
396
- )
397
- thread.start()
398
-
399
- print("Start generating")
400
- acc_text = ""
401
- for text_token in streamer:
402
- time.sleep(0.01)
403
- acc_text += text_token
404
- if acc_text.endswith("<end_of_utterance>"):
405
- acc_text = acc_text[:-18]
406
- yield acc_text
407
-
408
-
409
- FEATURES = datasets.Features(
410
- {
411
- "model_selector": datasets.Value("string"),
412
- "images": datasets.Sequence(datasets.Image(decode=True)),
413
- "conversation": datasets.Sequence({"User": datasets.Value("string"), "Assistant": datasets.Value("string")}),
414
- "decoding_strategy": datasets.Value("string"),
415
- "temperature": datasets.Value("float32"),
416
- "max_new_tokens": datasets.Value("int32"),
417
- "repetition_penalty": datasets.Value("float32"),
418
- "top_p": datasets.Value("int32"),
419
- }
420
- )
421
-
422
-
423
- # Hyper-parameters for generation
424
- max_new_tokens = gr.Slider(
425
- minimum=2048,
426
- maximum=16000,
427
- value=4096,
428
- step=64,
429
- interactive=True,
430
- label="Maximum number of new tokens to generate",
431
- )
432
- repetition_penalty = gr.Slider(
433
- minimum=0.01,
434
- maximum=5.0,
435
- value=1,
436
- step=0.01,
437
- interactive=True,
438
- label="Repetition penalty",
439
- info="1.0 is equivalent to no penalty",
440
- )
441
- decoding_strategy = gr.Radio(
442
- [
443
- "Greedy",
444
- "Top P Sampling",
445
- ],
446
- value="Top P Sampling",
447
- label="Decoding strategy",
448
- interactive=True,
449
- info="Higher values are equivalent to sampling more low-probability tokens.",
450
- )
451
- temperature = gr.Slider(
452
- minimum=0.0,
453
- maximum=2.0,
454
- value=0.5,
455
- step=0.05,
456
- visible=True,
457
- interactive=True,
458
- label="Sampling temperature",
459
- info="Higher values will produce more diverse outputs.",
460
- )
461
- top_p = gr.Slider(
462
- minimum=0.01,
463
- maximum=0.99,
464
- value=0.9,
465
- step=0.01,
466
- visible=True,
467
- interactive=True,
468
- label="Top P",
469
- info="Higher values are equivalent to sampling more low-probability tokens.",
470
- )
471
-
472
-
473
- chatbot = gr.Chatbot(
474
- label="OpnGPT-4o-Chatty",
475
- avatar_images=[None, BOT_AVATAR],
476
- show_copy_button=True,
477
- likeable=True,
478
- layout="panel"
479
- )
480
-
481
- output=gr.Textbox(label="Prompt")
482
-
483
- with gr.Blocks(
484
- fill_height=True,
485
- css=""".gradio-container .avatar-container {height: 40px width: 40px !important;} #duplicate-button {margin: auto; color: white; background: #f1a139; border-radius: 100vh; margin-top: 2px; margin-bottom: 2px;}""",
486
- ) as chat:
487
-
488
- gr.Markdown("# Image Chat, Image Generation, Image classification and Normal Chat")
489
- with gr.Row(elem_id="model_selector_row"):
490
- model_selector = gr.Dropdown(
491
- choices=MODELS.keys(),
492
- value=list(MODELS.keys())[0],
493
- interactive=True,
494
- show_label=False,
495
- container=False,
496
- label="Model",
497
- visible=False,
498
- )
499
-
500
- decoding_strategy.change(
501
- fn=lambda selection: gr.Slider(
502
- visible=(
503
- selection
504
- in [
505
- "contrastive_sampling",
506
- "beam_sampling",
507
- "Top P Sampling",
508
- "sampling_top_k",
509
- ]
510
- )
511
- ),
512
- inputs=decoding_strategy,
513
- outputs=temperature,
514
- )
515
- decoding_strategy.change(
516
- fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
517
- inputs=decoding_strategy,
518
- outputs=top_p,
519
- )
520
-
521
- gr.ChatInterface(
522
- fn=model_inference,
523
- chatbot=chatbot,
524
- examples=EXAMPLES,
525
- multimodal=True,
526
- cache_examples=False,
527
- additional_inputs=[
528
- model_selector,
529
- decoding_strategy,
530
- temperature,
531
- max_new_tokens,
532
- repetition_penalty,
533
- top_p,
534
- ],
535
- )
536
-
537
- with gr.Blocks() as voice:
538
- with gr.Row():
539
- select = gr.Dropdown([ 'Nous Hermes Mixtral 8x7B DPO', 'Mixtral 8x7B','StarChat2 15b','Mistral 7B v0.3','Phi 3 mini', 'Zephyr 7b' ], value="Mistral 7B v0.3", label="Select Model")
540
- seed = gr.Slider(
541
- label="Seed",
542
- minimum=0,
543
- maximum=999999,
544
- step=1,
545
- value=0,
546
- visible=False
547
- )
548
- input = gr.Audio(label="User", sources="microphone", type="filepath", waveform_options=False)
549
- output = gr.Audio(label="AI", type="filepath",
550
- interactive=False,
551
- autoplay=True,
552
- elem_classes="audio")
553
- gr.Interface(
554
- fn=respond,
555
- inputs=[input, select,seed],
556
- outputs=[output], api_name="translate", live=True)
557
-
558
- with gr.Blocks() as livechat:
559
- gr.Interface(
560
- fn=videochat,
561
- inputs=[gr.Image(type="pil",sources="webcam", label="Upload Image"), gr.Textbox(label="Prompt", value="what he is doing")],
562
- outputs=gr.Textbox(label="Answer")
563
- )
564
-
565
- with gr.Blocks() as instant:
566
- gr.HTML("<iframe src='https://kingnish-sdxl-flash.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
567
-
568
- with gr.Blocks() as dalle:
569
- gr.HTML("<iframe src='https://ehristoforu-dalle-3-xl-lora-v2.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
570
-
571
- with gr.Blocks() as image:
572
- gr.Markdown("""### More models are coming""")
573
- gr.TabbedInterface([ instant, dalle], ['Instant🖼️','Powerful🖼️'])
574
-
575
-
576
-
577
-
578
- with gr.Blocks() as instant2:
579
- gr.HTML("<iframe src='https://kingnish-instant-video.hf.space' width='100%' height='3000px' style='border-radius: 8px;'></iframe>")
580
-
581
- with gr.Blocks() as video:
582
- gr.Markdown("""More Models are coming""")
583
- gr.TabbedInterface([ instant2], ['Instant🎥'])
584
-
585
- with gr.Blocks(theme=theme, title="OpenGPT 4o DEMO") as demo:
586
- gr.Markdown("# OpenGPT 4o")
587
- gr.TabbedInterface([chat, voice, livechat, image, video], ['💬 SuperChat','🗣️ Voice Chat','📸 Live Chat', '🖼️ Image Engine', '🎥 Video Engine'])
588
-
589
- demo.queue(max_size=300)
590
- demo.launch()
 
1
+ import gradio as gr
2
+ import os
3
+ import spaces
4
+ from transformers import GemmaTokenizer, AutoModelForCausalLM
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
+ from threading import Thread
7
+
8
+ # Set an environment variable
9
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
+
11
+
12
+ DESCRIPTION = '''
13
+ <div>
14
+ <h1 style="text-align: center;">Mistral 7B Instruct v0.3</h1>
15
+ <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3"><b>mistralai/Mistral-7B-Instruct-v0.3</b></a>. The Mistral-7B-Instruct-v0.3 Large Language Model (LLM) is an instruct fine-tuned version of the Mistral-7B-v0.3, which is a Mistral-7B-v0.2 with extended vocabulary. Feel free to play with it, or duplicate to run privately!</p>
16
+ <p>🔎 For more details about the release and how to use the model with <code>transformers</code>, visit the model-card linked above.</p>
17
+ <p>🦕 The Instruct model - Has Extended vocabulary to 32768. Supports v3 Tokenizer. Supports function calling.</p>
18
+ </div>
19
+ '''
20
+
21
+
22
+ PLACEHOLDER = """
23
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
24
+ <img src="https://cdn-thumbnails.huggingface.co/social-thumbnails/models/mistralai/Mistral-7B-Instruct-v0.3.png" style="width: 70%; max-width: 550px; height: auto; opacity: 0.55; ">
25
+ <p style="font-size: 20px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
26
+ </div>
27
+ """
28
+
29
+
30
+ css = """
31
+ h1 {
32
+ text-align: center;
33
+ display: block;
34
+ }
35
+ #duplicate-button {
36
+ margin: auto;
37
+ color: white;
38
+ background: #1565c0;
39
+ border-radius: 100vh;
40
+ }
41
+ """
42
+
43
+ # Load the tokenizer and model
44
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")
45
+ model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", device_map="auto")
46
+ terminators = [
47
+ tokenizer.eos_token_id,
48
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
49
+ ]
50
+
51
+ @spaces.GPU(duration=120)
52
+ def chat_mistral7b_v0dot3(message: str,
53
+ history: list,
54
+ temperature: float,
55
+ max_new_tokens: int
56
+ ) -> str:
57
+ """
58
+ Generate a streaming response using the mistralai/Mistral-7B-Instruct-v0.3 model.
59
+ Args:
60
+ message (str): The input message.
61
+ history (list): The conversation history used by ChatInterface.
62
+ temperature (float): The temperature for generating the response.
63
+ max_new_tokens (int): The maximum number of new tokens to generate.
64
+ Returns:
65
+ str: The generated response.
66
+ """
67
+ conversation = []
68
+ for user, assistant in history:
69
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
70
+ conversation.append({"role": "user", "content": message})
71
+
72
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
73
+
74
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
75
+
76
+ generate_kwargs = dict(
77
+ input_ids= input_ids,
78
+ streamer=streamer,
79
+ max_new_tokens=max_new_tokens,
80
+ do_sample=True,
81
+ temperature=temperature,
82
+ eos_token_id=terminators,
83
+ )
84
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
85
+ if temperature == 0:
86
+ generate_kwargs['do_sample'] = False
87
+
88
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
89
+ t.start()
90
+
91
+ outputs = []
92
+ for text in streamer:
93
+ outputs.append(text)
94
+ #print(outputs)
95
+ yield "".join(outputs)
96
+
97
+
98
+ # Gradio block
99
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
100
+
101
+ with gr.Blocks(fill_height=True, css=css) as demo:
102
+
103
+ gr.Markdown(DESCRIPTION)
104
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
105
+ gr.ChatInterface(
106
+ fn=chat_mistral7b_v0dot3,
107
+ chatbot=chatbot,
108
+ fill_height=True,
109
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
110
+ additional_inputs=[
111
+ gr.Slider(minimum=0,
112
+ maximum=1,
113
+ step=0.1,
114
+ value=0.95,
115
+ label="Temperature",
116
+ render=False),
117
+ gr.Slider(minimum=128,
118
+ maximum=4096,
119
+ step=1,
120
+ value=512,
121
+ label="Max new tokens",
122
+ render=False ),
123
+ ],
124
+ examples=[
125
+ ['How to setup a human base on Mars? Give short answer.'],
126
+ ['Explain theory of relativity to me like I’m 8 years old.'],
127
+ ['What is 9,000 * 9,000?'],
128
+ ['Write a pun-filled happy birthday message to my friend Alex.'],
129
+ ['Justify why a penguin might make a good king of the jungle.']
130
+ ],
131
+ cache_examples=False,
132
+ )
133
+
134
+
135
+ if __name__ == "__main__":
136
+ demo.launch()