KingNish commited on
Commit
07d03e7
1 Parent(s): 5a304f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +403 -47
app.py CHANGED
@@ -1,75 +1,431 @@
1
- import re
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
 
 
 
 
3
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
 
4
 
5
- client2 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
 
 
 
 
6
 
7
- system_instructions2 = "[SYSTEM] You are the Best AI, you can solve complex problems you answer in short , simple and easy language.[USER]"
8
 
9
- def text(prompt):
 
 
10
  generate_kwargs = dict(
11
- temperature=0.5,
12
- max_new_tokens=5,
13
- top_p=0.7,
14
- repetition_penalty=1.2,
15
  do_sample=True,
16
  seed=42,
17
  )
18
-
19
- formatted_prompt = system_instructions2 + prompt + "[BOT]"
20
- stream = client2.text_generation(
21
  formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
22
  output = ""
23
-
24
  for response in stream:
25
  if not response.token.text == "</s>":
26
  output += response.token.text
27
 
28
- return output
29
 
 
 
 
 
 
 
 
 
30
 
31
- client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
 
 
 
 
 
 
 
 
 
 
32
 
33
- system_instructions = "[SYSTEM] You will be provided with text, and your task is to classify task tasks are (text generation, image generation, tts) answer with only task type that prompt user give, do not say anything else and stop as soon as possible. Example: User- What is friction , BOT - text generation [USER]"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- def classify_task(prompt):
36
- generate_kwargs = dict(
37
- temperature=0.5,
38
- max_new_tokens=5,
39
- top_p=0.7,
40
- repetition_penalty=1.2,
41
- do_sample=True,
42
- seed=42,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  )
44
 
45
- formatted_prompt = system_instructions + prompt + "[BOT]"
46
- stream = client.text_generation(
47
- formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
48
- output = ""
 
49
 
50
- for response in stream:
51
- if not response.token.text == "</s>":
52
- output += response.token.text
53
- if 'text' in output.lower():
54
- user = text(prompt)
55
- elif 'image' in output.lower():
56
- return 'Image Generation'
57
- else:
58
- return 'Unknown Task'
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # Create the Gradio interface
64
- with gr.Blocks() as demo:
65
- with gr.Row():
66
- text_uesr_input = gr.Textbox(label="Enter text 📚")
67
- output = gr.Textbox(label="Translation")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  with gr.Row():
69
- translate_btn = gr.Button("Translate 🚀")
70
- translate_btn.click(fn=classify_task, inputs=text_uesr_input,
71
- outputs=output, api_name="translate_text")
 
 
 
 
 
 
 
 
 
 
72
 
73
- # Launch the app
74
- if __name__ == "__main__":
75
- demo.launch()
 
1
+ import os
2
+ import subprocess
3
+
4
+ # Install flash attention
5
+ subprocess.run(
6
+ "pip install flash-attn --no-build-isolation",
7
+ env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
8
+ shell=True,
9
+ )
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
+ from PIL import Image
21
+ import io
22
+ import datasets
23
+
24
  import gradio as gr
25
+ from transformers import AutoProcessor, TextIteratorStreamer
26
+ from transformers import Idefics2ForConditionalGeneration
27
+ import tempfile
28
+ from streaming_stt_nemo import Model
29
  from huggingface_hub import InferenceClient
30
+ import edge_tts
31
+ import asyncio
32
+
33
+ theme = gr.themes.Base(
34
+ font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif'],
35
+ )
36
+
37
+ default_lang = "en"
38
+
39
+ engines = { default_lang: Model(default_lang) }
40
 
41
+ def transcribe(audio):
42
+ lang = "en"
43
+ model = engines[lang]
44
+ text = model.stt_file(audio)[0]
45
+ return text
46
 
47
+ client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
48
 
49
+ system_instructions1 = "<s>[SYSTEM] Answer as Real Jarvis JARVIS, Made by 'Tony Stark', 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. The request asks you to provide friendly responses as if You are the character Jarvis, made by 'Tony Stark.' The expectation is that I 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]"
50
+
51
+ def model(text):
52
  generate_kwargs = dict(
53
+ temperature=0.7,
54
+ max_new_tokens=512,
55
+ top_p=0.95,
56
+ repetition_penalty=1,
57
  do_sample=True,
58
  seed=42,
59
  )
60
+
61
+ formatted_prompt = system_instructions1 + text + "[JARVIS]"
62
+ stream = client1.text_generation(
63
  formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
64
  output = ""
 
65
  for response in stream:
66
  if not response.token.text == "</s>":
67
  output += response.token.text
68
 
69
+ return output
70
 
71
+ async def respond(audio):
72
+ user = transcribe(audio)
73
+ reply = model(user)
74
+ communicate = edge_tts.Communicate(reply)
75
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
76
+ tmp_path = tmp_file.name
77
+ await communicate.save(tmp_path)
78
+ yield tmp_path
79
 
80
+ DEVICE = torch.device("cuda")
81
+ MODELS = {
82
+ "idefics2-8b-chatty": Idefics2ForConditionalGeneration.from_pretrained(
83
+ "HuggingFaceM4/idefics2-8b-chatty",
84
+ torch_dtype=torch.bfloat16,
85
+ _attn_implementation="flash_attention_2",
86
+ ).to(DEVICE),
87
+ }
88
+ PROCESSOR = AutoProcessor.from_pretrained(
89
+ "HuggingFaceM4/idefics2-8b",
90
+ )
91
 
92
+ SYSTEM_PROMPT = [
93
+ {
94
+ "role": "system",
95
+ "content": [
96
+ {
97
+ "type": "text",
98
+ "text": "The following is a conversation between Idefics2, a highly knowledgeable and intelligent visual AI assistant created by Hugging Face, referred to as Assistant, and a human user called User. In the following interactions, User and Assistant will converse in natural language, and Assistant will do its best to answer User’s questions. Assistant has the ability to perceive images and reason about them, but it cannot generate images. Assistant was built to be respectful, polite and inclusive. It knows a lot, and always tells the truth. When prompted with an image, it does not make up facts. If required you can also generate images, always generate image in this format ![](https://image.pollinations.ai/prompt/{description}?width={width}&height={height}&nologo=poll&nofeed=yes&seed={random}), where {description} is: {StyleofImage}%20{PromptifiedPrompt}%20{adjective}%20{charactersDetailed}%20{visualStyle}%20{genre}, where [random] is: Random 10-digit positive integer",
99
+ },
100
+ ],
101
+ },
102
+ {
103
+ "role": "assistant",
104
+ "content": [
105
+ {
106
+ "type": "text",
107
+ "text": "Hello, I'm Idefics2, Huggingface's latest multimodal assistant. How can I help you?",
108
+ },
109
+ ],
110
+ }
111
+ ]
112
 
113
+ BOT_AVATAR = "OpenAI_logo.png"
114
+
115
+
116
+ # Chatbot utils
117
+ def turn_is_pure_media(turn):
118
+ return turn[1] is None
119
+
120
+
121
+ def load_image_from_url(url):
122
+ with urllib.request.urlopen(url) as response:
123
+ image_data = response.read()
124
+ image_stream = io.BytesIO(image_data)
125
+ image = Image.open(image_stream)
126
+ return image
127
+
128
+
129
+ def img_to_bytes(image_path):
130
+ image = Image.open(image_path).convert(mode='RGB')
131
+ buffer = io.BytesIO()
132
+ image.save(buffer, format="JPEG")
133
+ img_bytes = buffer.getvalue()
134
+ image.close()
135
+ return img_bytes
136
+
137
+
138
+ def format_user_prompt_with_im_history_and_system_conditioning(
139
+ user_prompt, chat_history
140
+ ) -> List[Dict[str, Union[List, str]]]:
141
+ """
142
+ Produces the resulting list that needs to go inside the processor.
143
+ It handles the potential image(s), the history and the system conditionning.
144
+ """
145
+ resulting_messages = copy.deepcopy(SYSTEM_PROMPT)
146
+ resulting_images = []
147
+ for resulting_message in resulting_messages:
148
+ if resulting_message["role"] == "user":
149
+ for content in resulting_message["content"]:
150
+ if content["type"] == "image":
151
+ resulting_images.append(load_image_from_url(content["image"]))
152
+
153
+ # Format history
154
+ for turn in chat_history:
155
+ if not resulting_messages or (
156
+ resulting_messages and resulting_messages[-1]["role"] != "user"
157
+ ):
158
+ resulting_messages.append(
159
+ {
160
+ "role": "user",
161
+ "content": [],
162
+ }
163
+ )
164
+
165
+ if turn_is_pure_media(turn):
166
+ media = turn[0][0]
167
+ resulting_messages[-1]["content"].append({"type": "image"})
168
+ resulting_images.append(Image.open(media))
169
+ else:
170
+ user_utterance, assistant_utterance = turn
171
+ resulting_messages[-1]["content"].append(
172
+ {"type": "text", "text": user_utterance.strip()}
173
+ )
174
+ resulting_messages.append(
175
+ {
176
+ "role": "assistant",
177
+ "content": [{"type": "text", "text": user_utterance.strip()}],
178
+ }
179
+ )
180
+
181
+ # Format current input
182
+ if not user_prompt["files"]:
183
+ resulting_messages.append(
184
+ {
185
+ "role": "user",
186
+ "content": [{"type": "text", "text": user_prompt["text"]}],
187
+ }
188
+ )
189
+ else:
190
+ # Choosing to put the image first (i.e. before the text), but this is an arbiratrary choice.
191
+ resulting_messages.append(
192
+ {
193
+ "role": "user",
194
+ "content": [{"type": "image"}] * len(user_prompt["files"])
195
+ + [{"type": "text", "text": user_prompt["text"]}],
196
+ }
197
+ )
198
+ resulting_images.extend([Image.open(path) for path in user_prompt["files"]])
199
+
200
+ return resulting_messages, resulting_images
201
+
202
+
203
+ def extract_images_from_msg_list(msg_list):
204
+ all_images = []
205
+ for msg in msg_list:
206
+ for c_ in msg["content"]:
207
+ if isinstance(c_, Image.Image):
208
+ all_images.append(c_)
209
+ return all_images
210
+
211
+
212
+ @spaces.GPU(duration=60)
213
+ def model_inference(
214
+ user_prompt,
215
+ chat_history,
216
+ model_selector,
217
+ decoding_strategy,
218
+ temperature,
219
+ max_new_tokens,
220
+ repetition_penalty,
221
+ top_p,
222
+ ):
223
+ if user_prompt["text"].strip() == "" and not user_prompt["files"]:
224
+ gr.Error("Please input a query and optionally image(s).")
225
+
226
+ if user_prompt["text"].strip() == "" and user_prompt["files"]:
227
+ gr.Error("Please input a text query along the image(s).")
228
+
229
+ streamer = TextIteratorStreamer(
230
+ PROCESSOR.tokenizer,
231
+ skip_prompt=True,
232
+ timeout=120.0,
233
  )
234
 
235
+ generation_args = {
236
+ "max_new_tokens": max_new_tokens,
237
+ "repetition_penalty": repetition_penalty,
238
+ "streamer": streamer,
239
+ }
240
 
241
+ assert decoding_strategy in [
242
+ "Greedy",
243
+ "Top P Sampling",
244
+ ]
245
+ if decoding_strategy == "Greedy":
246
+ generation_args["do_sample"] = False
247
+ elif decoding_strategy == "Top P Sampling":
248
+ generation_args["temperature"] = temperature
249
+ generation_args["do_sample"] = True
250
+ generation_args["top_p"] = top_p
251
 
252
+ # Creating model inputs
253
+ (
254
+ resulting_text,
255
+ resulting_images,
256
+ ) = format_user_prompt_with_im_history_and_system_conditioning(
257
+ user_prompt=user_prompt,
258
+ chat_history=chat_history,
259
+ )
260
+ prompt = PROCESSOR.apply_chat_template(resulting_text, add_generation_prompt=True)
261
+ inputs = PROCESSOR(
262
+ text=prompt,
263
+ images=resulting_images if resulting_images else None,
264
+ return_tensors="pt",
265
+ )
266
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
267
+ generation_args.update(inputs)
268
 
269
+ thread = Thread(
270
+ target=MODELS[model_selector].generate,
271
+ kwargs=generation_args,
272
+ )
273
+ thread.start()
274
 
275
+ print("Start generating")
276
+ acc_text = ""
277
+ for text_token in streamer:
278
+ time.sleep(0.01)
279
+ acc_text += text_token
280
+ if acc_text.endswith("<end_of_utterance>"):
281
+ acc_text = acc_text[:-18]
282
+ yield acc_text
283
+ print("Success - generated the following text:", acc_text)
284
+ print("-----")
285
 
286
+
287
+ FEATURES = datasets.Features(
288
+ {
289
+ "model_selector": datasets.Value("string"),
290
+ "images": datasets.Sequence(datasets.Image(decode=True)),
291
+ "conversation": datasets.Sequence({"User": datasets.Value("string"), "Assistant": datasets.Value("string")}),
292
+ "decoding_strategy": datasets.Value("string"),
293
+ "temperature": datasets.Value("float32"),
294
+ "max_new_tokens": datasets.Value("int32"),
295
+ "repetition_penalty": datasets.Value("float32"),
296
+ "top_p": datasets.Value("int32"),
297
+ }
298
+ )
299
+
300
+
301
+ # Hyper-parameters for generation
302
+ max_new_tokens = gr.Slider(
303
+ minimum=512,
304
+ maximum=4096,
305
+ value=1024,
306
+ step=1,
307
+ interactive=True,
308
+ label="Maximum number of new tokens to generate",
309
+ )
310
+ repetition_penalty = gr.Slider(
311
+ minimum=0.01,
312
+ maximum=5.0,
313
+ value=1.1,
314
+ step=0.01,
315
+ interactive=True,
316
+ label="Repetition penalty",
317
+ info="1.0 is equivalent to no penalty",
318
+ )
319
+ decoding_strategy = gr.Radio(
320
+ [
321
+ "Greedy",
322
+ "Top P Sampling",
323
+ ],
324
+ value="Greedy",
325
+ label="Decoding strategy",
326
+ interactive=True,
327
+ info="Higher values is equivalent to sampling more low-probability tokens.",
328
+ )
329
+ temperature = gr.Slider(
330
+ minimum=0.0,
331
+ maximum=5.0,
332
+ value=0.4,
333
+ step=0.1,
334
+ visible=False,
335
+ interactive=True,
336
+ label="Sampling temperature",
337
+ info="Higher values will produce more diverse outputs.",
338
+ )
339
+ top_p = gr.Slider(
340
+ minimum=0.01,
341
+ maximum=0.99,
342
+ value=0.8,
343
+ step=0.01,
344
+ visible=False,
345
+ interactive=True,
346
+ label="Top P",
347
+ info="Higher values is equivalent to sampling more low-probability tokens.",
348
+ )
349
+
350
+
351
+ chatbot = gr.Chatbot(
352
+ label="Idefics2-Chatty",
353
+ avatar_images=[None, BOT_AVATAR],
354
+ height=450,
355
+ show_copy_button=True,
356
+ likeable=True,
357
+ layout="panel"
358
+ )
359
+
360
+ output=gr.Textbox(label="Prompt")
361
+
362
+ with gr.Blocks(
363
+ fill_height=True,
364
+ 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;}""",
365
+ ) as img:
366
+
367
+ gr.Markdown("# Image Chat, Image Generation, Image classification and Normal Chat")
368
+ with gr.Row(elem_id="model_selector_row"):
369
+ model_selector = gr.Dropdown(
370
+ choices=MODELS.keys(),
371
+ value=list(MODELS.keys())[0],
372
+ interactive=True,
373
+ show_label=False,
374
+ container=False,
375
+ label="Model",
376
+ visible=False,
377
+ )
378
+
379
+ decoding_strategy.change(
380
+ fn=lambda selection: gr.Slider(
381
+ visible=(
382
+ selection
383
+ in [
384
+ "contrastive_sampling",
385
+ "beam_sampling",
386
+ "Top P Sampling",
387
+ "sampling_top_k",
388
+ ]
389
+ )
390
+ ),
391
+ inputs=decoding_strategy,
392
+ outputs=temperature,
393
+ )
394
+ decoding_strategy.change(
395
+ fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
396
+ inputs=decoding_strategy,
397
+ outputs=top_p,
398
+ )
399
+
400
+ gr.ChatInterface(
401
+ fn=model_inference,
402
+ chatbot=chatbot,
403
+ multimodal=True,
404
+ cache_examples=False,
405
+ additional_inputs=[
406
+ model_selector,
407
+ decoding_strategy,
408
+ temperature,
409
+ max_new_tokens,
410
+ repetition_penalty,
411
+ top_p,
412
+ ],
413
+ )
414
+
415
+ with gr.Blocks() as voice:
416
  with gr.Row():
417
+ input = gr.Audio(label="Voice Chat", sources="microphone", type="filepath", waveform_options=False)
418
+ output = gr.Audio(label="AI", type="filepath",
419
+ interactive=False,
420
+ autoplay=True,
421
+ elem_classes="audio")
422
+ gr.Interface(
423
+ fn=respond,
424
+ inputs=[input],
425
+ outputs=[output], live=True)
426
+
427
+ with gr.Blocks(theme=theme, css="footer {visibility: hidden}textbox{resize:none}", title="GPT 4o DEMO") as demo:
428
+ gr.TabbedInterface([voice, img], ['🗣️ Voice Chat', '💬 SuperChat'])
429
+
430
 
431
+ demo.launch()